Documentation
¶
Overview ¶
Package sidekiq is a pure-Go (no cgo) reimplementation of the core engine of the Ruby Sidekiq background-job framework: the client that enqueues jobs, the job/worker option model, the scheduled-job poller and a basic server/processor — backed by Redis.
It writes the exact same Redis data structures a real Sidekiq process does, so a real Sidekiq server can consume jobs this package enqueues and vice versa. The job payload is the documented Sidekiq JSON hash (class, args, queue, jid, created_at, enqueued_at, retry) LPUSH'd to queue:<name> with the queue name SADD'd to the queues set; scheduled jobs are ZADD'd to the schedule sorted-set keyed by their run-at timestamp; retries land in the retry sorted-set and exhausted jobs in the dead set — all byte-compatible with Sidekiq.
The only piece that is inherently interpreter-dependent is the body of a job (a Worker's perform method, which is Ruby). That is modelled as an injected host seam — a Perform function — mirroring the go-ruby-* design: the deterministic enqueue/schedule/retry machinery lives here in pure Go, and the host (for example go-embedded-ruby) supplies the perform bodies. The Redis socket itself is likewise a seam: the caller supplies a go-redis client.
Time, randomness (the 24-hex jid) and retry jitter are all injectable so the whole engine runs deterministically under test with no real Redis server, no sleeps and no background goroutines.
Index ¶
- Constants
- type ClassedError
- type Client
- func (c *Client) EnqueueScheduledJobs(ctx context.Context) (int, error)
- func (c *Client) NewProcessor(perform Perform, queues ...string) *Processor
- func (c *Client) Push(ctx context.Context, item Item) (string, error)
- func (c *Client) PushBulk(ctx context.Context, item Item, argsList [][]any) ([]string, error)
- func (c *Client) Stats(ctx context.Context) (Stats, error)
- func (c *Client) Worker(class string, opts WorkerOptions) *Worker
- type Item
- type Option
- type Perform
- type Processor
- type Stats
- type Worker
- type WorkerOptions
Constants ¶
const DefaultMaxRetries = 25
DefaultMaxRetries is the number of retry attempts Sidekiq makes before a job is moved to the dead set when its retry option is true (Sidekiq's DEFAULT_MAX_RETRY_ATTEMPTS).
const DefaultQueue = "default"
DefaultQueue is the queue a job lands on when none is specified, matching Sidekiq's default.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ClassedError ¶
type ClassedError interface {
error
// ErrorClass returns the Ruby exception class name, e.g. "RuntimeError".
ErrorClass() string
}
ClassedError lets a host carry the Ruby exception class name of a failed job through the Go error returned by a Perform seam. When a job's perform body (Ruby) raises, the host wraps the raised exception in an error implementing this interface so the retry machinery records the true Ruby class name in the payload's error_class field, matching Sidekiq.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client enqueues jobs into Redis exactly as Sidekiq's client does. It owns no socket: the caller supplies a go-redis client (a redis.Cmdable, which a *redis.Client satisfies), mirroring the go-ruby-* host-seam design. Time, randomness and retry jitter are injectable via Option for deterministic testing.
A Client is safe for concurrent use to the same extent its underlying go-redis client is.
func New ¶
New builds a Client over the supplied go-redis client. With no options it is production-ready: real time, crypto/rand job ids and randomised retry jitter.
func (*Client) EnqueueScheduledJobs ¶
EnqueueScheduledJobs moves every job in the schedule and retry sorted-sets whose run-at time is now due (score <= now) onto its target queue. It is the pure-Go model of Sidekiq's Scheduled::Poller#enqueue: a host calls it on whatever cadence it likes, and it advances deterministically against the Client's injected clock — no sleeps, no background goroutine. It returns the number of jobs enqueued.
func (*Client) NewProcessor ¶
NewProcessor builds a Processor that fetches from the given queues (in priority order, highest first) and runs jobs through perform. With no queues it defaults to DefaultQueue. The BRPOP wait defaults to one second and can be tuned with Processor.SetTimeout.
func (*Client) Push ¶
Push enqueues a single job and returns its jid. A job with a zero At is pushed onto its queue immediately; a job with a non-zero At is added to the schedule set to run later. This mirrors Sidekiq::Client#push.
func (*Client) PushBulk ¶
PushBulk enqueues many jobs that share a class/queue/retry policy, one per entry in argsList, and returns their jids in order. It mirrors Sidekiq::Client#push_bulk. A non-zero At schedules every job for that time.
type Item ¶
type Item struct {
// Class is the worker class name whose perform will run.
Class string
// Args are the positional arguments passed to perform.
Args []any
// Queue is the target queue; empty means [DefaultQueue].
Queue string
// Retry is the retry policy: nil (default true), a bool, or an int max
// attempt count.
Retry any
// At, when non-zero, schedules the job to run at that time (ZADD to the
// schedule set) instead of enqueuing it immediately.
At time.Time
// Jid is the job id; when empty a fresh 24-hex id is generated.
Jid string
}
Item describes a job to enqueue. Only Class is required; Queue defaults to DefaultQueue, Retry defaults to true, Jid is generated when empty, and a non-zero At schedules the job for that time rather than enqueuing it now.
type Option ¶
type Option func(*Client)
Option configures a Client. All the injectable seams (clock, randomness, retry jitter) default to production values, so New(rdb) yields a fully working client; tests override them for determinism.
func WithClock ¶
WithClock injects the time source used for created_at / enqueued_at stamps, schedule scoring and retry timing. It defaults to time.Now.
func WithJitter ¶
WithJitter injects the retry-jitter function. Given the current retry count it returns an added delay in seconds; Sidekiq's default is a random value in [0, 30*(count+1)). It defaults to the randomised production jitter.
func WithMaxRetries ¶
WithMaxRetries sets the default maximum retry attempts for jobs whose retry option is true. It defaults to DefaultMaxRetries.
type Perform ¶
Perform is the host seam that runs a job's body. Given a worker class name and its decoded arguments it executes the work and returns nil on success or an error on failure. This is the one inherently interpreter-dependent piece of Sidekiq — a worker's perform method is Ruby — so it is injected: a host such as go-embedded-ruby dispatches (class, args) to the matching Ruby perform body. To record the true Ruby exception class on a retry, the returned error may implement ClassedError.
type Processor ¶
type Processor struct {
// contains filtered or unexported fields
}
Processor is the pure-Go model of a Sidekiq server process: it fetches a job off a queue, decodes it and invokes the Perform seam, then does Sidekiq's success/failure bookkeeping (processed/failed counters, retry scheduling and the dead set). It spawns no goroutines; a host drives it by calling Processor.ProcessOne or Processor.Run.
func (*Processor) ProcessOne ¶
ProcessOne fetches at most one job (BRPOP across the configured queues, highest priority first) and runs it. It reports whether a job was processed; a false result with a nil error means the fetch timed out with no work. Any error from the job's perform body is handled internally (retry or dead set) and is not returned; the returned error is reserved for Redis/transport failures.
func (*Processor) Run ¶
Run drives the processor until ctx is cancelled, fetching and running jobs in a loop. It returns ctx.Err() when the context is done, or any Redis/transport error encountered. It runs entirely on the calling goroutine — no background goroutines are started.
func (*Processor) SetTimeout ¶
SetTimeout sets the BRPOP block duration used when waiting for a job.
type Stats ¶
type Stats struct {
// Processed is the lifetime count of processed jobs (stat:processed).
Processed int64
// Failed is the lifetime count of failed jobs (stat:failed).
Failed int64
// Enqueued is the total number of jobs waiting across all known queues.
Enqueued int64
// Scheduled, Retries and Dead are the cardinalities of the schedule, retry
// and dead sorted-sets.
Scheduled int64
Retries int64
Dead int64
}
Stats is a snapshot of the engine's global counters and set sizes, modelling Sidekiq::Stats: lifetime processed/failed totals, the number of jobs waiting across all queues, and the sizes of the schedule, retry and dead sets.
type Worker ¶
type Worker struct {
// contains filtered or unexported fields
}
Worker binds a worker class name and its options to a Client, exposing the familiar perform_async / perform_in / perform_at enqueue methods. It is the Go analogue of a class that includes Sidekiq::Job and calls sidekiq_options.
func (*Worker) PerformAsync ¶
PerformAsync enqueues the job to run now (Sidekiq's perform_async) and returns its jid.
type WorkerOptions ¶
type WorkerOptions struct {
// Queue is the queue jobs of this worker run on; empty means [DefaultQueue].
Queue string
// Retry is the retry policy: nil (default true), a bool, or an int max
// attempt count, matching sidekiq_options retry:.
Retry any
}
WorkerOptions models a worker's sidekiq_options declaration: the per-class defaults applied to every job it enqueues. A zero value means "use the engine defaults" (queue "default", retry true).
