Documentation
¶
Overview ¶
Package queue runs slow work asynchronously in background worker processes so HTTP requests can respond immediately.
Define a job as a struct holding its input data with a Handle(ctx context.Context) error method, register the job type in laravel.Options.Jobs, dispatch it with Dispatch, and run queue:work to process it:
_, err := queue.Dispatch(r, jobs.ProcessPodcast{PodcastID: podcast.ID})
Use OnConnection, OnQueue, Delay, DelayUntil, OnGroup, and DeduplicationID to customize routing and timing, or compose multiple jobs with NewChain and NewBatch.
A struct field tagged queue:"model" may hold a model, a pointer to a model, or a slice of models. The queue stores only each model's primary key and reloads the rows from the default database's writer connection before Handle runs, so a worker finds rows created right before dispatch even when read replicas are configured. For a model on another database, name its connection in the tag, such as queue:"model,connection=reporting". By default, if a referenced row no longer exists when the job runs, the worker deletes the job without running it. Set Options.FailWhenMissingModels to fail the job with a *MissingModelsError instead.
A job's Handle method returns nil on success, an error to fail and retry according to its Options, or the sentinel errors from Release, Delete, or Fail to control what happens next.
Index ¶
- Constants
- func CancelBatch(ctx context.Context, id BatchID) error
- func Clear(ctx context.Context, connection, queue string) (int64, error)
- func CreateTables(ctx context.Context) error
- func Delete() error
- func DispatchSync(ctx context.Context, job any) error
- func Fail(err error) error
- func NewID() string
- func PruneBatches(ctx context.Context, before time.Time, which Prune) (int64, error)
- func Release(delay time.Duration) error
- func Retry(ctx context.Context, job FailedJob) error
- func RetryBatch(ctx context.Context, id BatchID) (int, error)
- type Attempt
- func (a *Attempt) AddToBatch(jobs ...any)
- func (a *Attempt) AppendToChain(jobs ...any)
- func (a *Attempt) Batch() BatchID
- func (a *Attempt) CancelBatch()
- func (a *Attempt) Connection() string
- func (a *Attempt) ID() JobID
- func (a *Attempt) Name() string
- func (a *Attempt) Number() int
- func (a *Attempt) PrependToChain(jobs ...any)
- func (a *Attempt) Queue() string
- type Attempted
- type Batch
- type BatchID
- type BatchStore
- type Batched
- type BulkPusher
- type Chain
- func (c *Chain) Catch(callbacks ...any) *Chain
- func (c *Chain) Delay(d time.Duration) *Chain
- func (c *Chain) DelayUntil(t time.Time) *Chain
- func (c *Chain) Dispatch(ctx context.Context) (JobID, error)
- func (c *Chain) OnConnection(name string) *Chain
- func (c *Chain) OnQueue(name string) *Chain
- func (c *Chain) Then(jobs ...any) *Chain
- type Config
- type Connection
- type DatabaseDriver
- func (d *DatabaseDriver) Clear(ctx context.Context, queue string) (int64, error)
- func (d *DatabaseDriver) Push(ctx context.Context, queue string, payload []byte, delay time.Duration) error
- func (d *DatabaseDriver) PushBulk(ctx context.Context, queue string, payloads [][]byte) error
- func (d *DatabaseDriver) Reserve(ctx context.Context, queues []string) (Reserved, error)
- func (d *DatabaseDriver) Sizes(ctx context.Context, queue string) (Sizes, error)
- type Driver
- type FailedJob
- type FailedJobs
- func (f *FailedJobs) All(ctx context.Context) ([]FailedJob, error)
- func (f *FailedJobs) Find(ctx context.Context, id JobID) (FailedJob, bool, error)
- func (f *FailedJobs) Flush(ctx context.Context, before time.Time) (int64, error)
- func (f *FailedJobs) Forget(ctx context.Context, id JobID) (bool, error)
- type Failer
- type JobFailed
- type JobID
- type JobInfo
- type JobProcessed
- type Middleware
- type MissingModelsError
- type Options
- type Outcome
- type PanicError
- type PendingBatch
- func (b *PendingBatch) AllowFailures() *PendingBatch
- func (b *PendingBatch) Catch(callbacks ...any) *PendingBatch
- func (b *PendingBatch) Delay(d time.Duration) *PendingBatch
- func (b *PendingBatch) DelayUntil(t time.Time) *PendingBatch
- func (b *PendingBatch) Dispatch(ctx context.Context) (BatchID, error)
- func (b *PendingBatch) Finally(callbacks ...any) *PendingBatch
- func (b *PendingBatch) Name(name string) *PendingBatch
- func (b *PendingBatch) OnConnection(name string) *PendingBatch
- func (b *PendingBatch) OnQueue(name string) *PendingBatch
- func (b *PendingBatch) Then(callbacks ...any) *PendingBatch
- type PendingDispatch
- func (p *PendingDispatch) Batch(jobs ...any) *PendingBatch
- func (p *PendingDispatch) Bulk(ctx context.Context, jobs ...any) ([]JobID, error)
- func (p *PendingDispatch) Chain(jobs ...any) *Chain
- func (p *PendingDispatch) DeduplicationID(id string) *PendingDispatch
- func (p *PendingDispatch) Delay(d time.Duration) *PendingDispatch
- func (p *PendingDispatch) DelayUntil(t time.Time) *PendingDispatch
- func (p *PendingDispatch) Dispatch(ctx context.Context, job any) (JobID, error)
- func (p *PendingDispatch) OnConnection(name string) *PendingDispatch
- func (p *PendingDispatch) OnGroup(group string) *PendingDispatch
- func (p *PendingDispatch) OnQueue(name string) *PendingDispatch
- type Processed
- type Prune
- type Pushed
- type Queue
- func (q *Queue) Attempt(ctx context.Context, job any, number int, batch BatchID) Attempted
- func (q *Queue) Batch(jobs ...any) *PendingBatch
- func (q *Queue) Bulk(ctx context.Context, jobs ...any) ([]JobID, error)
- func (q *Queue) CancelBatch(ctx context.Context, id BatchID) error
- func (q *Queue) Chain(jobs ...any) *Chain
- func (q *Queue) CheckConnection(name string) error
- func (q *Queue) Clear(ctx context.Context, connection, queue string) (int64, error)
- func (q *Queue) Close() error
- func (q *Queue) Connection(name string) *Queue
- func (q *Queue) DeduplicationID(id string) *Queue
- func (q *Queue) DefaultConnection() string
- func (q *Queue) Delay(d time.Duration) *Queue
- func (q *Queue) DelayUntil(t time.Time) *Queue
- func (q *Queue) Delays(connection string) bool
- func (q *Queue) Dispatch(ctx context.Context, job any) (JobID, error)
- func (q *Queue) DispatchSync(ctx context.Context, job any) error
- func (q *Queue) Failed() *FailedJobs
- func (q *Queue) Fake(r Recorder) bool
- func (q *Queue) FindBatch(ctx context.Context, id BatchID) (*Batch, bool, error)
- func (q *Queue) OnGroup(group string) *Queue
- func (q *Queue) OnQueue(name string) *Queue
- func (q *Queue) PruneBatches(ctx context.Context, before time.Time, which Prune) (int64, error)
- func (q *Queue) QueueOf(connection string) (string, bool)
- func (q *Queue) Retry(ctx context.Context, job FailedJob) error
- func (q *Queue) RetryBatch(ctx context.Context, id BatchID) (int, error)
- func (q *Queue) Sizes(ctx context.Context, connection, queue string) (Sizes, bool, error)
- func (q *Queue) Worker(connection string) (*Worker, error)
- type Recorder
- type Reserved
- type Sizer
- type Sizes
- type TimeoutError
- type UndecodableError
- type UnknownJobError
- type Worker
Constants ¶
const Heartbeat = 15 * time.Second
Heartbeat is how often a worker renews the reservation of a running job.
const Lease = 60 * time.Second
Lease is how long a job reservation remains valid without renewal. If a worker crashes or stops renewing its reservation, the job becomes available to other workers after Lease elapses.
Variables ¶
This section is empty.
Functions ¶
func CancelBatch ¶
CancelBatch cancels the batch with the given id on the application queue carried by ctx, matching Queue.CancelBatch.
func Clear ¶
Clear deletes all jobs waiting on the named connection and queue and returns the number of removed jobs, matching Queue.Clear.
func CreateTables ¶
CreateTables creates the jobs, failed_jobs, job_batches, and job_batch_jobs tables used by the database queue driver, failed job tracking, and job batches. Register it directly in database/migrations/migrations.go:
{Name: "0001_01_01_000002_create_jobs_table", Run: queue.CreateTables}
Table names follow DB_QUEUE_TABLE, DB_QUEUE_FAILED_TABLE, and cfg.Queue.Batches when configured.
func Delete ¶
func Delete() error
Delete returns a control error that removes the job from the queue without retrying or recording it as failed. Return it from a job's Handle method or Middleware when the work is no longer needed.
func DispatchSync ¶
DispatchSync runs job immediately in the current process using the application queue carried by ctx and returns its error. DispatchSync panics if ctx does not carry an application scope.
func Fail ¶
Fail returns a control error that fails the job permanently with err without retrying it. If err is nil, a generic failure error is used.
func NewID ¶
func NewID() string
NewID generates a version 7 UUID using 48 bits of Unix millisecond timestamp followed by random bits, matching the format of JobID and BatchID.
func PruneBatches ¶
PruneBatches deletes batches older than before that match which and returns the number of deleted batches, matching Queue.PruneBatches.
func Release ¶
Release returns a control error that tells the worker to put the job back on its queue after delay. Return it from a job's Handle method or Middleware:
if !podcast.Uploaded {
return queue.Release(30 * time.Second)
}
Each release counts toward Options.Tries, so jobs that release themselves repeatedly should configure Options.RetryFor instead.
func Retry ¶
Retry re-dispatches a permanently failed job onto its original connection and queue, matching Queue.Retry.
func RetryBatch ¶
RetryBatch re-dispatches every failed job in the batch with the given id and returns how many jobs were retried, matching Queue.RetryBatch.
Types ¶
type Attempt ¶
type Attempt struct {
// contains filtered or unexported fields
}
Attempt describes the currently executing attempt of a job. Retrieve it from the job's context with AttemptOf to inspect attempt metadata or modify the job's chain or batch.
func AttemptOf ¶
AttemptOf returns the *Attempt associated with ctx. It panics if ctx does not belong to an active job attempt, because only a job's Handle method, its middleware, and its Failed method receive an attempt context.
func (*Attempt) AddToBatch ¶
AddToBatch adds jobs to the job's batch so the batch waits for them before finishing. It panics if the job is not part of a batch.
func (*Attempt) AppendToChain ¶
AppendToChain schedules jobs to run at the end of the current chain. If the job is not in a chain, this starts one. The appended jobs are dispatched only if this attempt succeeds or returns Delete.
func (*Attempt) Batch ¶
Batch returns the BatchID the job belongs to, or an empty string if the job is not part of a batch.
func (*Attempt) CancelBatch ¶
func (a *Attempt) CancelBatch()
CancelBatch cancels the job's batch once this attempt returns. Remaining jobs in the batch are skipped when reserved, and the batch's Then callbacks do not run. It panics if the job is not part of a batch.
func (*Attempt) Connection ¶
Connection returns the name of the queue connection the job was reserved from.
func (*Attempt) PrependToChain ¶
PrependToChain schedules jobs to run next, ahead of any remaining jobs in the current chain. If the job is not in a chain, this starts one. The prepended jobs are dispatched only if this attempt succeeds or returns Delete.
type Attempted ¶
type Attempted struct {
// Outcome is one of [Succeeded], [Released], [Deleted], [MissingModels],
// or [Failed].
Outcome Outcome
// Delay is the release delay when Outcome is [Released].
Delay time.Duration
// Err is the error returned by the job when Outcome is [Failed].
Err error
// Retryable reports whether a worker would retry this failure if the job's
// options allow another attempt.
Retryable bool
// Chained holds the jobs prepended or appended to the chain during the
// attempt, in execution order.
Chained []any
// AddedToBatch holds the jobs added to the batch with
// [Attempt.AddToBatch] during the attempt.
AddedToBatch []any
// CancelledBatch reports whether the attempt called [Attempt.CancelBatch].
CancelledBatch bool
}
Attempted records the outcome of a single job attempt executed by Queue.Attempt in tests.
type Batch ¶
type Batch struct {
// ID is the unique identifier assigned when the batch was dispatched.
ID BatchID `json:"id"`
// Name is the optional display name set with [PendingBatch.Name].
Name string `json:"name"`
// TotalJobs is the total number of jobs in the batch, including jobs added
// dynamically with [Attempt.AddToBatch].
TotalJobs int `json:"total_jobs"`
// PendingJobs is the number of jobs that have not yet succeeded or been
// skipped.
PendingJobs int `json:"pending_jobs"`
// FailedJobs is the number of jobs in the batch that failed permanently.
FailedJobs int `json:"failed_jobs"`
// CreatedAt is the time the batch was created.
CreatedAt time.Time `json:"created_at"`
// CancelledAt is the time the batch was canceled, or nil if it has not
// been canceled.
CancelledAt *time.Time `json:"cancelled_at"`
// FinishedAt is the time every job in the batch finished, or nil if the
// batch is still running.
FinishedAt *time.Time `json:"finished_at"`
}
Batch describes the state and progress of a dispatched job batch loaded with Queue.FindBatch. It marshals to JSON with computed processed_jobs and progress fields so an HTTP handler can return it directly.
func FindBatch ¶
FindBatch loads the Batch with the given id from the application queue carried by ctx, matching Queue.FindBatch. It returns false with a nil error if no batch has that id:
batch, ok, err := queue.FindBatch(r, id)
func (*Batch) Cancelled ¶
Cancelled reports whether the batch was canceled, either manually or because a job failed without PendingBatch.AllowFailures.
func (*Batch) MarshalJSON ¶
MarshalJSON encodes the batch along with its computed processed_jobs and progress fields so clients polling the batch do not have to calculate them.
func (*Batch) ProcessedJobs ¶
ProcessedJobs returns the number of jobs in the batch that have succeeded or been skipped.
type BatchStore ¶
type BatchStore struct {
// contains filtered or unexported fields
}
BatchStore persists job batch progress in two database tables: one row per batch (typically job_batches) and one row per member job (typically job_batch_jobs).
func NewBatchStore ¶
func NewBatchStore(conn *db.DB, table, jobsTable string) *BatchStore
NewBatchStore returns a *BatchStore backed by table and jobsTable on conn.
type Batched ¶
type Batched struct {
// ID is the [BatchID] assigned to the batch.
ID BatchID
// Name is the optional display name set with [PendingBatch.Name].
Name string
// Jobs holds the batch's jobs as a worker would receive them. A chain
// member is represented as a []any of its jobs in order.
Jobs []any
// Then, Catch, and Finally hold the callback values registered on the
// batch.
Then, Catch, Finally []any
// AllowFailures reports whether [PendingBatch.AllowFailures] was set.
AllowFailures bool
// Connection and Queue are the routing overrides set on the batch.
Connection, Queue string
}
Batched describes a dispatched batch captured by a Recorder.
type BulkPusher ¶
type BulkPusher interface {
// PushBulk appends payloads to queue in order so they are immediately
// available. If an error occurs partway through, earlier payloads may
// already be stored.
PushBulk(ctx context.Context, queue string, payloads [][]byte) error
}
BulkPusher is an optional Driver interface for storing multiple immediate jobs in a single round trip. Without it, Queue.Bulk pushes each job individually.
type Chain ¶
type Chain struct {
// contains filtered or unexported fields
}
Chain represents a sequence of jobs that run one after another. Each step is dispatched only after the previous step succeeds, so a permanent failure stops the remaining steps from running. A job that returns Release pauses the chain until it runs again and succeeds, while a job that returns Delete allows the chain to continue. Create a Chain with NewChain or Queue.Chain.
func NewChain ¶
NewChain creates a Chain that runs jobs sequentially in order. A step may also be a *PendingBatch from NewBatch, in which case the chain continues after every job in that batch completes:
_, err := queue.NewChain(
jobs.ProcessPodcast{PodcastID: id},
jobs.OptimizePodcast{PodcastID: id},
jobs.ReleasePodcast{PodcastID: id},
).Dispatch(ctx)
Calling Chain.Dispatch uses the application queue carried by ctx.
func (*Chain) Catch ¶
Catch returns a copy of c that runs callbacks when a job in the chain fails permanently. Each callback must be registered in laravel.Options.Jobs and define Catch(ctx context.Context, err error) error (or also accept a *queue.Batch parameter, which receives nil for a chain). The worker invokes catch callbacks immediately before the failed job's Failed method and logs any callback error without retrying.
func (*Chain) Delay ¶
Delay returns a copy of c whose first job waits d before becoming available to workers. Jobs on SyncDriver still run immediately.
func (*Chain) DelayUntil ¶
DelayUntil returns a copy of c whose first job waits until t on the application's clock before becoming available to workers.
func (*Chain) Dispatch ¶
Dispatch pushes the chain's first step onto the queue and returns its JobID, or an empty string if the chain is empty or its first step is a *PendingBatch. Inside a database transaction, the chain is dispatched after the outermost transaction commits.
func (*Chain) OnConnection ¶
OnConnection returns a copy of c whose jobs dispatch on the named connection. Dispatching panics if the application does not configure that connection.
type Config ¶
type Config struct {
// Default names the connection used when a dispatch does not specify one.
Default string
// Connections maps connection names to their backend drivers and default
// queues.
Connections map[string]Connection
// Testing routes every dispatch to the Default connection regardless of
// the connection named by the dispatch, so tests execute all jobs on the
// default (usually sync) connection.
Testing bool
// Jobs lists a zero value of each job and callback type the queue may
// serialize and run, such as jobs.ProcessPodcast{}.
Jobs []any
// Cache stores shared queue state including debounced dispatches, error
// counts, and the restart and pause signals used by queue:restart and
// queue:pause. If nil, [New] uses an in-memory cache.
Cache *cache.Cache
// Failed stores jobs that have failed permanently. If nil, permanently
// failed jobs are not recorded.
Failed *FailedJobs
// Batches persists job batch progress. If nil, dispatching a batch returns
// an error.
Batches *BatchStore
// Databases maps database connection names to their [*db.DB] handles for
// reloading fields tagged queue:"model". Use "" for the default database.
Databases map[string]*db.DB
// Logger receives errors from failed jobs and workers. If nil, [New] uses
// [slog.Default].
Logger *slog.Logger
// Events receives [JobProcessed] after each worker run and [JobFailed]
// after a job fails permanently. If nil, no events are emitted.
Events func(ctx context.Context, event any)
// Unit wraps ctx to start a fresh unit of work for each job attempt,
// shared across the job's middleware and Failed method. If nil, jobs run
// with the caller's context.
Unit func(ctx context.Context) context.Context
}
Config configures a Queue created by New. The laravel package builds this automatically from the application's configuration and options.
type Connection ¶
type Connection struct {
// Driver stores and reserves jobs for this connection.
Driver Driver
// Queue is the default queue name for this connection, or "default" when
// empty.
Queue string
}
Connection pairs a Driver backend with the default queue name used when a dispatch does not specify one. If Driver implements io.Closer, Queue.Close closes it when the application shuts down.
type DatabaseDriver ¶
type DatabaseDriver struct {
// contains filtered or unexported fields
}
DatabaseDriver is a Driver, BulkPusher, and Sizer that stores queued jobs in a SQL database table with columns id, queue, payload, attempts, reserved_at, available_at, and created_at. Multiple workers can share the table safely, and each job is claimed by only one worker at a time.
func NewDatabaseDriver ¶
func NewDatabaseDriver(conn *db.DB, table string) *DatabaseDriver
NewDatabaseDriver returns a *DatabaseDriver that stores jobs in table (typically "jobs") on conn.
func (*DatabaseDriver) Clear ¶
Clear deletes all rows on queue and returns the number of deleted jobs.
func (*DatabaseDriver) Push ¶
func (d *DatabaseDriver) Push(ctx context.Context, queue string, payload []byte, delay time.Duration) error
Push inserts payload into the jobs table so it becomes available on queue after delay.
func (*DatabaseDriver) PushBulk ¶
PushBulk inserts payloads into the jobs table in batches so they are immediately available on queue.
type Driver ¶
type Driver interface {
// Push stores payload on queue so it becomes available after delay.
Push(ctx context.Context, queue string, payload []byte, delay time.Duration) error
// Reserve claims the next available job from the first queue in queues
// that has one. It returns nil with a nil error if no job is available.
// Implementations may long-poll for incoming jobs, but must return when
// ctx is canceled.
Reserve(ctx context.Context, queues []string) (Reserved, error)
// Clear deletes all jobs on queue and returns the number of jobs removed.
Clear(ctx context.Context, queue string) (int64, error)
}
Driver stores queued jobs and leases each one to a single worker at a time. The framework provides drivers for SQL databases (NewDatabaseDriver), Redis, SQS, synchronous execution (SyncDriver), and discarding jobs (DiscardDriver). Register a custom Driver in laravel.Options.QueueConnections:
laravel.Options{
QueueConnections: map[string]queue.Connection{
"beanstalkd": {Driver: beanstalkd.New("127.0.0.1:11300"), Queue: "default"},
},
}
A Driver stores opaque payloads without handling retries, timeouts, or failed jobs. The worker makes those decisions and settles each job through its Reserved handle. Reservations last for Lease and are renewed every Heartbeat while a job runs. When a reservation expires, the job becomes available again and the next reservation counts as a new attempt.
A Driver may optionally implement BulkPusher and Sizer, and its Reserved handles may implement Failer.
var DiscardDriver Driver = discardDriver{}
DiscardDriver drops every dispatched job without storing or running it.
var SyncDriver Driver = syncDriver{}
SyncDriver runs each job synchronously in the calling process during dispatch and returns the job's error directly.
func Unavailable ¶
Unavailable returns a Driver that fails every operation with err. Use it for a configured connection whose backend cannot be initialized. Queue.CheckConnection returns err for that connection.
type FailedJob ¶
type FailedJob struct {
// ID is the [JobID] assigned when the job was dispatched.
ID JobID
// Connection is the queue connection on which the job ran.
Connection string
// Queue is the queue name from which the job was reserved.
Queue string
// Payload is the raw JSON payload of the queued job.
Payload []byte
// Error is the error message that caused the permanent failure.
Error string
// FailedAt is the time the failure was recorded.
FailedAt time.Time
}
FailedJob represents a job that failed permanently and was recorded in FailedJobs.
type FailedJobs ¶
type FailedJobs struct {
// contains filtered or unexported fields
}
FailedJobs stores permanently failed jobs in a SQL database table with columns id, job_id, connection, queue, payload, error, and failed_at. The queue:failed command lists stored failures and queue:retry re-dispatches them.
func NewFailedJobs ¶
func NewFailedJobs(conn *db.DB, table string) *FailedJobs
NewFailedJobs returns a *FailedJobs store backed by table (typically "failed_jobs") on conn.
func (*FailedJobs) All ¶
func (f *FailedJobs) All(ctx context.Context) ([]FailedJob, error)
All returns all recorded failed jobs ordered from most recent to oldest.
func (*FailedJobs) Find ¶
Find returns the FailedJob with the given id. It returns false with a nil error if no failed job has that id.
type Failer ¶
type Failer interface {
// Fail removes the job from the active queue, records the permanent
// failure with err in the backend, and reports whether this worker still
// owned the job.
Fail(ctx context.Context, err error) (bool, error)
}
Failer is an optional interface for Reserved jobs whose backend records permanently failed jobs itself, such as Laravel Cloud. When implemented, the worker calls Fail instead of Reserved.Delete and skips recording the job in the application's FailedJobs table.
type JobFailed ¶
type JobFailed struct {
// Job identifies the job that failed.
Job JobInfo
// Err is the error that caused the permanent failure.
Err error
}
JobFailed is emitted after a job fails permanently on a worker.
type JobID ¶
type JobID string
JobID identifies a single dispatched job across all of its attempts. It is a version 7 UUID, so IDs sort chronologically by dispatch time.
func Bulk ¶
Bulk dispatches multiple jobs on the application queue carried by ctx, matching Queue.Bulk. Bulk panics if ctx does not carry an application scope.
func Dispatch ¶
Dispatch pushes job onto the application queue carried by ctx and returns its JobID, matching Queue.Dispatch:
_, err := queue.Dispatch(r, jobs.ProcessPodcast{PodcastID: podcast.ID})
Inside a database transaction, the job is pushed after the outermost transaction commits and is discarded if the transaction rolls back. Dispatch panics if ctx does not carry an application scope.
type JobInfo ¶
type JobInfo struct {
// ID is the [JobID] assigned when the job was dispatched.
ID JobID
// Name is the registered job name.
Name string
// Connection is the queue connection on which the job ran.
Connection string
// Queue is the queue name from which the job was reserved.
Queue string
// Attempt is the 1-based attempt number for this execution.
Attempt int
}
JobInfo identifies the job associated with a JobProcessed or JobFailed event.
type JobProcessed ¶
type JobProcessed struct {
// Job identifies the job that ran.
Job JobInfo
// Outcome describes how the attempt ended.
Outcome Outcome
// Duration is the total elapsed time to process and settle the job.
Duration time.Duration
}
JobProcessed is emitted after a worker finishes processing a job attempt.
type Middleware ¶
Middleware wraps a job's Handle method to add cross-cutting behavior such as rate limiting or overlap locks. Call next to continue execution, or return Release, Delete, or Fail to short-circuit the attempt:
func MailRateLimit(ctx context.Context, next func(ctx context.Context) error) error {
if _, err := rate.Attempt(ctx, "mail", rate.PerSecond(14)); err != nil {
return err
}
return next(ctx)
}
Attach middleware to a job by defining a Middleware() []queue.Middleware method. The worker invokes them in slice order, with the first element running outermost.
If a job or its middleware returns a *rate.TooManyAttemptsError, or any error reporting HTTP 429 with a Retry-After header in seconds, the worker releases the job until that wait elapses, as if Release had been returned. If the wait extends past Options.RetryFor, the worker fails the job permanently.
type MissingModelsError ¶
type MissingModelsError struct {
// Job is the registered name of the job or callback.
Job string
// Model is the Go type name of the missing model, such as "models.User".
Model string
// Keys holds the missing primary key values in field order.
Keys []any
}
MissingModelsError reports that one or more database rows referenced by a job's queue:"model" fields no longer exist when the worker reloads them. By default, the worker deletes the job (or skips the callback) without running it. When Options.FailWhenMissingModels is true, the worker fails the job permanently with this error without retrying or calling Failed, and a callback logs the error.
func (*MissingModelsError) Error ¶
func (e *MissingModelsError) Error() string
Error returns a message listing the job, model type, and missing keys.
type Options ¶
type Options struct {
// Queue is the default queue name for this job when the dispatch does not
// override it with [OnQueue]. An empty string uses the connection's default
// queue.
Queue string
// Tries is the maximum number of attempts allowed for the job, including
// releases. Zero means 1 attempt.
Tries int
// Backoff specifies the delay before each retry attempt. Each retry uses
// the next entry, and the final entry repeats for any later retries. An
// empty slice retries immediately.
Backoff []time.Duration
// Timeout is the maximum duration for a single attempt, including
// middleware. Zero defaults to 60 seconds.
Timeout time.Duration
// RetryFor is the time window after dispatch during which the job may be
// retried. When positive, it replaces Tries as the retry limit, and a
// failed attempt whose backoff would run past the window fails the job
// for good with that attempt's error.
RetryFor time.Duration
// MaxErrors limits how many attempts may fail with an error, tracked in
// the queue's cache. Zero imposes no separate error limit beyond Tries or
// RetryFor.
MaxErrors int
// DebounceFor delays each dispatch by this duration and discards it
// without running if a newer dispatch with the same DebounceID arrives
// before it runs.
DebounceFor time.Duration
// MaxWait runs a debounced job immediately once the oldest waiting
// dispatch for the same DebounceID reaches this age.
MaxWait time.Duration
// FailWhenMissingModels permanently fails the job with a
// [*MissingModelsError] when a row referenced by a queue:"model" field no
// longer exists. When false, the worker deletes the job without running
// it, stops its chain, and counts it as skipped in its batch.
FailWhenMissingModels bool
}
Options configures a job's retry, timeout, debouncing, and routing behavior. Provide options on a job type by defining a JobOptions() queue.Options method:
func (ProcessPodcast) JobOptions() queue.Options {
return queue.Options{Queue: "podcasts", Tries: 3, Backoff: []time.Duration{10 * time.Second, time.Minute}}
}
The worker evaluates JobOptions on the job value decoded from the queue, so updating the method applies to already-queued jobs, and individual instances can return different options from their fields:
func (j RunAction) JobOptions() queue.Options { return j.Options }
func (Options) MarshalJSON ¶
MarshalJSON encodes the options for a job that carries them in a field.
func (*Options) UnmarshalJSON ¶
UnmarshalJSON decodes options that Options.MarshalJSON encoded.
type Outcome ¶
type Outcome int
Outcome describes how a single job attempt ended.
const ( // Succeeded indicates that the job's Handle method returned nil. Succeeded Outcome = iota // Released indicates that the job released itself to run again later. Released // Deleted indicates that the job deleted itself or was skipped because its // batch was canceled. Deleted // Debounced indicates that the job was discarded because a newer dispatch // with the same DebounceID replaced it. Debounced // MissingModels indicates that the job was deleted without running because // a referenced model row no longer existed, ending its chain. MissingModels // Retrying indicates that the attempt failed and was released back to the // queue for another try after its backoff delay. Retrying // Failed indicates that the job failed permanently and will not be retried. Failed )
type PanicError ¶
type PanicError struct {
// Value is the recovered panic value.
Value any
// Stack is the stack trace of the goroutine that panicked.
Stack []byte
}
PanicError reports that a job, middleware, or callback panicked during execution. The worker treats it as a retryable failure unless the job has exhausted its retry limits.
func (*PanicError) Error ¶
func (e *PanicError) Error() string
Error returns a message containing the recovered panic value.
type PendingBatch ¶
type PendingBatch struct {
// contains filtered or unexported fields
}
PendingBatch configures a batch of jobs before dispatch. Create one with NewBatch or Queue.Batch. Each configuration method returns a new copy.
func NewBatch ¶
func NewBatch(jobs ...any) *PendingBatch
NewBatch creates a *PendingBatch that runs jobs concurrently and tracks their progress together. A job may also be a *Chain from NewChain, whose steps run sequentially while other jobs in the batch run in parallel:
id, err := queue.NewBatch(
jobs.ImportCsv{ImportID: id, From: 1, To: 100},
jobs.ImportCsv{ImportID: id, From: 101, To: 200},
).Name("Import CSV").Then(jobs.ImportFinished{ImportID: id}).Dispatch(ctx)
Calling PendingBatch.Dispatch uses the application queue carried by ctx and stores batch progress in the job_batches and job_batch_jobs tables on the default database.
func (*PendingBatch) AllowFailures ¶
func (b *PendingBatch) AllowFailures() *PendingBatch
AllowFailures returns a copy of b that continues running remaining jobs when a job fails permanently instead of canceling the batch. PendingBatch.Then callbacks run only after every failed job is retried and succeeds.
func (*PendingBatch) Catch ¶
func (b *PendingBatch) Catch(callbacks ...any) *PendingBatch
Catch returns a copy of b that runs callbacks with the failing error when the first job in the batch fails permanently. Each callback must be registered in laravel.Options.Jobs and define Catch(ctx context.Context, err error) error or Catch(ctx context.Context, batch *queue.Batch, err error) error.
func (*PendingBatch) Delay ¶
func (b *PendingBatch) Delay(d time.Duration) *PendingBatch
Delay returns a copy of b whose jobs wait d before becoming available to workers. Jobs on SyncDriver still run immediately.
func (*PendingBatch) DelayUntil ¶
func (b *PendingBatch) DelayUntil(t time.Time) *PendingBatch
DelayUntil returns a copy of b whose jobs wait until t on the application's clock before becoming available to workers.
func (*PendingBatch) Dispatch ¶
func (b *PendingBatch) Dispatch(ctx context.Context) (BatchID, error)
Dispatch persists the batch, dispatches all of its jobs, and returns the new BatchID. Inside a database transaction, the batch is created and dispatched after the outermost transaction commits.
func (*PendingBatch) Finally ¶
func (b *PendingBatch) Finally(callbacks ...any) *PendingBatch
Finally returns a copy of b that runs callbacks once every job in the batch has finished, whether it succeeded, failed, or was skipped. Each callback must be registered in laravel.Options.Jobs and define Finally(ctx context.Context) error or Finally(ctx context.Context, batch *queue.Batch) error.
func (*PendingBatch) Name ¶
func (b *PendingBatch) Name(name string) *PendingBatch
Name returns a copy of b with the given display name stored on the Batch.
func (*PendingBatch) OnConnection ¶
func (b *PendingBatch) OnConnection(name string) *PendingBatch
OnConnection returns a copy of b whose jobs dispatch on the named connection. Dispatching panics if the application does not configure that connection.
func (*PendingBatch) OnQueue ¶
func (b *PendingBatch) OnQueue(name string) *PendingBatch
OnQueue returns a copy of b whose jobs dispatch on the named queue instead of each job's or connection's default queue.
func (*PendingBatch) Then ¶
func (b *PendingBatch) Then(callbacks ...any) *PendingBatch
Then returns a copy of b that runs callbacks once every job in the batch has succeeded. Each callback must be registered in laravel.Options.Jobs and define Then(ctx context.Context) error or Then(ctx context.Context, batch *queue.Batch) error.
type PendingDispatch ¶
type PendingDispatch struct {
// contains filtered or unexported fields
}
PendingDispatch builds dispatch routing and timing options for the application queue carried by ctx. Start a chain with OnConnection, OnQueue, Delay, DelayUntil, OnGroup, or DeduplicationID, and finish with PendingDispatch.Dispatch, PendingDispatch.Bulk, PendingDispatch.Chain, or PendingDispatch.Batch:
_, err := queue.OnConnection("reports").OnQueue("podcasts").Delay(10*time.Minute).Dispatch(r, job)
Each configuration method returns a new copy.
func DeduplicationID ¶
func DeduplicationID(id string) *PendingDispatch
DeduplicationID starts a *PendingDispatch that assigns id as the SQS FIFO message deduplication ID, matching Queue.DeduplicationID.
func Delay ¶
func Delay(d time.Duration) *PendingDispatch
Delay starts a *PendingDispatch whose jobs wait d before becoming available to workers. Jobs on SyncDriver still run immediately.
func DelayUntil ¶
func DelayUntil(t time.Time) *PendingDispatch
DelayUntil starts a *PendingDispatch whose jobs wait until t on the application's clock before becoming available to workers:
_, err := queue.DelayUntil(event.StartsAt.Add(-time.Hour)).Dispatch(r, jobs.SendReminder{EventID: event.ID})
If t is in the past, the jobs become available immediately.
func OnConnection ¶
func OnConnection(name string) *PendingDispatch
OnConnection starts a *PendingDispatch targeting the named connection. Dispatching panics if the application does not configure that connection.
func OnGroup ¶
func OnGroup(group string) *PendingDispatch
OnGroup starts a *PendingDispatch whose jobs join the named SQS message group, matching Queue.OnGroup.
func OnQueue ¶
func OnQueue(name string) *PendingDispatch
OnQueue starts a *PendingDispatch targeting the named queue instead of the job's or connection's default queue.
func (*PendingDispatch) Batch ¶
func (p *PendingDispatch) Batch(jobs ...any) *PendingBatch
Batch creates a *PendingBatch with p's connection, queue, delay, and SQS settings applied to its jobs.
func (*PendingDispatch) Bulk ¶
Bulk dispatches multiple jobs onto the application queue carried by ctx using p's routing and timing settings. It panics if ctx does not carry an application scope or if p names an unknown connection.
func (*PendingDispatch) Chain ¶
func (p *PendingDispatch) Chain(jobs ...any) *Chain
Chain creates a Chain with p's connection and queue applied to every job in the chain and p's delay applied to the first job.
func (*PendingDispatch) DeduplicationID ¶
func (p *PendingDispatch) DeduplicationID(id string) *PendingDispatch
DeduplicationID returns a copy of p with the SQS FIFO message deduplication ID set to id.
func (*PendingDispatch) Delay ¶
func (p *PendingDispatch) Delay(d time.Duration) *PendingDispatch
Delay returns a copy of p whose jobs wait d before becoming available.
func (*PendingDispatch) DelayUntil ¶
func (p *PendingDispatch) DelayUntil(t time.Time) *PendingDispatch
DelayUntil returns a copy of p whose jobs wait until t before becoming available.
func (*PendingDispatch) Dispatch ¶
Dispatch pushes job onto the application queue carried by ctx using p's routing and timing settings. It panics if ctx does not carry an application scope or if p names an unknown connection.
func (*PendingDispatch) OnConnection ¶
func (p *PendingDispatch) OnConnection(name string) *PendingDispatch
OnConnection returns a copy of p targeting the named connection.
func (*PendingDispatch) OnGroup ¶
func (p *PendingDispatch) OnGroup(group string) *PendingDispatch
OnGroup returns a copy of p whose jobs join the named SQS message group.
func (*PendingDispatch) OnQueue ¶
func (p *PendingDispatch) OnQueue(name string) *PendingDispatch
OnQueue returns a copy of p targeting the named queue.
type Processed ¶
type Processed struct {
// Name is the registered job name, or "an unreadable job" if the payload
// could not be parsed.
Name string
// Outcome describes how the attempt ended.
Outcome Outcome
// Duration is the elapsed time spent running and settling the job.
Duration time.Duration
// Err is the error returned by the job when the attempt failed.
Err error
}
Processed summarizes the result of a single Worker.Process call.
type Pushed ¶
type Pushed struct {
// ID is the [JobID] assigned when the job was dispatched.
ID JobID
// Job is the decoded job value as a worker would receive it, with model
// relationships stripped.
Job any
// Connection is the target connection name resolved for the dispatch.
Connection string
// Queue is the target queue name resolved for the dispatch.
Queue string
// Delay is the dispatch delay computed when the job was pushed.
Delay time.Duration
// Chain holds any jobs chained after this one in execution order. A batch
// step in the chain is represented as a [Batched].
Chain []any
// Batch is the [BatchID] the job belongs to, or empty if none.
Batch BatchID
}
Pushed describes a dispatched job captured by a Recorder.
type Queue ¶
type Queue struct {
// contains filtered or unexported fields
}
Queue dispatches jobs, chains, and batches. Configuration methods such as Queue.Connection, Queue.OnQueue, and Queue.Delay return a new copy so a Queue can be shared safely across goroutines. Obtain the application's Queue from a context with From.
func From ¶
From returns the *Queue of the application carried by ctx. Use it for operations that do not have package-level helpers, such as inspecting queue sizes:
sizes, ok, err := queue.From(ctx).Sizes(ctx, "redis", "emails")
From panics if ctx does not carry an application scope, such as context.Background.
func New ¶
New constructs a Queue from cfg. It returns a joined error if any job or callback type has an invalid signature, two types share a job name, a model tag references an unknown database connection, or Config.Default is not in Config.Connections.
func (*Queue) Attempt ¶
Attempt runs a single attempt of job through its middleware for testing, without retrying, calling Failed, or dispatching chained or batched jobs. Pass number to set Attempt.Number (values below 1 default to 1), and pass a non-empty batch to simulate running inside that batch. Tests typically call queuetest.Attempt to assert on the returned Attempted.
func (*Queue) Batch ¶
func (q *Queue) Batch(jobs ...any) *PendingBatch
Batch returns a *PendingBatch that dispatches jobs on q, matching NewBatch.
func (*Queue) Bulk ¶
Bulk dispatches multiple jobs in as few backend round trips as possible and returns their JobID values in order. Each entry in jobs may be a single job or a typed slice of jobs (such as []jobs.ImportChunk). Jobs with a delay, debouncing, or a sync driver are sent individually because BulkPusher.PushBulk sends immediate payloads. If a push fails partway through, earlier jobs may already be queued. Use Queue.Batch to track a group of jobs together.
func (*Queue) CancelBatch ¶
CancelBatch marks the batch with the given id as canceled. Jobs that have not yet started are skipped when reserved, and the batch's PendingBatch.Then callbacks do not run.
func (*Queue) Chain ¶
Chain returns a *Chain that runs jobs sequentially on q, matching NewChain. Any connection, queue, or SQS message group configured on q applies to every job in the chain, while q's delay and deduplication ID apply to the first job.
func (*Queue) CheckConnection ¶
CheckConnection verifies that the named connection exists and has a working driver. It returns an error if the connection is not configured or uses a driver created by Unavailable. Applications call this during startup so a missing driver fails at boot rather than on the first dispatch.
func (*Queue) Clear ¶
Clear deletes all jobs waiting on the named connection and queue and returns the number of deleted jobs. Pass an empty queue name to clear the connection's default queue.
func (*Queue) Close ¶
Close closes every connection driver that implements io.Closer, closing each shared driver instance once. The application calls Close on shutdown.
func (*Queue) Connection ¶
Connection returns a copy of q that dispatches to the named connection. It panics if no connection with that name is configured.
func (*Queue) DeduplicationID ¶
DeduplicationID returns a copy of q that assigns id as the SQS FIFO message deduplication ID, causing SQS to drop duplicate dispatches with the same ID within five minutes. Without a deduplication ID, each job receives a unique ID automatically. Other drivers ignore this setting.
A deduplication ID applies to a single job. For a Chain, it attaches to the first job. Calling Queue.Bulk or dispatching a PendingBatch with more than one job returns an error, because a FIFO queue would keep only the first job.
func (*Queue) DefaultConnection ¶
DefaultConnection returns the name of the default queue connection.
func (*Queue) Delay ¶
Delay returns a copy of q whose dispatched jobs wait d before becoming available to workers. Jobs on SyncDriver still run immediately.
func (*Queue) DelayUntil ¶
DelayUntil returns a copy of q whose dispatched jobs wait until t on the application's clock before becoming available to workers. If t is in the past, jobs become available immediately.
func (*Queue) Delays ¶
Delays reports whether jobs dispatched to connection wait on a backend queue for a worker rather than running immediately on SyncDriver. Pass an empty name to check the default connection. When Config.Testing is enabled, Delays checks the default connection just as dispatches do.
func (*Queue) Dispatch ¶
Dispatch pushes job onto its configured connection and returns its JobID. On SyncDriver, the job runs immediately in the current process and Dispatch returns its error. Inside a database transaction, the job is pushed after the outermost transaction commits and is discarded if it rolls back.
If the job sets Options.DebounceFor, each dispatch waits for that duration before running. If a later dispatch with the same DebounceID arrives before the earlier one runs, the worker discards the earlier job so only the latest dispatch executes.
func (*Queue) DispatchSync ¶
DispatchSync runs job immediately in the current process with its middleware and returns its error, bypassing asynchronous drivers and debouncing.
func (*Queue) Failed ¶
func (q *Queue) Failed() *FailedJobs
Failed returns the *FailedJobs store configured for permanently failed jobs, or nil if failed job storage is disabled.
func (*Queue) Fake ¶
Fake installs r to record matching jobs and all batches instead of pushing them to a driver. It returns false and makes no change if a fake is already installed. Tests typically install a fake through queuetest.New.
func (*Queue) FindBatch ¶
FindBatch loads the Batch with the given id. It returns false with a nil error if no batch has that id, or an error if batch storage is not configured.
func (*Queue) OnGroup ¶
OnGroup returns a copy of q whose dispatched jobs, including every job in a chain or batch, belong to the named SQS message group. On an SQS FIFO queue, jobs in the same group run one at a time in dispatch order. On a standard SQS queue, the group enables fair queueing across groups. Other drivers ignore the group.
func (*Queue) OnQueue ¶
OnQueue returns a copy of q that dispatches to the named queue instead of the job's or connection's default queue.
func (*Queue) PruneBatches ¶
PruneBatches deletes batches matching which that are older than before and returns the number of deleted batches.
func (*Queue) QueueOf ¶
QueueOf returns the default queue name for connection and reports whether that connection is configured.
func (*Queue) Retry ¶
Retry pushes job back onto its original connection and queue with a fresh dispatch timestamp and removes it from FailedJobs. It returns an error if the original connection is no longer configured or the payload cannot be decoded.
func (*Queue) RetryBatch ¶
RetryBatch re-dispatches every permanently failed job in the batch with the given id and returns how many jobs were retried. It returns an error if the batch does not exist, failed job storage is disabled, or the batch was canceled (batches must be dispatched with PendingBatch.AllowFailures to support retrying failed jobs).
type Recorder ¶
type Recorder interface {
// Records reports whether the recorder intercepts this job.
Records(job any) bool
// Record stores a job that would have been pushed to a queue.
Record(job Pushed)
// RecordBatch stores a batch that would have been dispatched without
// running its jobs.
RecordBatch(batch Batched)
}
Recorder intercepts dispatched jobs and batches in tests instead of pushing them to a driver. Jobs for which Records returns false still dispatch normally. Install a Recorder with Queue.Fake or through queuetest.New.
type Reserved ¶
type Reserved interface {
// Queue returns the name of the queue from which the job was reserved.
Queue() string
// Payload returns the raw job payload bytes as pushed.
Payload() []byte
// Attempts returns how many times this job has been reserved, starting at
// 1 for the first run. Releases, retries, and expired reservations each
// increment the count.
Attempts() int
// Renew extends the reservation to [Lease] from now and reports whether
// this worker still owns the job.
Renew(ctx context.Context) (bool, error)
// Delete removes the job from the queue and reports whether this worker
// still owned it.
Delete(ctx context.Context) (bool, error)
// Release returns the job to its queue to become available after delay,
// preserving its attempt count, and reports whether this worker still
// owned it.
Release(ctx context.Context, delay time.Duration) (bool, error)
}
Reserved represents a worker's active reservation on a single queued job. If the reservation expires and another worker claims the job, Renew, Delete, and Release return false so the worker leaves the job untouched.
type Sizer ¶
type Sizer interface {
// Sizes returns the current job counts for queue.
Sizes(ctx context.Context, queue string) (Sizes, error)
}
Sizer is an optional Driver interface that reports queue depth counts for Queue.Sizes.
type Sizes ¶
type Sizes struct {
// Pending is the number of jobs immediately available to workers,
// including jobs whose previous reservation expired.
Pending int64
// Delayed is the number of jobs waiting for a dispatch or release delay.
Delayed int64
// Reserved is the number of jobs currently claimed by workers.
Reserved int64
// OldestPending is the dispatch time of the oldest pending job, or the
// zero [time.Time] if the queue has no pending jobs or the driver does not
// track timestamps.
OldestPending time.Time
}
Sizes holds the number of jobs on a queue grouped by state.
type TimeoutError ¶
type TimeoutError struct {
// Timeout is the duration limit that the attempt exceeded.
Timeout time.Duration
}
TimeoutError reports that a job attempt exceeded its configured Options.Timeout. The worker cancels the attempt's context with this error as the cause so context-aware operations stop promptly.
func (*TimeoutError) Error ¶
func (e *TimeoutError) Error() string
Error returns a message describing the exceeded timeout.
type UndecodableError ¶
type UndecodableError struct {
// Job is the registered name of the job that could not be decoded.
Job string
// Err is the underlying JSON decoding error.
Err error
}
UndecodableError reports that a queued job's stored JSON payload could not be decoded into its registered Go type, such as after an incompatible field change. Because retrying cannot fix a malformed payload, the worker fails the job permanently.
func (*UndecodableError) Error ¶
func (e *UndecodableError) Error() string
Error returns a message naming the job and the decoding failure.
func (*UndecodableError) Unwrap ¶
func (e *UndecodableError) Unwrap() error
Unwrap returns the underlying decoding error.
type UnknownJobError ¶
type UnknownJobError struct {
// Job is the unregistered job name read from the payload.
Job string
}
UnknownJobError reports that a queued job's registered name does not match any type listed in laravel.Options.Jobs, such as after a job type was renamed. Because retrying cannot resolve an unknown type, the worker fails the job permanently.
func (*UnknownJobError) Error ¶
func (e *UnknownJobError) Error() string
Error returns a message naming the unknown job and how to register it.
type Worker ¶
type Worker struct {
// contains filtered or unexported fields
}
Worker reserves and executes jobs from a single queue connection. The queue:work command runs a Worker loop.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package redisqueue provides a Redis-backed queue.Driver, queue.BulkPusher, and queue.Sizer using github.com/redis/go-redis/v9.
|
Package redisqueue provides a Redis-backed queue.Driver, queue.BulkPusher, and queue.Sizer using github.com/redis/go-redis/v9. |
|
Package sqsqueue provides queue.Driver implementations for Amazon SQS (Driver) and Laravel Cloud managed queues (CloudDriver).
|
Package sqsqueue provides queue.Driver implementations for Amazon SQS (Driver) and Laravel Cloud managed queues (CloudDriver). |