Documentation
¶
Overview ¶
Package bullmq is the official Go implementation of BullMQ, the job queue for Redis and PostgreSQL.
Jobs are fully interoperable with the Node.js, Python, Elixir, PHP, Rust and .NET ports: every state transition runs the same shared Lua scripts (Redis) or SQL (PostgreSQL), so a queue may be produced by one language and consumed by another.
Backends ¶
Queue, Worker, QueueEvents and FlowProducer only depend on the Backend interface, and this package imports no datastore driver. The datastore is chosen with the required Backend option, a BackendFactory:
- redisbackend.New, in package github.com/taskforcesh/bullmq-go/redisbackend, for Redis. Its Options hold the address, credentials, the key prefix ("bull" by default) or an existing go-redis client.
- postgresbackend.New, in package github.com/taskforcesh/bullmq-go/postgresbackend, for PostgreSQL. Its Options hold the connection string or pgxpool pool, the schema ("bullmq" by default, migrated on first use) and the pool size.
A constructor called without a Backend returns a *ConfigError.
Adding and processing jobs ¶
backend := redisbackend.New(redisbackend.Options{Addr: "127.0.0.1:6379"})
queue, err := bullmq.NewQueue("emails", &bullmq.QueueOptions{Backend: backend})
if err != nil {
return err
}
defer queue.Close()
if _, err := queue.Add(ctx, "welcome", payload, nil); err != nil {
return err
}
worker, err := bullmq.NewWorker("emails", func(ctx context.Context, job *bullmq.Job) (any, error) {
var p Payload
if err := job.DecodeData(&p); err != nil {
return nil, bullmq.NewUnrecoverableError("invalid payload: %v", err)
}
return send(ctx, p)
}, &bullmq.WorkerOptions{Backend: backend, Concurrency: 10})
if err != nil {
return err
}
defer worker.Close()
return worker.Run(ctx)
A Processor returns the job's result, stored as JSON, or an error that fails the attempt; the job is retried while JobOptions.Attempts remain, after its Backoff. Each processing slot finishes its job and fetches the next one in the same backend call, so a busy worker needs about one round trip per job whatever its concurrency.
Stopping a worker ¶
Worker.Close is a graceful shutdown: the worker stops fetching and waits for the jobs in flight. Cancelling the context passed to Worker.Run stops it immediately: the processors' contexts are cancelled, and the jobs they were running stay active, without using up an attempt, until the stalled check of a running worker moves them back to wait. Close must still be called to release the connections. Worker.CancelJob cancels the context of one job, which then fails with the given reason; context.Cause tells a processor why its context was cancelled (ErrJobCancelled, ErrLockLost or the cause of the Run context).
Events ¶
Worker.Events publishes lifecycle events on a buffered channel that drops events when the reader falls behind (Worker.DroppedEvents counts them); WorkerOptions.OnEvent receives every event synchronously. QueueEvents reads the event stream shared by every worker of a queue, in any language.
Flows and job schedulers ¶
FlowProducer adds trees of jobs whose parents wait for their children. Queue.UpsertJobScheduler creates job schedulers, which repeat a job on a cron pattern, evaluated as cron-parser does in Node.js, or at a fixed interval.
The README of the golang directory of the BullMQ repository is the user guide, and FEATURE_PARITY.md lists what is implemented relative to the Node.js reference implementation.
Index ¶
- Constants
- Variables
- func Bool(b bool) *bool
- func Int(n int) *int
- func Int64(n int64) *int64
- func IsUnrecoverable(err error) bool
- func NewUnrecoverableError(format string, args ...any) error
- type Backend
- type BackendFactory
- type BackendOptions
- type Backoff
- type BackoffType
- type ConfigError
- type DeduplicationOptions
- type Dependencies
- type DependenciesOptions
- type DependencyCounts
- type DependencyPage
- type Event
- type EventType
- type FailureInfo
- type FetchResult
- type FinishOptions
- type FinishResult
- type FlowEntry
- type FlowGetOptions
- type FlowJob
- type FlowOpts
- type FlowProducer
- func (fp *FlowProducer) Add(ctx context.Context, flow FlowJob, opts *FlowOpts) (*JobNode, error)
- func (fp *FlowProducer) AddBulk(ctx context.Context, flows []FlowJob) ([]*JobNode, error)
- func (fp *FlowProducer) Backend() Backend
- func (fp *FlowProducer) Close() error
- func (fp *FlowProducer) GetFlow(ctx context.Context, opts FlowGetOptions) (*JobNode, error)
- type FlowProducerOptions
- type FlowQueueOptions
- type Job
- func (j *Job) ChangeDelay(ctx context.Context, delay time.Duration) error
- func (j *Job) ChangePriority(ctx context.Context, priority int64, lifo bool) error
- func (j *Job) ChildrenValues(ctx context.Context) (map[string]json.RawMessage, error)
- func (j *Job) DecodeChildrenValues(ctx context.Context, out any) error
- func (j *Job) DecodeData(out any) error
- func (j *Job) DecodeReturnValue(out any) error
- func (j *Job) Dependencies(ctx context.Context, opts *DependenciesOptions) (*Dependencies, error)
- func (j *Job) DependenciesCount(ctx context.Context) (DependencyCounts, error)
- func (j *Job) Discard()
- func (j *Job) Discarded() bool
- func (j *Job) ExtendLock(ctx context.Context, duration time.Duration) error
- func (j *Job) FailedChildrenValues(ctx context.Context) (map[string]string, error)deprecated
- func (j *Job) IgnoredChildrenFailures(ctx context.Context) (map[string]string, error)
- func (j *Job) IsCompleted(ctx context.Context) (bool, error)
- func (j *Job) IsFailed(ctx context.Context) (bool, error)
- func (j *Job) Log(ctx context.Context, message string) (int64, error)
- func (j *Job) Logs(ctx context.Context, start, end int64) ([]string, int64, error)
- func (j *Job) MoveToCompleted(ctx context.Context, result any, token string, fetchNext bool) (*Job, error)
- func (j *Job) MoveToDelayed(ctx context.Context, delay time.Duration) error
- func (j *Job) MoveToFailed(ctx context.Context, cause error, token string, fetchNext bool) (*Job, error)
- func (j *Job) MoveToWait(ctx context.Context) error
- func (j *Job) MoveToWaitingChildren(ctx context.Context, child *ParentKeys) (bool, error)
- func (j *Job) Promote(ctx context.Context) error
- func (j *Job) Remove(ctx context.Context, removeChildren bool) error
- func (j *Job) RemoveChildDependency(ctx context.Context) (bool, error)
- func (j *Job) RemoveDeduplicationKey(ctx context.Context) (bool, error)
- func (j *Job) RemoveUnprocessedChildren(ctx context.Context) error
- func (j *Job) Retry(ctx context.Context, state JobState, opts *RetryOptions) error
- func (j *Job) State(ctx context.Context) (JobState, error)
- func (j *Job) Token() string
- func (j *Job) UpdateData(ctx context.Context, data any) error
- func (j *Job) UpdateProgress(ctx context.Context, progress any) error
- type JobCounts
- type JobLock
- type JobNode
- type JobOptions
- type JobRecord
- type JobScheduler
- type JobSchedulerNext
- type JobSchedulerTemplate
- type JobSpec
- type JobState
- type JobTemplate
- type Metrics
- type MetricsOptions
- type MoveToActiveOptions
- type MoveToDelayedOptions
- type NewJob
- type NewJobScheduler
- type ObliterateOptions
- type ParentKeys
- type ParentOptions
- type Processor
- type Progress
- type Queue
- func (q *Queue) Add(ctx context.Context, name string, data any, opts *JobOptions) (*Job, error)
- func (q *Queue) AddBulk(ctx context.Context, specs []JobSpec) ([]*Job, error)
- func (q *Queue) Backend() Backend
- func (q *Queue) Clean(ctx context.Context, grace time.Duration, limit int64, state JobState) ([]string, error)
- func (q *Queue) Close() error
- func (q *Queue) Count(ctx context.Context) (int64, error)
- func (q *Queue) CountsPerPriority(ctx context.Context, priorities ...int64) (map[int64]int64, error)
- func (q *Queue) DeduplicationJobID(ctx context.Context, dedupID string) (string, error)
- func (q *Queue) DelayedCount(ctx context.Context, before time.Time) (int64, error)
- func (q *Queue) Drain(ctx context.Context, delayed bool) error
- func (q *Queue) GlobalConcurrency(ctx context.Context) (*int64, error)
- func (q *Queue) GlobalRateLimit(ctx context.Context) (*RateLimiter, error)
- func (q *Queue) IsMaxed(ctx context.Context) (bool, error)
- func (q *Queue) IsPaused(ctx context.Context) (bool, error)
- func (q *Queue) Job(ctx context.Context, jobID string) (*Job, error)
- func (q *Queue) JobCounts(ctx context.Context, states ...JobState) (JobCounts, error)
- func (q *Queue) JobIDs(ctx context.Context, start, end int64, asc bool, states ...JobState) ([]string, error)
- func (q *Queue) JobScheduler(ctx context.Context, id string) (*JobScheduler, error)
- func (q *Queue) JobSchedulers(ctx context.Context, start, end int64, asc bool) ([]*JobScheduler, error)
- func (q *Queue) JobSchedulersCount(ctx context.Context) (int64, error)
- func (q *Queue) JobState(ctx context.Context, jobID string) (JobState, error)
- func (q *Queue) Jobs(ctx context.Context, start, end int64, asc bool, states ...JobState) ([]*Job, error)
- func (q *Queue) Meta(ctx context.Context) (*QueueMeta, error)
- func (q *Queue) Metrics(ctx context.Context, state JobState, start, end int64) (*Metrics, error)
- func (q *Queue) Name() string
- func (q *Queue) Obliterate(ctx context.Context, opts *ObliterateOptions) error
- func (q *Queue) Pause(ctx context.Context) error
- func (q *Queue) PromoteJobs(ctx context.Context, count int64) error
- func (q *Queue) RateLimitTTL(ctx context.Context, maxJobs int64) (int64, error)
- func (q *Queue) Remove(ctx context.Context, jobID string, removeChildren bool) (bool, error)
- func (q *Queue) RemoveDeduplicationKey(ctx context.Context, dedupID string) (bool, error)
- func (q *Queue) RemoveGlobalConcurrency(ctx context.Context) error
- func (q *Queue) RemoveGlobalRateLimit(ctx context.Context) error
- func (q *Queue) RemoveJobScheduler(ctx context.Context, id string) (bool, error)
- func (q *Queue) Resume(ctx context.Context) error
- func (q *Queue) RetryJobs(ctx context.Context, opts *RetryJobsOptions) error
- func (q *Queue) SetGlobalConcurrency(ctx context.Context, max int64) error
- func (q *Queue) SetGlobalRateLimit(ctx context.Context, max int64, duration time.Duration) error
- func (q *Queue) TrimEvents(ctx context.Context, maxLength int64) (int64, error)
- func (q *Queue) UpsertJobScheduler(ctx context.Context, id string, repeat RepeatOptions, template *JobTemplate) (*Job, error)
- func (q *Queue) Version(ctx context.Context) (string, error)
- func (q *Queue) Workers(ctx context.Context) ([]WorkerInfo, error)
- type QueueEvent
- type QueueEvents
- type QueueEventsOptions
- type QueueEventsProducer
- type QueueEventsProducerOptions
- type QueueMeta
- type QueueOptions
- type RateLimiter
- type RemoveOnFinish
- type RepeatOptions
- type RepeatStrategy
- type RetryJobsOptions
- type RetryOptions
- type ScriptError
- type StalledOptions
- type UnrecoverableError
- type WaitResult
- type Worker
- func (w *Worker) ActiveCount() int
- func (w *Worker) Backend() Backend
- func (w *Worker) CancelAllJobs(reason string)
- func (w *Worker) CancelJob(jobID, reason string) bool
- func (w *Worker) Close() error
- func (w *Worker) Concurrency() int
- func (w *Worker) DroppedEvents() uint64
- func (w *Worker) Events() <-chan Event
- func (w *Worker) GetNextJob(ctx context.Context, token string, block bool) (*Job, error)
- func (w *Worker) ID() string
- func (w *Worker) IsPaused() bool
- func (w *Worker) Name() string
- func (w *Worker) Pause(ctx context.Context, doNotWaitActive bool) error
- func (w *Worker) RateLimit(ctx context.Context, d time.Duration) error
- func (w *Worker) Resume()
- func (w *Worker) Run(ctx context.Context) error
- func (w *Worker) SetConcurrency(n int) error
- func (w *Worker) StartStalledCheck() error
- type WorkerInfo
- type WorkerOptions
Constants ¶
const ( ErrCodeJobNotExist = -1 ErrCodeJobLockNotExist = -2 ErrCodeJobNotInState = -3 ErrCodeJobPendingDeps = -4 ErrCodeParentJobNotExist = -5 ErrCodeJobLockMismatch = -6 ErrCodeJobHasFailedChildren = -9 )
Error codes returned by the shared Lua commands, and by the shared SQL commands on PostgreSQL (see ScriptError).
const ( ErrCodeJobBelongsToJobScheduler = -8 ErrCodeSchedulerJobIDCollision = -10 ErrCodeSchedulerJobSlotsBusy = -11 )
Script error codes of job schedulers.
const DefaultEventsMaxLen int64 = 10000
DefaultEventsMaxLen is the default QueueOptions.EventsMaxLen.
const DefaultMaxEvents int64 = 1000
DefaultMaxEvents is the maxEvents of QueueEventsProducer.PublishEvent when it is 0, as in Node.js.
const ErrCodeParentJobCannotBeReplaced = -7
ErrCodeParentJobCannotBeReplaced is the script error code returned when a job that already belongs to a parent is added under another one.
const ScriptsVersion = "6.7.10"
ScriptsVersion is the version of the Node.js BullMQ package whose Lua and SQL scripts this module embeds. Queues store it in their metadata as `bullmq:<ScriptsVersion>`, as Node's Queue does, so that dashboards enable the features of that version. Version is the version of this module.
const Version = "0.1.0"
Version is the version of this module. The release process sets it (see scripts/publishGolang.sh). Queues store ScriptsVersion in their metadata instead.
Variables ¶
var ( // ErrJobNotFound is returned when the job an operation refers to does // not exist (any longer) in the datastore. ErrJobNotFound = errors.New("bullmq: missing job key") // ErrJobLockNotExist is returned when the job lock is missing. ErrJobLockNotExist = errors.New("bullmq: missing job lock") // ErrJobNotInState is returned when a job is not in the expected state set. ErrJobNotInState = errors.New("bullmq: job is not in the expected state") // ErrJobPendingDependencies is returned when a parent still has pending children. ErrJobPendingDependencies = errors.New("bullmq: job has pending dependencies") // ErrParentJobNotExist is returned when the referenced parent job is missing. ErrParentJobNotExist = errors.New("bullmq: parent job does not exist") // ErrJobLockMismatch is returned when the lock is owned by another client. ErrJobLockMismatch = errors.New("bullmq: lock is not owned by this client") // ErrParentJobCannotBeReplaced is returned when a job that already // belongs to a parent is added again under another one. ErrParentJobCannotBeReplaced = errors.New("bullmq: the parent of a job cannot be replaced") // ErrJobHasFailedChildren is returned when a parent cannot complete because a child failed. ErrJobHasFailedChildren = errors.New("bullmq: job has failed children") // ErrJobBelongsToJobScheduler is returned when removing the pending job // of a job scheduler, which only RemoveJobScheduler may remove. ErrJobBelongsToJobScheduler = errors.New("bullmq: job belongs to a job scheduler and cannot be removed directly") // ErrSchedulerJobIDCollision is returned when the job of a scheduler's // next iteration already exists. ErrSchedulerJobIDCollision = errors.New("bullmq: cannot create job scheduler iteration, job id already exists") // ErrSchedulerJobSlotsBusy is returned when the jobs of the next // iterations of an Every scheduler already exist. ErrSchedulerJobSlotsBusy = errors.New("bullmq: cannot create job scheduler iteration, current and next time slots already have jobs") // ErrJobLocked is returned by Job.Remove when the job (or a dependency) is // currently locked by another worker and therefore cannot be removed. ErrJobLocked = errors.New("bullmq: job is locked by another worker") // ErrWorkerClosed is returned by Worker.Run when the worker was already // run or is closed, and by Worker.Pause when the worker is closed while // Pause waits for its jobs. ErrWorkerClosed = errors.New("bullmq: worker is closed") // ErrQueueEventsClosed is returned by QueueEvents.Run when it was // already called or the listener is closed. ErrQueueEventsClosed = errors.New("bullmq: queue events is closed") // ErrNoContext is returned by the methods of a Job that reach the // datastore, such as UpdateProgress or Log, when the Job has no backend: // it was built by the caller (for example in a unit test) rather than // returned by a Queue, a Worker or a FlowProducer. ErrNoContext = errors.New("bullmq: job has no backend") // ErrDelayed is returned by a processor that has moved its job to the delayed set. ErrDelayed = errors.New("bullmq: job moved to delayed") // ErrWaitingChildren is returned by a processor that moved its job to waiting-children. ErrWaitingChildren = errors.New("bullmq: job moved to waiting children") // ErrWaiting is returned by a processor that moved its job back to wait // with Job.MoveToWait, as Node's WaitingError. ErrWaiting = errors.New("bullmq: job moved to wait") // ErrRateLimited is returned by a processor to put its job back in the // wait list without using up an attempt, because the queue is rate // limited (see Worker.RateLimit), as Node's Worker.RateLimitError does. // The worker then waits until the rate limit lifts. ErrRateLimited = errors.New("bullmq: rate limit exceeded") // ErrJobCancelled is the cause (see context.Cause) of the context of a // job cancelled with Worker.CancelJob or Worker.CancelAllJobs. The cause // reads as the cancellation reason and matches ErrJobCancelled with // errors.Is. ErrJobCancelled = errors.New("bullmq: job cancelled") // ErrLockLost is the cause (see context.Cause) of the context of a job // whose lock the worker could not renew: the job may belong to another // worker now. ErrLockLost = errors.New("bullmq: job lock lost") // ErrNotSupported is returned, wrapped, by an operation the backend // does not implement, as Node's backends throw "not implemented". ErrNotSupported = errors.New("bullmq: not supported by this backend") )
Sentinel errors returned by the library.
var AllStates = []JobState{ StateWaiting, StateActive, StateDelayed, StatePrioritized, StateCompleted, StateFailed, StateWaitingChildren, }
AllStates lists every state that can be queried through Queue.JobCounts.
var ErrFlowProducerClosed = errors.New("bullmq: flow producer is closed")
ErrFlowProducerClosed is returned by the operations of a closed FlowProducer.
var ErrLegacyRepeatableJob = errors.New("bullmq: legacy repeatable job metadata is not supported")
ErrLegacyRepeatableJob is returned for repeatable jobs created with the legacy repeat API (BullMQ v5 and earlier), which this port does not support. They must be migrated to job schedulers.
Functions ¶
func Int ¶
Int returns a pointer to n, for use with pointer-typed options fields such as WorkerOptions.MaxStalledCount.
func Int64 ¶
Int64 returns a pointer to n, for use with pointer-typed JobOptions fields such as Delay.
func IsUnrecoverable ¶
IsUnrecoverable reports whether err (or any error it wraps) is unrecoverable.
func NewUnrecoverableError ¶
NewUnrecoverableError builds an error that stops a job from being retried.
Types ¶
type Backend ¶
type Backend interface {
// Close releases every connection owned by the backend. Connections that
// were supplied by the caller are left open.
Close() error
// SetName labels the connection used for blocking reads, for
// observability. It is a no-op for backends without such a concept.
SetName(ctx context.Context, name string) error
// IsTransientError reports whether err is a connectivity or availability
// problem that is worth retrying, as opposed to a logic error.
IsTransientError(err error) bool
// QueueName returns the bare queue name.
QueueName() string
// QualifiedName returns the cross-backend logical identifier of the queue,
// used for example as a flow parent reference. Redis: `{prefix}:{queue}`;
// backends without a prefix (PostgreSQL) return the bare queue name, as
// Node does.
QualifiedName() string
// ResolveParent resolves the parent a job is added under into the
// identifiers the backend persists, without touching the datastore. It
// returns the parent reference and the backend-specific parent key
// (Redis: `{prefix}:{queue}:{id}`), matching what fetching the job later
// reports as [JobRecord.Parent] and [JobRecord.ParentKey].
ResolveParent(parent *ParentOptions) (*ParentKeys, string, error)
// ClientName builds the connection name used for worker discovery. Redis:
// `{prefix}:{base64(queue)}{suffix}`; PostgreSQL: `{queue}{suffix}`.
ClientName(suffix string) string
// AddJob adds a single job, routing it to its initial state (wait,
// delayed, prioritized, waiting-children) based on its options, and
// returns its id.
AddJob(ctx context.Context, job NewJob) (string, error)
// AddJobs adds many jobs in a single efficient operation (a Redis
// transaction, an SQL transaction, ...) and returns their ids in order.
// When the datastore rejects a job, it returns an error; as for AddFlow,
// PostgreSQL then adds none of them, while Redis keeps those it accepted.
AddJobs(ctx context.Context, jobs []NewJob) ([]string, error)
// MoveToActive atomically moves the next eligible job to active, locks
// it with opts.Token for opts.LockDuration and returns it. When no job can
// be fetched it returns a result with a nil Job and the reason, as
// described on [FetchResult]. It never blocks waiting for a job.
MoveToActive(ctx context.Context, opts MoveToActiveOptions) (*FetchResult, error)
// MoveToCompleted moves an active job owned by opts.Token to completed
// and records returnValue. When opts.FetchNext is set it then fetches the
// next job exactly as MoveToActive would, locked with the same token, and
// reports it in [FinishResult.Next].
MoveToCompleted(ctx context.Context, jobID string, returnValue []byte, opts FinishOptions) (*FinishResult, error)
// MoveToFailed moves an active job owned by opts.Token to failed and
// records failure. Fetching the next job works as in MoveToCompleted.
MoveToFailed(ctx context.Context, jobID string, failure FailureInfo, opts FinishOptions) (*FinishResult, error)
// MoveToDelayed reschedules an active job owned by token to run after
// delay. When opts.FetchNext is set it then tries to fetch the next job,
// locked with the same token, and returns the outcome; otherwise it
// returns nil. Unlike the finishing operations it may report only a
// fetched job, without the rate-limit or delayed-job hints (Redis does
// so), so a result with a nil Job means "fetch again", not "drained".
MoveToDelayed(ctx context.Context, jobID, token string, delay time.Duration, opts MoveToDelayedOptions) (*FetchResult, error)
// MoveJobFromActiveToWait puts an active job back in the wait list (or
// the prioritized set, keeping its priority) without counting an attempt,
// and releases its lock. Workers use it when a processor reports that the
// queue is rate limited. An empty token skips the lock check, as Node's
// default token "0" does. It returns the remaining rate-limit time, or 0
// when the queue is not rate limited.
MoveJobFromActiveToWait(ctx context.Context, jobID, token string) (time.Duration, error)
// MoveToWaitingChildren parks an active parent job until its children
// finish. It returns true when the job was moved and false when there were
// no pending dependencies.
MoveToWaitingChildren(ctx context.Context, jobID, token string, child *ParentKeys) (bool, error)
// RetryJob puts an active job straight back into the wait list.
RetryJob(ctx context.Context, jobID, token string, lifo bool, failure *FailureInfo) error
// RetryFinishedJob reprocesses a completed or failed job, resetting its
// attempt counters as opts asks.
RetryFinishedJob(ctx context.Context, jobID string, state JobState, lifo bool, opts RetryOptions) error
// Promote makes a delayed job available immediately.
Promote(ctx context.Context, jobID string) error
// MoveStalledJobsToWait recovers active jobs whose lock expired and returns
// the ids of the jobs that were moved.
MoveStalledJobsToWait(ctx context.Context, opts StalledOptions) ([]string, error)
// RetryFinishedJobs moves up to count jobs of state that finished at or
// before timestamp (Unix milliseconds) back to wait. It returns a cursor,
// not a count: 0 once nothing is left to move, positive while more may
// remain.
RetryFinishedJobs(ctx context.Context, state JobState, count, timestamp int64) (int64, error)
// PromoteJobs moves up to count delayed jobs back to wait. It returns a
// cursor as RetryFinishedJobs does.
PromoteJobs(ctx context.Context, count int64) (int64, error)
// Pause pauses (true) or resumes (false) the whole queue.
Pause(ctx context.Context, paused bool) error
// Drain removes waiting jobs, and delayed jobs too when delayed is true.
Drain(ctx context.Context, delayed bool) error
// CleanJobsByState removes up to limit jobs of state that are older than
// timestamp (Unix milliseconds) and returns their ids.
CleanJobsByState(ctx context.Context, state JobState, timestamp, limit int64) ([]string, error)
// Obliterate destroys the queue and its contents, removing up to count
// jobs per call. It returns a cursor: 0 once the obliteration is
// complete.
Obliterate(ctx context.Context, force bool, count int64) (int64, error)
// ExtendLock refreshes the lock of one active job. It returns
// [ErrJobLockNotExist] when the lock is gone or owned by another token.
ExtendLock(ctx context.Context, jobID, token string, duration time.Duration) error
// ExtendLocks refreshes the locks of several active jobs at once and
// returns the ids whose lock could not be extended.
ExtendLocks(ctx context.Context, locks []JobLock, duration time.Duration) ([]string, error)
// UpdateData replaces the JSON payload of a job.
UpdateData(ctx context.Context, jobID string, data []byte) error
// UpdateProgress stores a job's progress and emits the progress event.
UpdateProgress(ctx context.Context, jobID string, progress Progress) error
// AddLog appends a row to the job's log, keeping at most keepLogs rows when
// keepLogs is positive, and returns the number of rows.
AddLog(ctx context.Context, jobID, row string, keepLogs int64) (int64, error)
// GetJobLogs returns the log rows in [start, end] and the total row count.
GetJobLogs(ctx context.Context, jobID string, start, end int64) ([]string, int64, error)
// ChangeDelay changes the delay of a delayed job.
ChangeDelay(ctx context.Context, jobID string, delay time.Duration) error
// ChangePriority changes the priority (and lifo flag) of a waiting job.
ChangePriority(ctx context.Context, jobID string, priority int64, lifo bool) error
// Remove deletes a job and, optionally, its children. It returns false when
// the job (or a dependency) is locked by another worker.
Remove(ctx context.Context, jobID string, removeChildren bool) (bool, error)
// GetState returns the state of a job, or [StateUnknown].
GetState(ctx context.Context, jobID string) (JobState, error)
// GetJob returns the stored job, or nil when it does not exist.
GetJob(ctx context.Context, jobID string) (*JobRecord, error)
// GetJobs returns the jobs of each of states in turn, those at positions
// start to end of that state, ordered as GetRanges orders them. A job is
// returned once even if it shows up in two states, and jobs removed
// meanwhile are skipped.
GetJobs(ctx context.Context, states []JobState, start, end int64, asc bool) ([]*JobRecord, error)
// GetCounts returns the number of jobs per requested state, in order.
GetCounts(ctx context.Context, states []JobState) ([]int64, error)
// GetRanges returns the ids of the jobs of each of states in turn, those
// at positions start to end (inclusive; a negative end counts from the
// last one) of that state, oldest or first due first when asc is set.
// An id is returned once even if it shows up in two states.
GetRanges(ctx context.Context, states []JobState, start, end int64, asc bool) ([]string, error)
// IsMaxed reports whether the queue reached its global concurrency limit.
IsMaxed(ctx context.Context) (bool, error)
// GetRateLimitTTL returns the time left in the current rate limit window,
// in milliseconds, once at least maxJobs jobs were counted in it, and 0
// otherwise. A maxJobs of 0 uses the max of the global rate limit and,
// without one, returns the time left whatever the count, or -2 when no
// window is open (-1 for a window without expiry), as Redis PTTL does.
GetRateLimitTTL(ctx context.Context, maxJobs int64) (int64, error)
// SetRateLimit rate limits the whole queue for ttl, as if the limiter's
// window were full: until it expires, fetching reports a rate limit
// instead of a job. Like the shared commands, the limit only applies to
// fetches made with a limiter (a worker Limiter or a global rate limit).
// ttl must be at least 1ms.
SetRateLimit(ctx context.Context, ttl time.Duration) error
// GetMetrics returns the metrics collected for the completed or failed
// state.
GetMetrics(ctx context.Context, state JobState, start, end int64) (*Metrics, error)
// GetClientList returns the connection list(s) of the datastore, used
// for worker discovery, in the `CLIENT LIST` format: one string per
// server (a cluster has several), with one connection per line as
// space-separated key=value fields, including `name`. Queue.Workers
// parses them. Redis returns CLIENT LIST itself; other backends report
// their named connections as `name=<name>` lines (PostgreSQL: one per
// application_name), or nothing.
GetClientList(ctx context.Context) ([]string, error)
// SetQueueMeta sets one or more queue metadata fields.
SetQueueMeta(ctx context.Context, values map[string]any) error
// GetQueueMetaField reads a single metadata field. The bool is false when
// the field does not exist.
GetQueueMetaField(ctx context.Context, field string) (string, bool, error)
// RemoveQueueMetaFields removes metadata fields.
RemoveQueueMetaFields(ctx context.Context, fields ...string) error
// LastEventID returns the id of the newest event, or "0-0" when there is
// none (the Redis stream syntax, which other backends reuse for "before
// the first event"). Reading from it only yields events produced
// afterwards. Event ids are opaque to callers.
LastEventID(ctx context.Context) (string, error)
// ReadEvents blocks up to block waiting for events newer than lastID. It
// returns no events when the wait times out.
ReadEvents(ctx context.Context, lastID string, block time.Duration) ([]QueueEvent, error)
// WaitForJob blocks up to timeout until the queue signals that a job may
// be available or that a delayed job was scheduled, then reports it in a
// [WaitResult]. A timeout is not an error: it returns a zero WaitResult.
// When ctx is done it returns promptly with ctx's error. It uses the
// connection dedicated to blocking reads.
//
// A backend MAY return early, with or without Woken, for example when a
// signal was meant for another worker or its blocking primitive cannot
// wait that long. The caller must cope by fetching again (and finding
// nothing) or waiting again; it must never rely on WaitForJob for timing.
//
// Workers may call it while some of their jobs are still being processed,
// so it must not report work that cannot be claimed, for example while
// the queue is paused or at its global concurrency limit.
WaitForJob(ctx context.Context, timeout time.Duration) (WaitResult, error)
// ForQueue returns a backend for another queue of the same namespace
// that shares this backend's connections, as Node's forQueue does.
// [FlowProducer] uses it to reach every queue of a flow over one
// connection. name is a bare queue name or a qualified name as returned
// by QualifiedName. The returned backend does not own the connections:
// closing it releases only what it opened itself, and it stops working
// once this backend is closed.
ForQueue(name string) (Backend, error)
// AddFlow inserts the jobs of one or more flows in a single operation (a
// Redis transaction, an SQL transaction) and returns their ids in
// order. Each entry names its own queue, which may differ from this
// backend's. Entries are ordered so that a parent comes before its
// children, and a parent is released from waiting-children only once the
// whole tree has been inserted, if none of its children is pending.
//
// When the datastore rejects an entry, for example because its parent
// does not exist ([ErrParentJobNotExist]) or because the job already
// exists under another parent ([ErrParentJobCannotBeReplaced]), AddFlow
// returns an error for the first rejected entry. A datastore that can
// roll back, such as PostgreSQL, then adds none of the entries; Redis
// keeps those it accepted.
AddFlow(ctx context.Context, entries []FlowEntry) ([]string, error)
// GetDependencies returns the children of a parent job grouped by
// status, identified by their keys (`{QualifiedName}:{id}`). With nil
// opts every group is returned in full; otherwise only the requested
// groups are, one page each, with the cursor of the next page.
GetDependencies(ctx context.Context, jobID string, opts *DependenciesOptions) (*Dependencies, error)
// GetDependencyCounts returns how many children of a parent job are in
// each status.
GetDependencyCounts(ctx context.Context, jobID string) (DependencyCounts, error)
// GetProcessedChildrenValues returns the return value (JSON) of every
// completed child of a parent job, by child key.
GetProcessedChildrenValues(ctx context.Context, jobID string) (map[string]json.RawMessage, error)
// GetIgnoredChildrenFailures returns the failure reason of every child
// of a parent job whose failure was ignored (IgnoreDependencyOnFailure or
// ContinueParentOnFailure), by child key.
GetIgnoredChildrenFailures(ctx context.Context, jobID string) (map[string]string, error)
// RemoveChildDependency detaches a job that has not finished yet from
// the parent stored under parentKey (see [JobRecord.ParentKey]), and
// moves the parent to wait when it was its last pending child. It
// returns false when there was no such dependency, [ErrJobNotFound] when
// the job does not exist and [ErrParentJobNotExist] when the parent does
// not.
RemoveChildDependency(ctx context.Context, jobID, parentKey string) (bool, error)
// RemoveUnprocessedChildren removes, recursively, the children of a
// parent job that have not been processed yet. Active, completed and
// failed children, and locked ones, are kept.
RemoveUnprocessedChildren(ctx context.Context, jobID string) error
// AddJobScheduler creates the job scheduler s.ID, or replaces its
// schedule and template, and adds the job of its next iteration,
// removing the pending job of the previous one. For Every schedulers
// the backend computes the next iteration itself. It returns the id of
// the added job and its delay in milliseconds. It fails with
// [ErrSchedulerJobIDCollision] when a job of a Pattern scheduler with
// that id already exists, and with [ErrSchedulerJobSlotsBusy] when no
// free slot was found for an Every scheduler.
AddJobScheduler(ctx context.Context, s NewJobScheduler) (string, int64, error)
// UpdateJobSchedulerNextMillis advances the job scheduler schedulerID
// to the iteration due at nextMillis (computed by the backend for Every
// schedulers) and adds its job, with options jobOpts and the stored
// template data (templateData is a fallback). Only the job of the
// current iteration, producerID, may advance it. It returns the id of
// the added job, or "" when none was added: the scheduler is gone,
// producerID is not the current iteration, or the job already exists
// (a `duplicated` event is then emitted).
UpdateJobSchedulerNextMillis(ctx context.Context, schedulerID string, nextMillis int64, templateData []byte, jobOpts *JobOptions, producerID string) (string, error)
// RemoveJobScheduler removes a job scheduler and the job of its next
// iteration while that job is still delayed. It reports whether the
// scheduler existed.
RemoveJobScheduler(ctx context.Context, schedulerID string) (bool, error)
// GetJobScheduler returns a job scheduler with the due time of its next
// job, or nil when it does not exist or has no stored metadata.
GetJobScheduler(ctx context.Context, schedulerID string) (*JobScheduler, error)
// GetJobSchedulersRange returns the job schedulers ranked start to end
// (inclusive; a negative end counts from the last one) by the due time
// of their next job, latest first unless asc is set.
GetJobSchedulersRange(ctx context.Context, start, end int64, asc bool) ([]JobSchedulerNext, error)
// GetJobSchedulersCount returns the number of job schedulers.
GetJobSchedulersCount(ctx context.Context) (int64, error)
// IsJobScheduler reports whether id is a job scheduler, as opposed to a
// legacy repeatable job, which this port does not support.
IsJobScheduler(ctx context.Context, id string) (bool, error)
// GetDeduplicationJobID returns the id of the job that holds the
// deduplication id dedupID (see [DeduplicationOptions]), or "" when no
// job holds it: it was never set, was removed, or its TTL expired.
GetDeduplicationJobID(ctx context.Context, dedupID string) (string, error)
// RemoveDeduplicationKey releases the deduplication id dedupID if the
// job jobID still holds it, and reports whether it did.
RemoveDeduplicationKey(ctx context.Context, dedupID, jobID string) (bool, error)
// DeleteDeduplicationKey releases the deduplication id dedupID,
// whichever job holds it, and reports whether there was one to release.
DeleteDeduplicationKey(ctx context.Context, dedupID string) (bool, error)
// GetCountsPerPriority returns, for each of priorities in order, how
// many waiting jobs have that priority; 0 counts the waiting jobs
// without a priority.
GetCountsPerPriority(ctx context.Context, priorities []int64) ([]int64, error)
// GetDelayedCount returns how many delayed jobs are due strictly before
// before (Unix milliseconds).
GetDelayedCount(ctx context.Context, before int64) (int64, error)
// GetQueueMeta returns every field of the queue metadata hash, or an
// empty map when there is none.
GetQueueMeta(ctx context.Context) (map[string]string, error)
// TrimEvents trims the event stream to about maxLength events and
// returns how many it removed. A backend that can't returns an error
// wrapping ErrNotSupported.
TrimEvents(ctx context.Context, maxLength int64) (int64, error)
// PublishEvent appends an event called event with fields (besides the
// `event` field) to the event stream, trimmed to about maxEvents where
// the backend trims on add, and returns its id.
PublishEvent(ctx context.Context, event string, fields map[string]string, maxEvents int64) (string, error)
}
Backend is the datastore-agnostic contract describing every high-level operation that Queue, Worker, QueueEvents and Job need in order to function. It is the Go counterpart of the `IQueueBackend` interface of the Node.js implementation (src/interfaces/queue-backend.ts) and keeps the same operation names and semantics.
The interface expresses the queue semantics ("move job to active", "extend lock", "promote job", ...) independently of the underlying store. The Redis implementation lives in the redisbackend subpackage; other datastores are plugged in through a BackendFactory without any change to Queue, Worker, QueueEvents or Job. This package never imports a datastore driver.
Rules for implementations:
- Methods use only exported domain types. Datastore specifics (Lua scripts, key names, SQL, msgpack encoding, reply parsing) stay private to the implementation.
- A backend owns its connection(s). Callers never thread a connection or a transaction through an operation.
- Operations that fail because of queue semantics return the sentinel errors of this package (for example ErrJobNotFound or ErrJobLockNotExist), directly or wrapped in a ScriptError whose Code is one of the ErrCode constants (-1 to -11), whatever the datastore reports natively. The shared PostgreSQL commands raise SQLSTATE BM001 with the same code in the detail.
- All methods must be safe for concurrent use.
- Times are Unix milliseconds and durations have millisecond precision, as in every other BullMQ port.
Fetching jobs follows Node's protocol. Backend.MoveToActive moves the next job to active and locks it with a token chosen by the worker. When no job can be fetched, the FetchResult says why, so the worker knows how long it may sleep. A worker finishing a job can ask for the next one in the same operation (FinishOptions.FetchNext), which saves a round trip per job; the next job is then locked with the same token. Between fetches an idle worker blocks in Backend.WaitForJob.
type BackendFactory ¶
type BackendFactory func(name string, opts BackendOptions) (Backend, error)
BackendFactory builds a Backend for the queue called name. It is injected through the required Backend field of QueueOptions, WorkerOptions and QueueEventsOptions, for example with redisbackend.New. The queue name has already been validated when the factory is called.
type BackendOptions ¶
type BackendOptions struct {
// WithBlockingConnection requests a connection dedicated to WaitForJob and
// ReadEvents, so a blocked read never starves other operations.
WithBlockingConnection bool
// ClientNameSuffix is appended to the base client name of the dedicated
// blocking connection, for example ":w:<worker>" or ":qe".
ClientNameSuffix string
// BlockTimeout is the longest blocking read the owner will request. It
// lets the backend size socket read timeouts.
BlockTimeout time.Duration
// QueueMeta holds queue metadata fields the backend writes, as
// SetQueueMeta does, once, before the first command it sends. A write
// that fails is not retried, unless it failed because its context was
// done or with a transient error. Obliterate and Close stop any later
// write, so the metadata never comes back after an Obliterate. Queue
// sets it unless QueueOptions.SkipMetasUpdate is set.
QueueMeta map[string]any
}
BackendOptions describes the role of the backend being built by a BackendFactory. Datastore settings such as addresses, credentials or a Redis key prefix belong to the options of the backend package itself.
type Backoff ¶
type Backoff struct {
// Type is the strategy name. Custom strategy names are forwarded to the
// worker's WorkerOptions.BackoffStrategy callback.
Type BackoffType `json:"type"`
// Delay is the base delay, in milliseconds (an int64, not a
// time.Duration).
Delay int64 `json:"delay,omitempty"`
// Jitter is the fraction (0 to 1) of the delay that is randomized: the
// effective delay is drawn uniformly from [delay*(1-Jitter), delay),
// excluding delay itself, and rounded down to whole milliseconds. 0 (the
// default) disables jitter. Applies to the fixed and exponential
// strategies.
Jitter float64 `json:"jitter,omitempty"`
}
Backoff configures the retry delay of a job.
type BackoffType ¶
type BackoffType string
BackoffType selects the delay curve used between retries.
const ( BackoffFixed BackoffType = "fixed" BackoffExponential BackoffType = "exponential" )
Supported backoff strategies.
type ConfigError ¶
type ConfigError struct {
Message string
}
ConfigError signals invalid user supplied configuration.
func (*ConfigError) Error ¶
func (e *ConfigError) Error() string
type DeduplicationOptions ¶
type DeduplicationOptions struct {
// ID is the deduplication id.
ID string `json:"id"`
// TTL is how long the id is held, in milliseconds (an int64, not a
// time.Duration). When it is 0, the id is held until the job completes
// or fails for good.
TTL int64 `json:"ttl,omitempty"`
// Extend refreshes the TTL when a duplicate is discarded.
Extend bool `json:"extend,omitempty"`
// Replace discards the existing job in favour of the new one, while the
// existing job is still delayed.
Replace bool `json:"replace,omitempty"`
// Reschedule moves the existing job, while it is still delayed, to the
// new job's delay counted from the new job's timestamp (no delay makes
// it due now). The existing job keeps its id and data, and a `delayed`
// event is emitted. It is independent of Extend, and ignored when
// Replace is set.
Reschedule bool `json:"reschedule,omitempty"`
// KeepLastIfActive keeps the data of the last job added while the
// existing job is active: when that job completes or fails, a new job
// is added with it, so at most one job runs and one waits per id. TTL
// is then ignored: the id is held until the jobs finish. It can't be
// used on a flow node with a parent.
KeepLastIfActive bool `json:"keepLastIfActive,omitempty"`
}
DeduplicationOptions prevents duplicate jobs from being added while a job holds the deduplication id, as Node's deduplication option does.
Adding a job whose id another job holds adds nothing: Queue.Add returns a Job with the ID of the job that holds it (and the data and options of the call), and QueueEvents reports a `deduplicated` event. As in Node, Add does not say whether it deduplicated the job; use the event, or compare the returned ID with JobOptions.JobID when you set one. Queue.DeduplicationJobID reports the job that holds an id, and Queue.RemoveDeduplicationKey and Job.RemoveDeduplicationKey release it early.
type Dependencies ¶
type Dependencies struct {
// Processed maps the key of every completed child to its return value
// (JSON).
Processed map[string]json.RawMessage
// Unprocessed lists the keys of the children that have not finished.
Unprocessed []string
// Ignored maps the key of every child whose failure was ignored
// (IgnoreDependencyOnFailure or ContinueParentOnFailure) to its failure
// reason.
Ignored map[string]string
// Failed lists the keys of the children that failed with
// FailParentOnFailure.
Failed []string
NextProcessedCursor uint64
NextUnprocessedCursor uint64
NextIgnoredCursor uint64
NextFailedCursor uint64
}
Dependencies are the children of a parent job grouped by status. Children are identified by their key, `{QualifiedName}:{id}` (for example `bull:emails:42` on Redis and `emails:42` on PostgreSQL), which works across queues.
A group that was not requested is nil. A next cursor is 0 once the last page of its group was returned.
type DependenciesOptions ¶
type DependenciesOptions struct {
// Processed pages through the completed children.
Processed *DependencyPage
// Unprocessed pages through the children that have not finished yet.
Unprocessed *DependencyPage
// Ignored pages through the children whose failure was ignored.
Ignored *DependencyPage
// Failed pages through the children that failed their parent.
Failed *DependencyPage
}
DependenciesOptions selects the children returned by Job.Dependencies: only the groups whose page is set are returned, one page each.
type DependencyCounts ¶
DependencyCounts is the number of children of a parent job in each status (see Dependencies).
type DependencyPage ¶
type DependencyPage struct {
// Cursor is where the page starts: 0 for the first page, then the next
// cursor reported with the previous page.
Cursor uint64
// Count is how many children to return. Defaults to 20. On Redis it is
// a hint for the processed, unprocessed and ignored groups, as the COUNT
// of HSCAN and SSCAN: the children of a small group are all returned.
Count int64
}
DependencyPage requests a page of a group of children.
type Event ¶
type Event struct {
// Type is the kind of event.
Type EventType
// Job is the job the event refers to; nil for EventDrained, EventError,
// EventClosed, EventPaused, EventResumed and the lock events. For EventStalled only ID and
// QueueName are set, since the stalled check reports job ids; load the
// job with Queue.Job (or Job.State) if needed.
Job *Job
// JobIDs lists the jobs of EventLockRenewalFailed and EventLocksRenewed.
JobIDs []string
// Result is the processor return value for EventCompleted, or the new
// Progress value for EventProgress.
Result any
// Err carries the failure for EventFailed and EventError.
Err error
}
Event is emitted by a Worker through Worker.Events.
type EventType ¶
type EventType string
EventType identifies a worker lifecycle event.
const ( EventActive EventType = "active" EventCompleted EventType = "completed" EventFailed EventType = "failed" EventProgress EventType = "progress" // EventStalled reports a job that the stalled check of this worker // moved back to wait (or failed) because its lock had expired. Only the // ID and QueueName of its Event.Job are set. EventStalled EventType = "stalled" // EventLockRenewalFailed lists, in Event.JobIDs, the jobs of this worker // whose lock could not be renewed. Their contexts are cancelled with // ErrLockLost, since another worker may own them now; Node.js only // reports them. EventLockRenewalFailed EventType = "lockRenewalFailed" // EventLocksRenewed lists, in Event.JobIDs, the jobs whose locks were // renewed. EventLocksRenewed EventType = "locksRenewed" EventDrained EventType = "drained" EventError EventType = "error" EventClosed EventType = "closed" // EventPaused is emitted by the Pause that paused the worker once it // returns, as Node emits paused once pause has waited for the jobs in // flight (whose EventCompleted or EventFailed may follow it); not when // the worker was resumed or closed meanwhile. EventPaused EventType = "paused" // EventResumed is emitted by Resume when the worker was paused. EventResumed EventType = "resumed" )
Worker event types.
type FailureInfo ¶
type FailureInfo struct {
// Reason is the failure message.
Reason string
// Stacktrace holds the (already trimmed) failure traces to persist.
Stacktrace []string
}
FailureInfo describes why an attempt failed.
type FetchResult ¶
type FetchResult struct {
// Job is the job that was moved to active, or nil when none was fetched.
Job *JobRecord
// RateLimitDelay is how long the queue stays rate limited when Job is nil
// because of the rate limit.
RateLimitDelay time.Duration
// NextDelayedAt is when the next delayed job is due (Unix milliseconds)
// when Job is nil; 0 means none, or unknown.
NextDelayedAt int64
}
FetchResult is the outcome of fetching a job, with Backend.MoveToActive or as the next job of a finishing operation. It mirrors the `[jobData, id, rateLimitDelay, delayUntil]` tuple of the other ports.
When Job is nil, the other fields say why no job was fetched:
- RateLimitDelay > 0: the queue is rate limited for that long, and no job may be fetched before it lifts.
- NextDelayedAt > 0: nothing is ready, but a delayed job is due then.
- both zero: the queue is empty, paused or at its global concurrency limit.
type FinishOptions ¶
type FinishOptions struct {
// Token is the lock token held on the job. The next job, when fetched,
// is locked with the same token.
Token string
// JobOpts are the options of the job being finished.
JobOpts *JobOptions
// KeepJobs is the effective removal policy for the target state.
KeepJobs *RemoveOnFinish
// LockDuration is the worker lock duration.
LockDuration time.Duration
// WorkerName is the name of the worker.
WorkerName string
// Limiter is the worker rate limiter.
Limiter *RateLimiter
// Metrics enables metrics collection.
Metrics *MetricsOptions
// FetchNext fetches the next job in the same operation, as MoveToActive
// would with Token, LockDuration, WorkerName and Limiter.
FetchNext bool
}
FinishOptions carries the settings needed to move a job to a finished state and, optionally, to fetch the next one.
type FinishResult ¶
type FinishResult struct {
// FinishedOn is the recorded finishedOn timestamp (Unix milliseconds).
FinishedOn int64
// Next is the outcome of fetching the next job. It is nil when
// [FinishOptions.FetchNext] was not set, so callers can tell "not
// requested" from "nothing to fetch" (a non-nil result with a nil Job).
Next *FetchResult
}
FinishResult is the outcome of Backend.MoveToCompleted and Backend.MoveToFailed.
type FlowEntry ¶
type FlowEntry struct {
// QueueName is the queue the job is added to.
QueueName string
// JobID is the id the job is stored under: its custom id, or one the
// FlowProducer generated, since children must know their parent's id
// before it is stored. Job.Opts.JobID only holds a custom id, which is
// what the other ports store in the job options.
JobID string
// Job is the validated job.
Job NewJob
// WaitingChildren adds the job in the waiting-children state: it is a
// parent, and its children follow it in the entries.
WaitingChildren bool
}
FlowEntry is a job of a flow handed to Backend.AddFlow.
type FlowGetOptions ¶
type FlowGetOptions struct {
// ID is the id of the root job.
ID string
// QueueName is the queue of the root job.
QueueName string
// Depth is how many levels of the tree are returned, the root included.
// Defaults to 10.
Depth int
// MaxChildren is how many children of each status (processed,
// unprocessed, failed, ignored) are returned per job. Defaults to 20. On
// Redis it is a hint, like the COUNT of HSCAN: the children of a small
// group are all returned.
MaxChildren int64
}
FlowGetOptions selects the flow returned by FlowProducer.GetFlow.
type FlowJob ¶
type FlowJob struct {
// Name is the job name handed to the processor.
Name string
// QueueName is the queue the job is added to.
QueueName string
// Data is the payload; it is marshalled to JSON. nil is stored as {}, as
// Node stores a job added without data.
Data any
// Opts are the job options. Opts.Parent is only honoured on the root of
// a flow, to add the whole flow under an existing job; the other nodes
// are children of their parent node. Deduplication is only allowed on a
// root without children nor parent.
Opts *JobOptions
// Children are the jobs this job waits for.
Children []FlowJob
}
FlowJob is a node of a flow: a job and the children it waits for. A node with children is added in the waiting-children state and processed once all of them are, with their results available through Job.ChildrenValues. Children may belong to other queues.
type FlowOpts ¶
type FlowOpts struct {
// QueuesOptions holds options for the nodes of a queue, by queue name.
QueuesOptions map[string]FlowQueueOptions
}
FlowOpts tunes FlowProducer.Add.
type FlowProducer ¶
type FlowProducer struct {
// contains filtered or unexported fields
}
FlowProducer adds flows: trees of jobs, possibly spanning several queues, in which a parent is processed only once its children are, as Node's FlowProducer does.
A FlowProducer is safe for concurrent use.
func NewFlowProducer ¶
func NewFlowProducer(opts *FlowProducerOptions) (*FlowProducer, error)
NewFlowProducer creates a flow producer.
func (*FlowProducer) Add ¶
Add adds a flow and returns its jobs. Children are processed before their parents; a parent sees their results with Job.ChildrenValues.
The whole tree is sent in one datastore operation (a Redis transaction, a database transaction on PostgreSQL). When the datastore rejects one of its jobs, for example because the parent of the root does not exist (ErrParentJobNotExist: then no job is added) or because a child with a custom id already belongs to another parent (ErrParentJobCannotBeReplaced), Add returns an error. PostgreSQL then rolls the whole tree back; on Redis, as in Node, the jobs the datastore accepted are kept.
func (*FlowProducer) AddBulk ¶
AddBulk adds several flows in one datastore operation and returns their jobs, in order. Errors are reported as in FlowProducer.Add: when the datastore rejects a job, AddBulk returns an error; PostgreSQL then adds no job of any of the flows, while Redis keeps the jobs it accepted.
func (*FlowProducer) Backend ¶
func (fp *FlowProducer) Backend() Backend
Backend returns the datastore backend of the producer, which reaches every queue of its flows. Type-assert it to the concrete backend, for example *redisbackend.Backend, to reach datastore-specific features.
func (*FlowProducer) Close ¶
func (fp *FlowProducer) Close() error
Close releases the connections of the flow producer. The jobs it returned can no longer reach the datastore afterwards.
func (*FlowProducer) GetFlow ¶
func (fp *FlowProducer) GetFlow(ctx context.Context, opts FlowGetOptions) (*JobNode, error)
GetFlow returns the tree of jobs rooted at a job: the job and, level by level, the children it has in any status. It returns nil when the job does not exist. Children that no longer exist are left out.
type FlowProducerOptions ¶
type FlowProducerOptions struct {
// Backend builds the datastore backend, for example
// redisbackend.New(redisbackend.Options{Addr: "127.0.0.1:6379"}). It is
// required. Every queue of a flow is reached through the backend it
// builds, so the queues of a flow share its connections and its namespace
// (the Redis key prefix or the PostgreSQL schema).
Backend BackendFactory
}
FlowProducerOptions configures a FlowProducer.
type FlowQueueOptions ¶
type FlowQueueOptions struct {
// DefaultJobOptions are merged into the options of the queue's nodes, as
// QueueOptions.DefaultJobOptions are into the jobs of a Queue.
DefaultJobOptions *JobOptions
}
FlowQueueOptions are applied to every node of a flow that belongs to one queue.
type Job ¶
type Job struct {
// ID is the job id.
ID string
// Name is the job name.
Name string
// Data is the JSON encoded payload. On PostgreSQL, which stores it as
// jsonb, a job read back from the datastore holds an equal JSON value
// but not necessarily the same bytes (whitespace and key order may
// differ), so decode it rather than compare bytes.
Data json.RawMessage
// Opts are the options the job was created with.
Opts *JobOptions
// Progress is the last reported progress value.
Progress Progress
// AttemptsMade is how many times the job has finished an attempt.
AttemptsMade int64
// AttemptsStarted is how many times the job has been moved to active.
AttemptsStarted int64
// Timestamp is the creation time in Unix milliseconds.
Timestamp int64
// ProcessedOn is when the job was last moved to active, in Unix milliseconds.
ProcessedOn int64
// FinishedOn is when the job completed or failed, in Unix milliseconds.
FinishedOn int64
// FailedReason is the error message of the last failure.
FailedReason string
// DeferredFailure is set by the stalled-check script when the job
// exceeded MaxStalledCount; when non-empty the job must be failed
// unrecoverably instead of being handed to the processor.
DeferredFailure string
// Stacktrace holds the recorded failure traces.
Stacktrace []string
// ReturnValue is the JSON encoded value returned by the processor. On
// PostgreSQL it is re-encoded as Data is: equal as JSON, possibly with
// different bytes.
ReturnValue json.RawMessage
// ParentKey is the key of the parent job, if any.
ParentKey string
// Parent identifies the parent job, if any.
Parent *ParentKeys
// ProcessedBy is the name of the worker that last processed the job.
ProcessedBy string
// StalledCounter is how many times the job has been detected as stalled.
StalledCounter int64
// Delay is the configured delay, in milliseconds (ChangeDelay takes a
// time.Duration).
Delay int64
// Priority is the configured priority.
Priority int64
// RepeatJobKey links the job to a job scheduler.
RepeatJobKey string
// DeduplicationID is the deduplication id the job was added with (see
// JobOptions.Deduplication), or "".
DeduplicationID string
// QueueName is the name of the owning queue.
QueueName string
// contains filtered or unexported fields
}
Job is a unit of work stored in a queue.
Values returned by Queue and Worker methods carry a live Backend, so mutating methods such as UpdateProgress or Log can be called on them.
func (*Job) ChangeDelay ¶
ChangeDelay makes a job that is in the delayed set due after delay, counted from now. delay is a time.Duration, used with millisecond precision, unlike JobOptions.Delay and Job.Delay, which are milliseconds: pass 4*time.Second, not 4000.
func (*Job) ChangePriority ¶
ChangePriority updates the priority of a waiting or prioritized job.
func (*Job) ChildrenValues ¶
ChildrenValues returns the return value (JSON) of every completed child of the job, by child key (see Dependencies), as Node's getChildrenValues.
func (*Job) DecodeChildrenValues ¶
DecodeChildrenValues decodes the return values of the completed children of the job into out, a pointer to a map from child key to the type of the values, as DecodeData decodes the job's data:
var costs map[string]float64
if err := job.DecodeChildrenValues(ctx, &costs); err != nil {
return nil, err
}
func (*Job) DecodeData ¶
DecodeData unmarshals the job payload into out.
func (*Job) DecodeReturnValue ¶
DecodeReturnValue unmarshals the processor result into out.
func (*Job) Dependencies ¶
func (j *Job) Dependencies(ctx context.Context, opts *DependenciesOptions) (*Dependencies, error)
Dependencies returns the children of the job grouped by status. With nil opts every group is returned in full; otherwise only the requested groups, one page each.
func (*Job) DependenciesCount ¶
func (j *Job) DependenciesCount(ctx context.Context) (DependencyCounts, error)
DependenciesCount returns how many children of the job are in each status.
func (*Job) Discard ¶
func (j *Job) Discard()
Discard marks the job so that it is not retried when the processor fails.
func (*Job) ExtendLock ¶
ExtendLock refreshes the lock held on an active job, so it expires duration (a time.Duration, used with millisecond precision) from now.
func (*Job) FailedChildrenValues
deprecated
FailedChildrenValues returns the same as Job.IgnoredChildrenFailures.
Deprecated: use Job.IgnoredChildrenFailures; Node deprecated getFailedChildrenValues too.
func (*Job) IgnoredChildrenFailures ¶
IgnoredChildrenFailures returns the failure reason of every child whose failure was ignored, with IgnoreDependencyOnFailure or ContinueParentOnFailure, by child key.
func (*Job) IsCompleted ¶
IsCompleted reports whether the job finished successfully.
func (*Job) MoveToCompleted ¶
func (j *Job) MoveToCompleted(ctx context.Context, result any, token string, fetchNext bool) (*Job, error)
MoveToCompleted completes a job fetched with Worker.GetNextJob and locked with token, recording result (encoded as JSON) as its return value, as Node's job.moveToCompleted does. The worker's settings apply: the removal policy, the metrics and, for the next job, the lock duration and limiter.
With fetchNext, the next job is fetched in the same datastore call and locked with the same token, as GetNextJob(ctx, token, false) would; it is returned, or nil when there is none (or the worker is paused or closed). It fails when the job's lock is gone or held by another token, for example because the job stalled.
Processors don't call it: the worker completes their jobs.
func (*Job) MoveToDelayed ¶
MoveToDelayed reschedules an active job to run after delay, a time.Duration counted from now and used with millisecond precision (Node's moveToDelayed takes the due timestamp instead). Processors should return ErrDelayed afterwards so the worker does not also move the job to a finished state.
The current attempt is not counted, matching the Node.js implementation.
func (*Job) MoveToFailed ¶
func (j *Job) MoveToFailed(ctx context.Context, cause error, token string, fetchNext bool) (*Job, error)
MoveToFailed records a failed attempt of a job fetched with Worker.GetNextJob and locked with token, with cause as its failure, as Node's job.moveToFailed does. As when a processor fails, the job is retried, after its backoff, while attempts remain, unless cause is unrecoverable (see NewUnrecoverableError) or the job was discarded; otherwise it fails for good.
With fetchNext, the next job is fetched in the same datastore call, as in MoveToCompleted, and returned. A job retried right away is not, so fetch it with GetNextJob. It fails when the job's lock is gone or held by another token.
func (*Job) MoveToWait ¶
MoveToWait puts the active job back in the wait list (or the prioritized set, keeping its priority) without counting an attempt, and releases its lock, as Node's job.moveToWait does. A processor must then return ErrWaiting, so the worker does not also finish the job. It fails when the job's lock is gone or held by another token.
func (*Job) MoveToWaitingChildren ¶
MoveToWaitingChildren parks an active parent job until its children finish. It returns true when the job was moved and false when there were no pending dependencies. Processors should return ErrWaitingChildren when true.
child identifies the job whose completion is being awaited. Its QueueKey must be the fully qualified queue name (see Backend.QualifiedName) of the queue the child belongs to, which may differ from the parent's own queue. Pass nil if there is no specific child to check for.
func (*Job) RemoveChildDependency ¶
RemoveChildDependency detaches the job, which must not have finished yet, from its parent, so the parent no longer waits for it; a parent left without pending children is moved to wait. It returns false when the job was not a pending child of its parent. As in Node.js, it returns an error matching ErrParentJobNotExist when the job has no parent, or its parent no longer exists. On success the job's Parent and ParentKey are cleared.
func (*Job) RemoveDeduplicationKey ¶
RemoveDeduplicationKey releases the job's deduplication id if the job still holds it, so the next job added with it is not deduplicated, as Node's job.removeDeduplicationKey does. It reports whether it did: false when the job has no deduplication id, or when the id expired or is held by another job.
func (*Job) RemoveUnprocessedChildren ¶
RemoveUnprocessedChildren removes, recursively, the children of the job that have not been processed yet: active, completed and failed children, and locked ones, are kept. It can be slow with many children.
func (*Job) Retry ¶
Retry moves a completed or failed job back to the wait list (or to the prioritized set when it has a priority). opts may be nil.
state must be either StateCompleted or StateFailed. Unless opts resets them, the attempt counters are kept: a job that used up its attempts fails for good after its next failure.
func (*Job) UpdateData ¶
UpdateData replaces the job payload.
func (*Job) UpdateProgress ¶
UpdateProgress stores a new progress value and emits a `progress` event on the owning Worker, mirroring how a per-job update is observed through Worker.Events.
progress is a number, or any value encoded as JSON, as Node's updateProgress takes a number or an object; a Progress is stored as is. NaN and infinite numbers, which have no JSON encoding, are rejected.
type JobOptions ¶
type JobOptions struct {
// JobID overrides the automatically generated job id.
JobID string `json:"jobId,omitempty"`
// Delay is how long before the job becomes available, in milliseconds
// (an int64, not a time.Duration: use time.Minute.Milliseconds(), for
// example), as every port stores it. A pointer so a per-job value of 0
// can be told apart from "not set", letting it override a non-zero
// queue default back to 0.
Delay *int64 `json:"delay,omitempty"`
// Priority; lower values are processed first. 0 means unprioritized and
// the maximum is 2^21-1 (2097151). A
// pointer so a per-job value of 0 can be told apart from "not set",
// letting it override a non-zero queue default back to 0.
Priority *int64 `json:"priority,omitempty"`
// LIFO pushes the job to the front of the wait list. A pointer so an
// explicit `false` can override a queue default of `true`.
LIFO *bool `json:"lifo,omitempty"`
// Attempts is the total number of times the job may be tried. A pointer
// so a per-job value of 0 can override a non-zero queue default.
Attempts *int64 `json:"attempts,omitempty"`
// Backoff configures the delay between retries.
Backoff *Backoff `json:"backoff,omitempty"`
// RemoveOnComplete controls automatic removal of completed jobs.
RemoveOnComplete *RemoveOnFinish `json:"removeOnComplete,omitempty"`
// RemoveOnFail controls automatic removal of failed jobs.
RemoveOnFail *RemoveOnFinish `json:"removeOnFail,omitempty"`
// KeepLogs limits how many log rows are retained per job. A pointer so a
// per-job value of 0 can override a non-zero queue default.
KeepLogs *int64 `json:"kl,omitempty"`
// SizeLimit rejects jobs whose serialized data exceeds this many bytes. A
// pointer so a per-job value of 0 can override a non-zero queue default.
SizeLimit *int64 `json:"sizeLimit,omitempty"`
// StackTraceLimit caps how many failure traces are kept on the job: the
// most recent ones. 0 keeps none; unset keeps them all, as in Node.js.
StackTraceLimit *int64 `json:"stackTraceLimit,omitempty"`
// Timestamp is the creation time in Unix milliseconds. Defaults to now.
Timestamp int64 `json:"timestamp,omitempty"`
// Parent links this job to a parent job.
Parent *ParentOptions `json:"parent,omitempty"`
// Deduplication prevents duplicates while the key is alive.
Deduplication *DeduplicationOptions `json:"de,omitempty"`
// FailParentOnFailure fails the parent when this job fails. A pointer so
// an explicit `false` can override a queue default of `true`.
FailParentOnFailure *bool `json:"fpof,omitempty"`
// ContinueParentOnFailure unblocks the parent when this job fails. A
// pointer so an explicit `false` can override a queue default of `true`.
ContinueParentOnFailure *bool `json:"cpof,omitempty"`
// IgnoreDependencyOnFailure removes this job from the parent's
// dependencies when it fails, without failing the parent. A pointer so
// an explicit `false` can override a queue default of `true`.
IgnoreDependencyOnFailure *bool `json:"idof,omitempty"`
// RemoveDependencyOnFailure removes the dependency when this job fails. A
// pointer so an explicit `false` can override a queue default of `true`.
RemoveDependencyOnFailure *bool `json:"rdof,omitempty"`
// Repeat, PrevMillis and RepeatJobKey are set by job schedulers on the
// jobs they produce: the schedule with the iteration count, the due time
// of the iteration (Unix milliseconds) and the scheduler id. Repeat
// cannot be set when adding a job; use Queue.UpsertJobScheduler.
Repeat *RepeatOptions `json:"repeat,omitempty"`
PrevMillis int64 `json:"prevMillis,omitempty"`
RepeatJobKey string `json:"repeatJobKey,omitempty"`
}
JobOptions configures a single job.
The JSON tags mirror the field names persisted by the shared Lua and SQL commands, so options round-trip across all BullMQ language ports.
func (*JobOptions) UnmarshalJSON ¶
func (opts *JobOptions) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes stored job options. A removal policy stored in a form no BullMQ port writes is dropped, so the worker default applies.
type JobRecord ¶
type JobRecord struct {
ID string
Name string
Data json.RawMessage
Opts *JobOptions
Progress Progress
ReturnValue json.RawMessage
Stacktrace []string
ParentKey string
Parent *ParentKeys
ProcessedBy string
RepeatJobKey string
DeduplicationID string
FailedReason string
DeferredFailure string
Timestamp int64
AttemptsMade int64
AttemptsStarted int64
ProcessedOn int64
FinishedOn int64
StalledCounter int64
Priority int64
Delay int64
}
JobRecord is the stored representation of a job returned by a Backend.
type JobScheduler ¶
type JobScheduler struct {
// ID is the scheduler id (Node's `key`).
ID string
// Name is the name of the jobs it produces.
Name string
// IterationCount is how many jobs it has produced.
IterationCount int64
Limit int64
StartDate int64
EndDate int64
Tz string
Pattern string
Every int64
Offset int64
// Next is when its next job is due.
Next int64
// Template holds the data and options of the jobs it produces, or nil
// when it stores neither.
Template *JobSchedulerTemplate
}
JobScheduler describes a stored job scheduler, as returned by Queue.JobScheduler and Queue.JobSchedulers. It mirrors Node's JobSchedulerJson; times are Unix milliseconds and zero values mean unset.
type JobSchedulerNext ¶
JobSchedulerNext is a scheduler id with the due time of its next job, as listed by Backend.GetJobSchedulersRange.
type JobSchedulerTemplate ¶
type JobSchedulerTemplate struct {
// Data is the JSON payload, or nil when none is stored.
Data json.RawMessage
// Opts are the job options, or nil when none are stored.
Opts *JobOptions
}
JobSchedulerTemplate is the stored template of a job scheduler.
type JobSpec ¶
type JobSpec struct {
// Name is the job name handed to the processor.
Name string
// Data is the payload; it is marshalled to JSON. nil is stored as {}, as
// Node stores a job added without data.
Data any
// Opts overrides the queue default job options.
Opts *JobOptions
}
JobSpec describes a job to add through Add or AddBulk.
type JobState ¶
type JobState string
JobState is the lifecycle state of a job.
const ( StateWaiting JobState = "waiting" StateActive JobState = "active" StateDelayed JobState = "delayed" StatePrioritized JobState = "prioritized" StateCompleted JobState = "completed" StateFailed JobState = "failed" StateWaitingChildren JobState = "waiting-children" StateUnknown JobState = "unknown" )
Job states, matching the values returned by the shared `getState` command.
const StatePaused JobState = "paused"
StatePaused designates the paused list of older BullMQ versions, as Node's "paused" job type does. Jobs of a paused queue stay waiting, and Queue.Resume moves any job left in that list back to wait. It is accepted by Clean, JobCounts and JobIDs but is never the state of a job. On PostgreSQL, which has no paused list, JobCounts and JobIDs report it empty, while Clean treats it as StateWaiting, as the shared SQL does.
type JobTemplate ¶
type JobTemplate struct {
// Name is the name of every job. It defaults to the scheduler id.
Name string
// Data is the payload of every job; it is marshalled to JSON. Nil
// means an empty object.
Data any
// Opts are the options of every job, merged over the queue's default
// job options. JobID, Delay, Deduplication and Repeat cannot be set.
Opts *JobOptions
}
JobTemplate describes the jobs a job scheduler produces.
type Metrics ¶
type Metrics struct {
// Count is the total number of jobs recorded.
Count int64
// PrevCount is the job count at the last time a data point was recorded.
// It is internal metrics state used to compute the next data point's
// delta, not a retention boundary.
PrevCount int64
// PrevTS is the timestamp (Unix milliseconds) of the transition that last
// recorded a data point, i.e. the previous collection timestamp. It is
// internal metrics state, not the timestamp of the oldest retained data
// point, so do not use it as the retention boundary.
PrevTS int64
// Data holds one entry per minute, most recent first: the number of
// jobs recorded in that minute. Entries are added when a job is
// recorded in a later minute than the previous entry, so Data stays
// empty during the first minute of collection, as in Node.js.
Data []int64
// NumPoints is the total number of retained data points, regardless of
// the requested [start, end] window. Use it for pagination (the reference
// getMetrics API returns it as `count`).
NumPoints int64
}
Metrics is the result of Queue.Metrics.
type MetricsOptions ¶
type MetricsOptions struct {
// MaxDataPoints is the number of one-minute data points to retain.
MaxDataPoints int64
}
MetricsOptions enables the collection of completed/failed counters.
type MoveToActiveOptions ¶
type MoveToActiveOptions struct {
// Token is the lock token to acquire.
Token string
// LockDuration is how long the lock is held.
LockDuration time.Duration
// WorkerName is stored on the job as the processing worker.
WorkerName string
// Limiter throttles how many jobs may be fetched per window.
Limiter *RateLimiter
}
MoveToActiveOptions are the worker settings needed to fetch a job.
type MoveToDelayedOptions ¶
type MoveToDelayedOptions struct {
// SkipAttempt keeps the attempts counter untouched.
SkipAttempt bool
// Failure is recorded on the job when the delay is a retry backoff.
Failure *FailureInfo
// FetchNext fetches the next job in the same operation, as MoveToActive
// would with the job's token and the settings below.
FetchNext bool
// LockDuration is how long the next job's lock is held.
LockDuration time.Duration
// WorkerName is stored on the next job as the processing worker.
WorkerName string
// Limiter throttles fetching the next job.
Limiter *RateLimiter
}
MoveToDelayedOptions tunes Backend.MoveToDelayed.
type NewJob ¶
type NewJob struct {
// Name is the job name handed to the processor.
Name string
// Data is the JSON encoded payload.
Data []byte
// Opts are the effective job options.
Opts *JobOptions
}
NewJob is a validated job ready to be stored by a Backend. Opts is a private copy with defaults merged and Timestamp set.
type NewJobScheduler ¶
type NewJobScheduler struct {
// ID identifies the scheduler.
ID string
// NextMillis is when the next iteration is due (Unix milliseconds). It
// is ignored for Every schedulers, whose next iteration the backend
// computes from Every, Offset and StartDate as the shared commands do.
NextMillis int64
// Name is the name of the jobs the scheduler produces.
Name string
// The schedule; zero values are not stored. Offset is only set for
// Every schedulers.
Pattern string
Every int64
Tz string
Limit int64
Offset int64
StartDate int64
EndDate int64
// TemplateData is the JSON payload of every job.
TemplateData []byte
// TemplateOpts are the options of every job.
TemplateOpts *JobOptions
// JobOpts are the options of the job of the next iteration.
JobOpts *JobOptions
// ProducerID is the job that produced this iteration, if any.
ProducerID string
}
NewJobScheduler is a job scheduler to store with Backend.AddJobScheduler, with the options of the job of its next iteration. It mirrors the arguments of Node's addJobScheduler.
type ObliterateOptions ¶
type ObliterateOptions struct {
// Force obliterates the queue even while some of its jobs are active.
Force bool
// Count is how many jobs are removed per datastore call, so that a
// large queue doesn't block the datastore; it is not a cap on the
// total. 0 means 1000.
Count int64
}
ObliterateOptions tunes Queue.Obliterate, as Node's obliterate options do.
type ParentKeys ¶
type ParentKeys struct {
// ID is the parent job id.
ID string `json:"id"`
// QueueKey is the qualified name of the parent's queue (see
// [Backend.QualifiedName]): `{prefix}:{queueName}` on Redis, the bare
// queue name on PostgreSQL.
QueueKey string `json:"queueKey"`
}
ParentKeys identifies the parent of a job as persisted by the backend.
type ParentOptions ¶
type ParentOptions struct {
// ID is the parent job id.
ID string `json:"id"`
// Queue is the parent queue. Either a bare queue name or a fully
// qualified `{prefix}:{queueName}` key.
Queue string `json:"queue"`
}
ParentOptions links a job to a parent job, possibly in another queue.
type Processor ¶
Processor handles a single job. The returned value is JSON encoded and stored as the job's return value.
Returning an error fails the job; if attempts remain the job is retried using the configured backoff. Return an error created with NewUnrecoverableError to fail without retrying.
ctx is cancelled when the context passed to Worker.Run is, when the worker loses the job's lock (ErrLockLost), and by Worker.CancelJob (ErrJobCancelled); context.Cause tells which. An error returned after the worker itself cancelled ctx (Run or the lock) is not recorded: the job is left active, without using up an attempt, for the stalled check to recover. After CancelJob the job fails with the error the processor returns, as in Node.js, and with the cancellation reason when that error is ctx.Err() itself.
Once ctx is cancelled, the job's methods called with it (UpdateProgress, Log, ...) fail with ctx's error. Cleanup that must still reach the datastore uses context.WithoutCancel(ctx).
type Progress ¶
type Progress struct {
// contains filtered or unexported fields
}
Progress is a job progress value: either a number or an arbitrary JSON value.
func JSONProgress ¶
JSONProgress builds a structured progress value. Job.UpdateProgress also takes the value itself.
func NumberProgress ¶
NumberProgress builds a numeric progress value. It returns an error for NaN and infinite values, which have no JSON representation.
func (Progress) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (Progress) Number ¶
Number returns the progress as a float. It reports false when the progress is not a plain number.
func (*Progress) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
type Queue ¶
type Queue struct {
// contains filtered or unexported fields
}
Queue adds jobs to a BullMQ queue and inspects its contents.
A Queue only depends on the Backend abstraction, so it works with any datastore for which a backend exists.
A Queue is safe for concurrent use.
func NewQueue ¶
func NewQueue(name string, opts *QueueOptions) (*Queue, error)
NewQueue creates a queue named name. It does not reach the datastore: the queue writes its metadata (see QueueOptions.SkipMetasUpdate) before its first command.
func (*Queue) Add ¶
Add inserts a single job into the queue. data is marshalled to JSON, and nil is stored as {}, as Node stores a job added without data. When the job is deduplicated (see DeduplicationOptions), nothing is added and the returned Job has the ID of the job that holds the deduplication id.
func (*Queue) AddBulk ¶
AddBulk inserts every job in one backend operation. On PostgreSQL that is a database transaction: a failed batch adds no job. On Redis it is a single transaction, but Redis does not roll back the scripts that ran when another returns an application-level error, such as a missing parent, so a failed batch may leave the other jobs added.
func (*Queue) Backend ¶
Backend returns the datastore backend used by the queue. Type-assert it to the concrete backend, for example *redisbackend.Backend, to reach datastore-specific features such as the underlying client.
func (*Queue) Clean ¶
func (q *Queue) Clean(ctx context.Context, grace time.Duration, limit int64, state JobState) ([]string, error)
Clean removes finished (or waiting/delayed) jobs older than grace.
state must be one of StateWaiting, StateActive, StatePaused, StatePrioritized, StateDelayed, StateCompleted or StateFailed ("wait" is accepted for StateWaiting, as in Node). A limit of 0 means unlimited. Removal runs in batches of at most 10,000 jobs, repeating until limit jobs were removed or a batch comes back short, so a large state never blocks the datastore in a single call. It returns the removed job ids.
func (*Queue) Count ¶
Count returns the number of waiting, delayed, prioritized, and waiting-children jobs.
func (*Queue) CountsPerPriority ¶
func (q *Queue) CountsPerPriority(ctx context.Context, priorities ...int64) (map[int64]int64, error)
CountsPerPriority returns how many waiting jobs have each of priorities, as Node's getCountsPerPriority does: 0 counts the waiting jobs without a priority. Repeated priorities are counted once, and an empty list returns an empty map.
func (*Queue) DeduplicationJobID ¶
DeduplicationJobID returns the id of the job that holds the deduplication id dedupID (see DeduplicationOptions), or "" when no job holds it: it was never used, was removed, or its TTL expired. While a job holds it, adding a job with the same deduplication id returns that job's id.
func (*Queue) DelayedCount ¶
DelayedCount returns how many delayed jobs are due strictly before before, as Node's getDelayedCount(timestamp) does, for example to count the overdue ones with time.Now(). The zero time counts every delayed job.
func (*Queue) Drain ¶
Drain removes all waiting and prioritized jobs. Active, completed and failed jobs are left untouched. When delayed is true, delayed jobs are removed too.
func (*Queue) GlobalConcurrency ¶
GlobalConcurrency returns the global concurrency limit, or nil when none is set, as Node's getGlobalConcurrency returns null. It may be 0 when another port stored it (see SetGlobalConcurrency): no job is then fetched, and IsMaxed reports true.
func (*Queue) GlobalRateLimit ¶
func (q *Queue) GlobalRateLimit(ctx context.Context) (*RateLimiter, error)
GlobalRateLimit returns the global rate limit, or nil when none is set.
func (*Queue) JobCounts ¶
JobCounts returns the number of jobs in each of the requested states. When no state is given every state in AllStates is returned.
func (*Queue) JobIDs ¶
func (q *Queue) JobIDs(ctx context.Context, start, end int64, asc bool, states ...JobState) ([]string, error)
JobIDs returns the ids of the jobs in the given states, as Node's getRanges does: for each state, in order, the jobs at positions start to end (inclusive; a negative end counts from the last one) of that state, so the range applies to every state on its own. A job listed twice is returned once. With no state, every state in AllStates is listed.
asc selects the order within each state. Node's shortcuts use asc=true for waiting, active, delayed, prioritized and waiting-children jobs (oldest or first due first: getWaiting, getActive, getDelayed, getPrioritized, getWaitingChildren) and asc=false for completed and failed jobs (most recent first: getCompleted, getFailed), and getJobs defaults to false.
func (*Queue) JobScheduler ¶
JobScheduler returns the job scheduler id, or nil when it does not exist.
func (*Queue) JobSchedulers ¶
func (q *Queue) JobSchedulers(ctx context.Context, start, end int64, asc bool) ([]*JobScheduler, error)
JobSchedulers returns the job schedulers ranked start to end (inclusive; -1 is the last one) by the due time of their next job, latest first unless asc is set.
func (*Queue) JobSchedulersCount ¶
JobSchedulersCount returns the number of job schedulers.
func (*Queue) Jobs ¶
func (q *Queue) Jobs(ctx context.Context, start, end int64, asc bool, states ...JobState) ([]*Job, error)
Jobs returns the jobs in the given states, selected and ordered as by JobIDs, as Node's getJobs does. For example, the 10 most recent failures:
jobs, err := queue.Jobs(ctx, 0, 9, false, bullmq.StateFailed)
func (*Queue) Obliterate ¶
func (q *Queue) Obliterate(ctx context.Context, opts *ObliterateOptions) error
Obliterate deletes the queue and every job in it, with its metadata, whatever their state. opts may be nil.
The queue is paused first, matching the behaviour of the other ports. Unless opts.Force is set, the call fails if there are still active jobs.
func (*Queue) Pause ¶
Pause stops workers from picking up new jobs. Jobs already active keep running.
func (*Queue) PromoteJobs ¶
PromoteJobs moves every delayed job to the wait list right away, in batches of count jobs (one datastore call each; 0 means 1000), as Node's promoteJobs does.
func (*Queue) RateLimitTTL ¶
RateLimitTTL returns how long, in milliseconds, the queue stays rate limited, as Node's getRateLimitTtl does.
maxJobs is the number of jobs per window that makes the queue rate limited: RateLimitTTL returns the time left in the current window once at least maxJobs jobs were counted in it, and 0 otherwise. A maxJobs of 0, like Node's omitted argument, uses the Max of the global rate limit (see SetGlobalRateLimit). Without a global rate limit either, it returns the time left in the current window whatever its count, or the codes of Redis PTTL: -2 when no window is open, and -1 when the window never expires.
func (*Queue) Remove ¶
Remove deletes the job jobID and all of its data, as Node's queue.remove does, without reading it first. With removeChildren, its children are removed too, recursively. It returns false, removing nothing, when the job or one of the children to remove is locked by a worker (Job.Remove reports that as ErrJobLocked); a job that does not exist counts as removed. The current job of a job scheduler can't be removed this way (ErrJobBelongsToJobScheduler); remove the scheduler instead.
func (*Queue) RemoveDeduplicationKey ¶
RemoveDeduplicationKey releases the deduplication id dedupID, whichever job holds it, so the next job added with it is not deduplicated. It reports whether there was one to release. Job.RemoveDeduplicationKey releases it only if a given job still holds it.
func (*Queue) RemoveGlobalConcurrency ¶
RemoveGlobalConcurrency removes the global concurrency limit.
func (*Queue) RemoveGlobalRateLimit ¶
RemoveGlobalRateLimit removes the global rate limit: workers are then only limited by their own Limiter.
func (*Queue) RemoveJobScheduler ¶
RemoveJobScheduler removes the job scheduler id and the job of its next iteration while that job is still delayed, as in Node.js: an iteration job already waiting (such as the first job of an Every scheduler, or a due job that was promoted) or being processed is kept, and runs once more. It reports whether the scheduler existed.
func (*Queue) RetryJobs ¶
func (q *Queue) RetryJobs(ctx context.Context, opts *RetryJobsOptions) error
RetryJobs moves every failed (or completed) job back to the wait list, in batches, as Node's retryJobs does. opts may be nil. Their attempt counters are kept on Redis but reset on PostgreSQL, as the shared commands do.
func (*Queue) SetGlobalConcurrency ¶
SetGlobalConcurrency limits how many jobs may be active across all workers. A value of 0 (or less) removes the limit, as RemoveGlobalConcurrency does. Unlike Go, Node's setGlobalConcurrency(0) stores 0, which stops every worker: the queue is then always maxed.
func (*Queue) SetGlobalRateLimit ¶
SetGlobalRateLimit throttles every worker of this queue to at most max jobs per duration. For a worker that also has a Limiter, this max and the Limiter's Duration apply, as in Node.js. A max of 0 removes the limit, as RemoveGlobalRateLimit does.
func (*Queue) TrimEvents ¶
TrimEvents trims the queue's event stream to about maxLength events, as Node's trimEvents does, and returns how many it removed. Redis trims approximately (XTRIM MAXLEN ~), so a few more events may be left. The PostgreSQL backend can't (an error wrapping ErrNotSupported, as Node's throws): it trims the stream to QueueOptions.EventsMaxLen as it adds events.
func (*Queue) UpsertJobScheduler ¶
func (q *Queue) UpsertJobScheduler(ctx context.Context, id string, repeat RepeatOptions, template *JobTemplate) (*Job, error)
UpsertJobScheduler creates the job scheduler id, or replaces its schedule and template, and adds the job of its next iteration, which it returns. The scheduler then keeps producing jobs: each time a worker fetches one, it adds the job of the following iteration. The jobs have the id `repeat:<id>:<due time in Unix milliseconds>`.
It returns nil, without error, when the schedule produces no job: its limit is reached, or no time matching Pattern is left before EndDate (or QueueOptions.RepeatStrategy returned 0).
func (*Queue) Version ¶
Version returns the BullMQ version of the scripts of the library that last wrote the queue's metadata, as `bullmq:<version>` (Go writes `bullmq:<ScriptsVersion>`), or "" when none did, as Node's getVersion does.
func (*Queue) Workers ¶
func (q *Queue) Workers(ctx context.Context) ([]WorkerInfo, error)
Workers lists the workers connected to this queue, as Node's getWorkers does. Workers are found by the name of their dedicated connection, in CLIENT LIST on Redis and in pg_stat_activity on PostgreSQL. PostgreSQL stores each non-ASCII byte of a connection name as a 4-byte `\xhh` escape (a `?` before version 16, which loses the worker name's non-ASCII characters) and truncates the result to 63 bytes, so there the workers of a queue with a long name may be missing, and long worker names are truncated. Those escapes are decoded, so a worker name that itself contains `\x` followed by two hex digits of 80-ff (such as `w\xc3\xb6`) is listed decoded (`wö`): PostgreSQL stores both names the same way.
type QueueEvent ¶
type QueueEvent struct {
// ID is the opaque, backend-specific id of the event: a stream entry id
// such as `1700000000000-0` on Redis, a number such as `42` on
// PostgreSQL. Ids increase with every event; pass one as
// QueueEventsOptions.LastEventID to resume reading after that event.
ID string
// Event is the event name, for example `added`, `active`, `completed`,
// `failed`, `progress`, `delayed`, `waiting`, `stalled`, `removed`,
// `paused`, `resumed` or `drained`.
Event string
// JobID is the job the event refers to, when applicable.
JobID string
// Data holds every field of the event, including `event` and `jobId`.
Data map[string]string
}
QueueEvent is a single event of the queue's event stream.
func (QueueEvent) DecodeProgress ¶
func (e QueueEvent) DecodeProgress(out any) error
DecodeProgress decodes the progress value of a `progress` event into out.
func (QueueEvent) DecodeReturnValue ¶
func (e QueueEvent) DecodeReturnValue(out any) error
DecodeReturnValue decodes the JSON return value of a `completed` event into out, as Job.DecodeReturnValue does. It does nothing when the event has none.
func (QueueEvent) DelayedUntil ¶
func (e QueueEvent) DelayedUntil() (t time.Time, ok bool)
DelayedUntil returns when the job of a `delayed` event becomes due: its delay field, which holds Unix milliseconds rather than a duration, as in Node.js. ok is false when the event has no such field.
func (QueueEvent) FailedReason ¶
func (e QueueEvent) FailedReason() string
FailedReason returns the error message of a `failed` event.
func (QueueEvent) Progress ¶
func (e QueueEvent) Progress() (Progress, error)
Progress returns the progress value of a `progress` event: a number or any JSON value, read with Progress.Number or Progress.Decode.
func (QueueEvent) ReturnValue ¶
func (e QueueEvent) ReturnValue() string
ReturnValue returns the serialized processor result of a `completed` event.
type QueueEvents ¶
type QueueEvents struct {
// contains filtered or unexported fields
}
QueueEvents streams the global events emitted by a queue, allowing a process that does not run the worker to observe job progress.
func NewQueueEvents ¶
func NewQueueEvents(queueName string, opts *QueueEventsOptions) (*QueueEvents, error)
NewQueueEvents creates an event listener for the given queue.
func (*QueueEvents) Backend ¶
func (qe *QueueEvents) Backend() Backend
Backend returns the datastore backend of the listener. Type-assert it to the concrete backend, for example *redisbackend.Backend, to reach datastore-specific features such as its dedicated blocking client.
func (*QueueEvents) Close ¶
func (qe *QueueEvents) Close() error
Close stops the listener and releases the connection when it owns it.
func (*QueueEvents) Errors ¶
func (qe *QueueEvents) Errors() <-chan error
Errors returns the channel carrying non-fatal read errors. It is closed when the listener stops, after the last error has been sent.
func (*QueueEvents) Events ¶
func (qe *QueueEvents) Events() <-chan QueueEvent
Events returns the channel on which stream entries are delivered. It is closed when the listener stops.
func (*QueueEvents) Run ¶
func (qe *QueueEvents) Run(ctx context.Context) error
Run reads the event stream and delivers its events on the Events channel until it stops, then closes the Events and Errors channels.
- After Close it returns nil.
- When ctx is done it returns ctx's error.
- Read errors are sent on the Errors channel and retried a second later, but an error reading the id of the newest event at startup (for the default LastEventID `$`) is returned.
- It returns ErrQueueEventsClosed straight away when Run was already called or the listener is closed.
Call Close after Run returns because ctx was done, to release the listener's connection.
type QueueEventsOptions ¶
type QueueEventsOptions struct {
// Backend builds the datastore backend. It is required.
Backend BackendFactory
// LastEventID is the id of the event to start reading after: a
// [QueueEvent.ID], `0-0` (or `0`) to read every stored event, or `$`,
// the default, to read only the events produced once the listener
// starts.
LastEventID string
// BlockingTimeout is the longest a single read of the event stream waits
// for new events before reading again (XREAD BLOCK on Redis, a LISTEN
// wait on PostgreSQL). Defaults to 5s.
BlockingTimeout time.Duration
// BufferSize is the size of the delivery channel. Defaults to 128.
BufferSize int
}
QueueEventsOptions configures a QueueEvents listener.
type QueueEventsProducer ¶
type QueueEventsProducer struct {
// contains filtered or unexported fields
}
QueueEventsProducer publishes custom events on a queue's event stream, as Node's QueueEventsProducer does. The QueueEvents of every runtime receive them like the events of jobs: QueueEvent.Event is the event's name and QueueEvent.Data holds its fields.
A QueueEventsProducer is safe for concurrent use.
func NewQueueEventsProducer ¶
func NewQueueEventsProducer(name string, opts *QueueEventsProducerOptions) (*QueueEventsProducer, error)
NewQueueEventsProducer creates a producer of custom events for the queue called name.
func (*QueueEventsProducer) Backend ¶
func (p *QueueEventsProducer) Backend() Backend
Backend returns the datastore backend of the producer.
func (*QueueEventsProducer) Close ¶
func (p *QueueEventsProducer) Close() error
Close releases the connections the producer owns.
func (*QueueEventsProducer) PublishEvent ¶
func (p *QueueEventsProducer) PublishEvent(ctx context.Context, eventName string, fields map[string]any, maxEvents int64) (string, error)
PublishEvent appends an event called eventName to the event stream, with fields, and returns its id, as Node's publishEvent({eventName, ...fields}, maxEvents) does. String values are stored as they are, and other values as their JSON encoding; a field can't be called "event", which holds the name. On Redis the stream is trimmed to about maxEvents events (0 means DefaultMaxEvents); PostgreSQL trims it to the queue's EventsMaxLen instead. Don't use the names of the events of jobs (completed, failed, ...), which listeners would take for them.
type QueueEventsProducerOptions ¶
type QueueEventsProducerOptions struct {
// Backend builds the datastore backend. It is required.
Backend BackendFactory
}
QueueEventsProducerOptions configures a QueueEventsProducer.
type QueueMeta ¶
type QueueMeta struct {
// Concurrency is the global concurrency limit (SetGlobalConcurrency). A
// stored 0, which another runtime may write, holds every job.
Concurrency *int64
// Max is the number of jobs allowed per Duration by the global rate
// limit (SetGlobalRateLimit).
Max *int64
// Duration is the window of the global rate limit.
Duration *time.Duration
// MaxLenEvents is the approximate maximum length of the events stream.
MaxLenEvents *int64
// Paused reports whether the queue is paused.
Paused bool
// Version is the BullMQ version of the scripts of the library that last
// wrote the queue's metadata, as `bullmq:<version>` (Go writes
// `bullmq:<ScriptsVersion>`), or "" when none did.
Version string
}
QueueMeta is the queue's metadata, as Node's Queue.getMeta returns it. A numeric field is nil when it is not set.
type QueueOptions ¶
type QueueOptions struct {
// Backend builds the datastore backend, for example
// redisbackend.New(redisbackend.Options{Addr: "127.0.0.1:6379"}). It is
// required.
Backend BackendFactory
// DefaultJobOptions are merged into every job added to this queue.
DefaultJobOptions *JobOptions
// EventsMaxLen is the approximate maximum length of the queue's events
// stream, stored as the `opts.maxLenEvents` metadata, as Node's
// streams.events.maxLen. Defaults to 10000.
EventsMaxLen int64
// SkipMetasUpdate stops the queue from writing its metadata (version
// and opts.maxLenEvents), for example for a role that may only read.
SkipMetasUpdate bool
// RepeatStrategy, when set, computes the due times of the Pattern job
// schedulers this queue upserts, instead of cron (see [RepeatStrategy]).
// Set the same one on the workers.
RepeatStrategy RepeatStrategy
}
QueueOptions configures a Queue.
type RateLimiter ¶
type RateLimiter struct {
// Max is the maximum number of jobs per Duration.
Max int64
// Duration is the rate limit window. It is stored with millisecond
// precision, so sub-millisecond values are rounded down.
Duration time.Duration
}
RateLimiter throttles how many jobs a worker may process per time window.
type RemoveOnFinish ¶
type RemoveOnFinish struct {
// Count keeps at most Count finished jobs. A value of 0 removes the job
// straight away.
Count *int64 `json:"count,omitempty"`
// Age keeps finished jobs younger than Age, in seconds (not
// milliseconds), as in every port.
Age *int64 `json:"age,omitempty"`
// Limit caps how many jobs a single cleanup pass may remove.
Limit *int64 `json:"limit,omitempty"`
// contains filtered or unexported fields
}
RemoveOnFinish controls the automatic removal of completed or failed jobs.
Use RemoveAll, KeepCount or KeepAge to construct a value, or set Count, Age and Limit directly; the zero value keeps every finished job. It is stored in the three forms the other BullMQ ports write: a boolean (RemoveAll is stored as true), a count (KeepCount), or a {count, age, limit} object.
func KeepAge ¶
func KeepAge(seconds int64) *RemoveOnFinish
KeepAge keeps finished jobs younger than seconds, in seconds (not milliseconds): KeepAge(24 * 60 * 60) keeps a day.
func KeepCount ¶
func KeepCount(n int64) *RemoveOnFinish
KeepCount keeps at most n finished jobs. It is stored as the number n, as the other ports store `removeOnComplete: n`.
func RemoveAll ¶
func RemoveAll() *RemoveOnFinish
RemoveAll removes jobs as soon as they finish. It is stored as true, as the other ports store `removeOnComplete: true`.
func (*RemoveOnFinish) IsRemoveAll ¶
func (r *RemoveOnFinish) IsRemoveAll() bool
IsRemoveAll reports whether r is the boolean form true (RemoveAll): each job is removed as soon as it finishes, without trimming the other finished jobs. Backends that tell "remove this job" from "keep no finished job" apart (the shared PostgreSQL commands do) must check it rather than Count.
func (RemoveOnFinish) MarshalJSON ¶
func (r RemoveOnFinish) MarshalJSON() ([]byte, error)
MarshalJSON writes r in the form it was built or read in: true or false, a count, or an object. A count whose Age or Limit was set afterwards is written as an object, so they are kept.
func (*RemoveOnFinish) UnmarshalJSON ¶
func (r *RemoveOnFinish) UnmarshalJSON(data []byte) error
UnmarshalJSON accepts the boolean, numeric and object forms written by the other BullMQ ports. Fractional counts are rounded away from zero, so they keep their meaning (a positive count stays positive, a negative one keeps every job), fractional ages are rounded up and negative ages are ignored. Any other value is ignored, as if the option were not set.
type RepeatOptions ¶
type RepeatOptions struct {
// Pattern is a cron expression with 5 fields, or 6 with leading seconds,
// evaluated like cron-parser does in Node.js, in time zone Tz.
Pattern string `json:"pattern,omitempty"`
// Every repeats the job every this many milliseconds.
Every int64 `json:"every,omitempty"`
// Limit is the maximum number of jobs the scheduler produces. 0 means no
// limit.
Limit int64 `json:"limit,omitempty"`
// Immediately makes a Pattern scheduler produce its first job right away
// instead of at the first time matching the pattern. Every schedulers
// always produce their first job right away (or at StartDate).
Immediately bool `json:"immediately,omitempty"`
// Offset shifts the runs of an Every scheduler, in milliseconds.
Offset int64 `json:"offset,omitempty"`
// StartDate is when the schedule starts, in Unix milliseconds. 0 means
// now.
StartDate int64 `json:"startDate,omitempty"`
// EndDate is when the schedule ends, in Unix milliseconds. 0 means
// never.
EndDate int64 `json:"endDate,omitempty"`
// Tz is the time zone Pattern is evaluated in, as Node.js resolves it:
// an IANA name in any case, an ICU legacy id such as "PST", or a fixed
// offset such as "+03:00" or "UTC+3". Empty means the local time zone
// of the process, as in Node.js. Time zones are read from the system's
// time zone database; programs running where there is none can embed
// one with `import _ "time/tzdata"`.
Tz string `json:"tz,omitempty"`
// Count is the iteration of the job it is stored in. It is maintained
// by the scheduler and ignored by Queue.UpsertJobScheduler.
Count int64 `json:"count,omitempty"`
}
RepeatOptions describe the schedule of a job scheduler, as Node's RepeatOptions do. Exactly one of Pattern and Every must be set. Every, Offset, StartDate and EndDate are int64 milliseconds (dates are Unix milliseconds: use time.Time.UnixMilli), not time.Duration or time.Time.
The JSON form is the one every BullMQ port stores in the options of the jobs a scheduler produces (`opts.repeat`), with times in Unix milliseconds.
func (*RepeatOptions) UnmarshalJSON ¶
func (r *RepeatOptions) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes repeat options written by any BullMQ port, accepting numbers written as floats or strings, and dates written as ISO 8601 strings.
type RepeatStrategy ¶
type RepeatStrategy func(millis int64, opts RepeatOptions, jobName string) (int64, error)
RepeatStrategy computes when the next job of a Pattern scheduler is due, instead of evaluating Pattern as a cron expression, as Node's settings.repeatStrategy does. It is set on QueueOptions and WorkerOptions, and every queue and worker that schedules the iterations of a scheduler needs the same one, whatever its language.
millis is the time to compute the next run after (Unix milliseconds), opts the scheduler's repeat options, whose Count is the number of jobs produced so far, and jobName the name of its jobs. It returns when the next job is due (Unix milliseconds; a time in the past means now), or 0 when there is no next run, as Node's strategy returns undefined. Pattern can then be any string the strategy understands, such as an RRULE.
type RetryJobsOptions ¶
type RetryJobsOptions struct {
// State is the state of the jobs to retry: StateFailed (the default) or
// StateCompleted.
State JobState
// Count is how many jobs are moved per batch, one datastore call each,
// not a cap on the total; 0 means 1000.
Count int64
// Before only retries the jobs that finished at or before it; the zero
// time means now.
Before time.Time
}
RetryJobsOptions tunes Queue.RetryJobs, as the options of Node's retryJobs do.
type RetryOptions ¶
type RetryOptions struct {
// ResetAttemptsMade sets the job's attempts-made counter back to 0, so
// it gets every attempt of JobOptions.Attempts again.
ResetAttemptsMade bool
// ResetAttemptsStarted sets the job's attempts-started counter back to
// 0, which WorkerOptions.MaxStartedAttempts checks.
ResetAttemptsStarted bool
}
RetryOptions tunes Job.Retry, as Node's RetryOptions does.
type ScriptError ¶
ScriptError wraps a negative status code returned by a backend command: a Lua command on Redis, or a shared SQL command on PostgreSQL, which raises SQLSTATE BM001 with the same code. Script names the command. Code is one of the ErrCode constants, and errors.Is matches the corresponding sentinel error (for example ErrJobNotFound for ErrCodeJobNotExist).
func (*ScriptError) Error ¶
func (e *ScriptError) Error() string
func (*ScriptError) Unwrap ¶
func (e *ScriptError) Unwrap() error
type StalledOptions ¶
type StalledOptions struct {
// MaxStalledCount is how many times a job may stall before failing.
MaxStalledCount int
// Interval is the stalled check interval.
Interval time.Duration
}
StalledOptions configures Backend.MoveStalledJobsToWait.
type UnrecoverableError ¶
type UnrecoverableError struct {
Message string
}
UnrecoverableError makes a job fail immediately without consuming further attempts.
func (*UnrecoverableError) Error ¶
func (e *UnrecoverableError) Error() string
type WaitResult ¶
type WaitResult struct {
// Woken is true when the wait ended because the queue signalled work,
// and false when it timed out. Signals may be spurious.
Woken bool
// NextDelayedAt is when the next delayed job is due (Unix milliseconds),
// when the signal says so; 0 means a job may be ready now, or unknown.
NextDelayedAt int64
}
WaitResult is the outcome of Backend.WaitForJob.
type Worker ¶
type Worker struct {
// contains filtered or unexported fields
}
Worker fetches jobs from a queue and hands them to a Processor.
Every processing slot finishes its job and fetches the next one in the same backend call (fetch-next), as the Node.js worker does, so a busy worker needs about one round trip per job whatever its concurrency. The fetch loop only fetches to fill free slots, and blocks on the backend only once the queue looks drained.
func NewWorker ¶
func NewWorker(queueName string, proc Processor, opts *WorkerOptions) (*Worker, error)
NewWorker creates a worker for the given queue. Call Run to start processing.
A worker created with a nil proc processes nothing by itself: its jobs are fetched with GetNextJob and finished with Job.MoveToCompleted or Job.MoveToFailed, as in Node's manual mode (see GetNextJob).
func (*Worker) ActiveCount ¶
ActiveCount returns how many jobs are currently being processed.
func (*Worker) Backend ¶
Backend returns the datastore backend of the worker. Type-assert it to the concrete backend, for example *redisbackend.Backend, to reach datastore-specific features such as its dedicated blocking client.
func (*Worker) CancelAllJobs ¶
CancelAllJobs cancels every job this worker is processing, as CancelJob does.
func (*Worker) CancelJob ¶
CancelJob cancels the context of a job this worker is processing, with a cause (see context.Cause) that matches ErrJobCancelled and reads as reason. When the processor then returns an error, the job fails with it (and is retried if attempts remain), as Node.js's cancelJob records what the processor throws; a bare ctx.Err() fails it with reason. To keep the reason in an error of your own, wrap context.Cause(ctx). A processor that returns no error completes the job. It reports whether the job was being processed.
func (*Worker) Close ¶
Close stops the worker and waits for in-flight jobs to finish. It is safe to call more than once and from several goroutines; every call returns the same result.
func (*Worker) Concurrency ¶
Concurrency returns how many jobs the worker processes in parallel: WorkerOptions.Concurrency, or the value of the last SetConcurrency.
func (*Worker) DroppedEvents ¶
DroppedEvents returns how many events could not be delivered on the Events channel because its buffer was full.
func (*Worker) Events ¶
Events returns the channel on which lifecycle events are published. It is closed by Close.
The channel is buffered; events are dropped when the consumer falls behind, so a worker never blocks on event delivery. DroppedEvents counts them. Use WorkerOptions.OnEvent to observe every event.
func (*Worker) GetNextJob ¶
GetNextJob fetches the next job of a worker without a processor and locks it with token, as Node's worker.getNextJob does. It returns nil when no job can be fetched: the queue is empty, paused, rate limited or at its global concurrency limit, or the worker is paused. When block is set and the queue is empty, it waits for a job for up to DrainDelay, fetching again whenever the queue signals one or a delayed job is due, or until ctx is done or the worker is closed.
The job is locked for LockDuration and its lock is not renewed: finish it with Job.MoveToCompleted or Job.MoveToFailed, with the same token, before the lock expires, or extend the lock with Job.ExtendLock. A job whose lock expires is moved back to wait by the stalled check of any worker (see StartStalledCheck), and its token no longer finishes it.
As in Node.js, it emits EventActive for the job and, for the job of a job scheduler, first adds the job of the scheduler's next iteration. Jobs fetched by hand don't count for Pause and ActiveCount. GetNextJob may be called concurrently; calls that block wait in turn. It returns ErrWorkerClosed once the worker is closed.
func (*Worker) Pause ¶
Pause stops this worker from starting new jobs, as Node's pause does. Unless doNotWaitActive is set, it then waits until the jobs being processed have finished, or until ctx is done (returning ctx's error), the worker is resumed, or it is closed (returning ErrWorkerClosed). The Pause that paused the worker then emits EventPaused, unless the worker was resumed or closed meanwhile. A paused worker keeps checking for stalled jobs, unlike Node's.
It may be called from WorkerOptions.OnEvent: from EventDrained, or from the EventCompleted or EventFailed of a job, it waits for the other jobs only. A processor pausing its own worker, or a callback for an event emitted while its job runs (EventActive, EventProgress), must set doNotWaitActive, since Pause would otherwise wait for that job.
func (*Worker) RateLimit ¶
RateLimit rate limits the whole queue for d, as Node's rateLimit does: until it expires, workers that fetch with a limiter (WorkerOptions.Limiter or a global rate limit) get no job. A processor typically calls it and then returns ErrRateLimited, which puts its job back in the wait list.
func (*Worker) Resume ¶
func (w *Worker) Resume()
Resume restarts fetching jobs after Pause, and emits EventResumed when the worker was paused.
func (*Worker) Run ¶
Run starts the worker and blocks until it stops.
- After Close it stops fetching, waits for the jobs being processed to finish, and returns nil.
- When ctx is done it stops fetching and cancels the context of the jobs being processed, which are left active for the stalled check to recover (see Processor). Once their processors have returned, it returns ctx's error, even if Close was also called.
- It returns ErrWorkerClosed straight away when Run was already called or the worker is closed, and a ConfigError for a worker without a processor.
Call Close after Run returns because ctx was done, to release the worker's connections.
func (*Worker) SetConcurrency ¶
SetConcurrency changes how many jobs the worker processes in parallel while it runs, as setting Node's worker.concurrency does. Raising it fetches jobs for the new slots right away. Lowering it lets the jobs in flight finish: a slot finishing a job fetches no next job while more slots than n are in use. n must be at least 1.
func (*Worker) StartStalledCheck ¶
StartStalledCheck starts the stalled check of a worker without a processor, as Node's startStalledCheckTimer does: right away and then every StalledInterval until the worker is closed, it moves the active jobs whose lock expired back to wait, or fails those that stalled more than MaxStalledCount times, and reports them with EventStalled. Calling it again does nothing, nor does it when SkipStalledCheck is set. A worker with a processor checks for stalled jobs while it runs, so it returns a ConfigError there.
type WorkerInfo ¶
type WorkerInfo struct {
// Name is the worker's name (WorkerOptions.Name), or "" for a worker
// without one.
Name string
// Fields holds what the datastore reports about the worker's
// connection: every field of its CLIENT LIST entry on Redis (id, addr,
// age, idle, ...), only name on PostgreSQL. Fields["name"] is the raw
// connection name, which encodes the queue: `{prefix}:{base64(queue)}`
// followed by `:w:{name}` for a named worker on Redis, `{queue}` and
// `:w:{name}` on PostgreSQL, where it is reported as the worker set it,
// with PostgreSQL's `\xhh` escaping of non-ASCII bytes undone.
Fields map[string]string
}
WorkerInfo describes a worker connected to a queue, as listed by Queue.Workers.
type WorkerOptions ¶
type WorkerOptions struct {
// Backend builds the datastore backend. It is required.
Backend BackendFactory
// Name identifies the worker; stored on each processed job as `pb`.
Name string
// Concurrency is the number of jobs processed in parallel. Defaults to 1.
// Worker.SetConcurrency changes it while the worker runs.
Concurrency int
// LockDuration is how long a job lock is held. Defaults to 30s. A positive
// value must be at least 1ms, since the lock TTL is stored in milliseconds,
// and at least 2ms unless SkipLockRenewal is set (the renewal interval
// must be at least 1ms and less than LockDuration).
LockDuration time.Duration
// LockRenewTime is how often the lock is renewed. Defaults to LockDuration/2.
// When renewal is enabled it must be at least 1ms (the lock TTL is stored
// in milliseconds) and less than LockDuration, so the lock is renewed
// before it expires.
LockRenewTime time.Duration
// StalledInterval is how often stalled jobs are checked. Defaults to 30s.
// A positive value must be at least 1ms unless SkipStalledCheck is set,
// since it is stored as a millisecond lock TTL.
StalledInterval time.Duration
// MaxStartedAttempts fails a job unrecoverably ("job started more than
// allowable limit") when it is started more than this many times, for
// example because it keeps stalling. 0, the default, means no limit.
// Negative values are rejected.
MaxStartedAttempts int
// MaxStalledCount is how many times a job may stall before failing. Defaults to 1.
// Use a pointer so an explicit 0 (fail on first stall) is distinguishable
// from unset. Negative values are rejected.
MaxStalledCount *int
// SkipStalledCheck disables the stalled job checker.
SkipStalledCheck bool
// SkipLockRenewal disables automatic lock renewal.
SkipLockRenewal bool
// DrainDelay is how long a blocking fetch waits for new jobs. Defaults to 5s.
DrainDelay time.Duration
// Limiter throttles job processing.
Limiter *RateLimiter
// MaximumRateLimitDelay caps how long the worker sleeps in one go while
// the queue is rate limited, so delayed jobs keep being promoted during a
// long limit. Defaults to 30s.
MaximumRateLimitDelay time.Duration
// Metrics enables completed/failed metrics collection.
Metrics *MetricsOptions
// RemoveOnComplete is the default removal policy for completed jobs.
RemoveOnComplete *RemoveOnFinish
// RemoveOnFail is the default removal policy for failed jobs.
RemoveOnFail *RemoveOnFinish
// BackoffStrategy computes a custom retry delay in milliseconds. Returning
// a negative value discards the job.
BackoffStrategy func(attemptsMade int64, backoffType BackoffType, err error, job *Job) int64
// RepeatStrategy, when set, computes the due time of the next iteration
// of a Pattern job scheduler when the worker fetches one of its jobs,
// instead of cron (see [RepeatStrategy]). It must match the one of the
// queue that upserted the scheduler.
RepeatStrategy RepeatStrategy
// OnEvent, when set, is called synchronously with every event the worker
// emits, including those dropped from a full Events channel. It runs on
// the worker's goroutines (a slow callback slows processing down), may
// be called concurrently, and must not call Worker.Close, which waits
// for those goroutines; start a goroutine for that instead. It may call
// Worker.Pause, for example on EventDrained (see Pause for the events it
// must not wait from).
OnEvent func(Event)
// OnError is called for background errors that cannot be returned to a caller.
// It runs on its own goroutine, so it may safely call Worker.Close, but
// calls can be concurrent and are not ordered; the callback must be safe
// for concurrent use.
OnError func(err error)
}
WorkerOptions configures a Worker.
Source Files
¶
- backend.go
- backend_access.go
- doc.go
- errors.go
- event_stream.go
- flow_producer.go
- flow_types.go
- job.go
- job_flow.go
- job_scheduler.go
- job_transitions.go
- options.go
- parent_completion.go
- queue.go
- queue_counts.go
- queue_event_decode.go
- queue_events.go
- queue_meta.go
- queue_remove.go
- scripts_version.go
- types.go
- util.go
- version.go
- worker.go
- worker_concurrency.go
- worker_manual.go
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
cronparity
Package cronparity evaluates cron expressions exactly like cron-parser 5.10.6, the library and version the Node.js BullMQ uses for job scheduler patterns, so a Go worker computes the same next runs, and therefore the same job ids, as a Node.js worker would.
|
Package cronparity evaluates cron expressions exactly like cron-parser 5.10.6, the library and version the Node.js BullMQ uses for job scheduler patterns, so a Go worker computes the same next runs, and therefore the same job ids, as a Node.js worker would. |
|
queuemeta
Package queuemeta writes the metadata of a queue (bullmq.BackendOptions.
|
Package queuemeta writes the metadata of a queue (bullmq.BackendOptions. |
|
testbackends
Package testbackends lists the datastores that the shared behaviour tests of package bullmq run against, together with the datastore-level fixtures some of those tests need.
|
Package testbackends lists the datastores that the shared behaviour tests of package bullmq run against, together with the datastore-level fixtures some of those tests need. |
|
Package postgresbackend is the PostgreSQL implementation of bullmq.Backend.
|
Package postgresbackend is the PostgreSQL implementation of bullmq.Backend. |
|
Package redisbackend is the Redis implementation of bullmq.Backend.
|
Package redisbackend is the Redis implementation of bullmq.Backend. |