Documentation
¶
Overview ¶
Package queue provides a driver-based job queue with pluggable backends, retries, per-job max attempts, priority queue ordering, and a polling worker.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrStalePause = errors.New("queue: pause handle is not current") ErrUnknownDisposition = errors.New("queue: a cycle has an unknown disposition") ErrControllerInUse = errors.New("queue: controller already belongs to another worker or active start") )
Controller errors are comparable with errors.Is. Driver errors remain in CycleReport rather than being folded into these fixed messages.
var ErrHandlerNotFound = errors.New("handler not found for job type")
ErrHandlerNotFound is used when a job is popped but no handler is registered for its type.
var ErrNoJob = errors.New("no job available")
ErrNoJob is returned by Pop when no job is available. Drivers return nil, nil instead of this error — this sentinel exists for internal worker logic.
Functions ¶
This section is empty.
Types ¶
type CycleController ¶ added in v0.2.1
type CycleController struct {
// contains filtered or unexported fields
}
CycleController gates entire polling cycles without canceling their contexts. Its zero value is ready to use. It belongs permanently to one Worker and must not be copied after use. Driver errors permanently quarantine new cycles for this controller, including across Starts. Resume never clears uncertainty. There is no reset API. Callbacks are part of a cycle and must not wait for their own quiescence.
func (*CycleController) Pause ¶ added in v0.2.1
func (c *CycleController) Pause() PauseHandle
Pause closes cycle admission. Repeated calls during the same pause return the same handle. It may be called before Worker.Start.
func (*CycleController) Report ¶ added in v0.2.1
func (c *CycleController) Report() CycleReport
Report returns detached result/slice values. It does not close admission.
func (*CycleController) Resume ¶ added in v0.2.1
func (c *CycleController) Resume(h PauseHandle) error
Resume reopens this pause only. Uncertainty still quarantines the worker.
func (*CycleController) WaitQuiescent ¶ added in v0.2.1
func (c *CycleController) WaitQuiescent(ctx context.Context, h PauseHandle) (CycleReport, error)
WaitQuiescent waits through eligibility, reservation, handlers, settlement and callbacks. A deadline stops only this wait. The caller must keep the pause held while relying on success. Unknown outcomes are reported only after active cycles finish; they never become a successful idle report.
type CycleDisposition ¶ added in v0.2.1
type CycleDisposition string
CycleDisposition describes what is known about a completed cycle.
const ( DispositionNoReservation CycleDisposition = "no_reservation" DispositionSettled CycleDisposition = "settled" DispositionUnknown CycleDisposition = "unknown" )
type CycleOperation ¶ added in v0.2.1
type CycleOperation string
CycleOperation identifies the last operation in a polling cycle.
const ( OperationEligibility CycleOperation = "eligibility" OperationPop CycleOperation = "pop" OperationSize CycleOperation = "size" OperationDelete CycleOperation = "delete" OperationRelease CycleOperation = "release" OperationFailed CycleOperation = "failed" )
type CycleReport ¶ added in v0.2.1
type CycleReport struct {
Active int
Last *CycleResult
Unknown []CycleResult
}
CycleReport is a snapshot. Only a successful WaitQuiescent with a still-held pause proves quiescence. Last is the most recently completed cycle; Unknown retains every uncertain cycle, bounded by the worker's polling concurrency.
type CycleResult ¶ added in v0.2.1
type CycleResult struct {
Cycle uint64
Operation CycleOperation
Disposition CycleDisposition
JobID string
Err error
}
CycleResult carries internal evidence, not a safe-to-publish diagnostic. Err may contain driver details; JobID is opaque and Payload is never retained. Cycle is a diagnostic sequence, not an authorization token.
type PauseHandle ¶ added in v0.2.1
type PauseHandle struct {
// contains filtered or unexported fields
}
PauseHandle belongs to one controller and one uninterrupted pause. Copies refer to the same pause; a handle cannot resume a later pause.
type PushConfig ¶
PushConfig holds resolved push options. Exported so drivers can access the resolved values.
func ResolvePushConfig ¶
func ResolvePushConfig(opts []PushOption) PushConfig
ResolvePushConfig applies options and returns the resolved config.
type PushOption ¶
type PushOption func(*PushConfig)
PushOption configures optional parameters for Push.
func OnQueue ¶
func OnQueue(name string) PushOption
OnQueue sets the queue name for the job. Default: "default".
func WithDelay ¶
func WithDelay(d time.Duration) PushOption
WithDelay sets a delay before the job becomes available. Default: 0.
func WithMaxTries ¶
func WithMaxTries(n int) PushOption
WithMaxTries sets the maximum number of attempts for this job. 0 means inherit from WorkerOpts.MaxTries.
type Queue ¶
type Queue interface {
// Push enqueues a new job. The jobType identifies which handler
// processes it; payload is an opaque JSON blob.
Push(ctx context.Context, jobType string, payload []byte, opts ...PushOption) error
// Pop retrieves and reserves the next available job from the named
// queue. Returns nil, nil when the queue is empty.
Pop(ctx context.Context, queueName string) (*QueuedJob, error)
// Delete removes a completed job from the queue.
Delete(ctx context.Context, id string) error
// Release puts a job back on the queue with a delay. The job gets
// a new position (FIFO ordering preserved) but keeps its attempt
// count.
Release(ctx context.Context, id string, delay time.Duration) error
// Size returns the total number of jobs on the named queue.
Size(ctx context.Context, queueName string) (int, error)
// Failed moves a job to the failed jobs store with the given error
// message. The original job is removed from the active queue.
Failed(ctx context.Context, job *QueuedJob, errMsg string) error
}
Queue is the driver interface. Each backend (SQLite, memory, noop) implements this contract. Consumers depend on this interface, not concrete drivers.
type QueuedJob ¶
type QueuedJob struct {
ID string
Type string
Queue string
Payload []byte
Attempts int
MaxTries int
CreatedAt time.Time
AvailableAt time.Time
ReservedAt *time.Time
}
QueuedJob is a job that has been popped from the queue. It carries the metadata the worker needs for dispatch, retry, and failure.
type Worker ¶
type Worker struct {
// contains filtered or unexported fields
}
Worker polls a Queue and dispatches jobs to registered handlers.
func NewWorker ¶
func NewWorker(q Queue, opts WorkerOpts) *Worker
NewWorker creates a Worker bound to the given Queue.
type WorkerOpts ¶
type WorkerOpts struct {
// Queues to poll in priority order. Default: ["default"].
Queues []string
// Concurrency is the number of polling goroutines. Default: 1.
Concurrency int
// PollInterval is the sleep duration between empty polls. Default: 3s.
PollInterval time.Duration
// MaxTries is the default max attempts per job. Jobs with
// WithMaxTries override this. 0 = unlimited. Default: 3.
MaxTries int
// RetryAfter is the delay before a failed job is retried.
// 0 means no delay (immediate retry). Default: 0.
RetryAfter time.Duration
// MaxMemoryMB stops the worker if memory exceeds this. 0 = no limit.
MaxMemoryMB int
// StopWhenEmpty exits after the queue is drained. Default: false.
StopWhenEmpty bool
// CanReserve, when non-nil, is asked once per poll cycle whether this
// worker may take work right now. Returning false skips the cycle: nothing
// is reserved, the worker sleeps PollInterval, and it asks again.
//
// It gates ONLY new reservations. A job already held runs to completion
// under a live context, which is the difference between "stop taking work"
// and "abandon work in progress" — and the reason this is a gate rather
// than something a caller can approximate by cancelling the worker's
// context. Cancelling aborts the handler mid-flight and then fails the
// bookkeeping that follows it, leaving the job reserved and its attempt
// spent.
//
// Written for deference between processes that share a queue: a leader that
// owns the work, a maintenance window, or a drain-down before shutdown. The
// canonical case is a long-lived service and short-lived helpers on one
// database, where only the service should run jobs while it is alive.
//
// nil means always eligible, which is exactly how every worker behaved
// before this option existed.
//
// Called on the polling goroutine, so it should be cheap and must not
// block for long — a slow check delays every cycle. It must not panic:
// this package does not recover panics anywhere, here or in handlers, and
// one raised here would take down the polling goroutine.
//
// Interaction with StopWhenEmpty, stated because it is a real corner: a
// gated cycle never inspects the queue, so it cannot conclude the queue is
// drained and will not trigger StopWhenEmpty. A worker told it may not
// reserve is deferring, not finished, and it waits rather than exiting.
CanReserve func(ctx context.Context) bool
// Controller optionally supports reversible whole-cycle draining. It gates
// before CanReserve and retains cycles through durable settlement and
// callbacks. Driver errors quarantine new cycles; nil preserves legacy
// behavior. One controller belongs to one worker, including across Starts.
Controller *CycleController
// Lifecycle callbacks.
OnProcessing func(job *QueuedJob)
OnProcessed func(job *QueuedJob)
OnFailed func(job *QueuedJob, err error)
OnError func(err error)
}
WorkerOpts configures worker behavior.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
driver
|
|
|
memory
Package memory provides the in-memory queue driver for github.com/hollis-labs/go-queue.
|
Package memory provides the in-memory queue driver for github.com/hollis-labs/go-queue. |
|
noop
Package noop provides the no-op queue driver for github.com/hollis-labs/go-queue.
|
Package noop provides the no-op queue driver for github.com/hollis-labs/go-queue. |
|
sqlite
Package sqlite provides the SQLite-backed queue driver for github.com/hollis-labs/go-queue.
|
Package sqlite provides the SQLite-backed queue driver for github.com/hollis-labs/go-queue. |
|
examples
|
|
|
inmemory
command
Package main is a runnable end-to-end example of go-queue using the in-memory driver.
|
Package main is a runnable end-to-end example of go-queue using the in-memory driver. |