queue

package
v0.8.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 10 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package queue is the PostgreSQL-native async job queue. The Enqueue and Dequeue helpers are the only public surface that touches the job_queue table; lint forbids raw INSERT INTO job_queue elsewhere.

Correlation propagation is built in: Enqueue extracts correlation_id from the caller's context (and errors if none is set); Dequeue restores the row's correlation_id onto a fresh worker context. See docs/engineering/correlation_id_propagation.md.

Spec: specs/system/job-queue.spec.yaml.

Index

Constants

This section is empty.

Variables

View Source
var ErrLeaseLost = errors.New("queue: lease lost")

ErrLeaseLost is returned when a lease is no longer the job's current claim: the job was retired as stale, completed, failed, or never existed.

View Source
var ErrMissingCorrelation = errors.New("queue: enqueue requires a correlation_id on context")

ErrMissingCorrelation is returned by Enqueue when the caller's context has no correlation_id set. The queue rejects such jobs because every async unit must be traceable to its originating intent (HTTP request, cron tick, system boot).

Spec system-job-queue AC-02, C-01.

View Source
var ErrNoJob = errors.New("queue: no pending job")

ErrNoJob is returned by Dequeue when no pending job is available. Not fatal — workers poll on this.

Functions

func Complete

func Complete(ctx context.Context, pool *pgxpool.Pool, jobID uuid.UUID) error

Complete marks a job as completed. Workers call this after the job runs successfully.

Spec system-job-queue AC-06.

func CompleteLeased added in v0.8.5

func CompleteLeased(ctx context.Context, db Execer, l Lease) error

CompleteLeased marks the job completed if the lease is still current, and returns ErrLeaseLost otherwise. The token is cleared, so the lease cannot be used again. Called in a transaction, it holds the job's row lock until that transaction ends, so a concurrent RetireStale waits for it.

Spec system-job-queue AC-16.

func Enqueue

func Enqueue(ctx context.Context, pool Execer, jobType string, payload any) (uuid.UUID, error)

Enqueue persists a new job_queue row, immediately dequeuable. The caller's ctx MUST carry a correlation_id; this is a programming-error guard per spec C-01. The row's correlation_id pins the job to the originating intent across the async boundary.

Returns the inserted job's ID. The job is in "pending" status with attempts=0 until a worker claims it via Dequeue.

Spec system-job-queue AC-01.

func EnqueueAfter

func EnqueueAfter(ctx context.Context, pool Execer, jobType string, payload any, delay time.Duration) (uuid.UUID, error)

EnqueueAfter is Enqueue with a delay: the job is not dequeuable until `delay` from now (available_at = now() + delay). A non-positive delay makes it immediately available, identical to Enqueue. Used to back off and requeue a job that can't run yet (e.g. the target host is busy) without a tight re-dequeue loop, since Dequeue skips not-yet-available rows.

Spec system-job-queue AC-13 (delayed visibility).

func EnqueueIfAbsent added in v0.8.5

func EnqueueIfAbsent(ctx context.Context, pool Execer, jobType string, payload any) (uuid.UUID, bool, error)

EnqueueIfAbsent inserts a pending job unless a unique index refuses it, in which case it inserts nothing and reports enqueued=false. A job type that must have at most one active job per subject declares that with a partial unique index; this is how callers respect it without treating the conflict as an error. Same correlation guard as Enqueue.

Spec system-job-queue AC-15.

func Fail

func Fail(ctx context.Context, pool *pgxpool.Pool, jobID uuid.UUID, errMsg string) error

Fail marks a job as failed and records the error message. Workers call this on terminal failure (after retry policy is exhausted, which the queue doesn't yet implement).

Spec system-job-queue AC-07.

func FailLeased added in v0.8.5

func FailLeased(ctx context.Context, db Execer, l Lease, errMsg string) error

FailLeased marks the job failed with errMsg if the lease is still current, and returns ErrLeaseLost otherwise.

Spec system-job-queue AC-16.

Types

type Execer added in v0.8.2

type Execer interface {
	Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
}

Execer is the write surface Enqueue needs. A *pgxpool.Pool satisfies it, and so does a pgx.Tx, which lets a caller commit the job together with the rows that describe it, or roll both back. bugs/OW-097.

type Job

type Job struct {
	ID            uuid.UUID
	JobType       string
	Payload       []byte // JSONB; opaque to the queue
	CorrelationID string
	Status        Status
	Attempts      int
	LastError     string
	CreatedAt     time.Time
	LockedAt      *time.Time
	CompletedAt   *time.Time
	// LeaseToken is minted by the claim that moved the job to processing.
	// Leased completion, failure and result writes must present it.
	LeaseToken uuid.UUID
}

Job is the row shape exposed to consumers. Payload is opaque JSON.

func Dequeue

func Dequeue(ctx context.Context, pool *pgxpool.Pool) (*Job, context.Context, error)

Dequeue claims one pending job atomically via SELECT ... FOR UPDATE SKIP LOCKED. Returns (job, workerCtx, nil) on success. workerCtx is a fresh context derived from context.Background() with the row's correlation_id set — the caller's ctx is NOT used as parent so the worker-loop's own correlation_id cannot leak into per-job execution (spec C-02).

Returns ErrNoJob (sentinel) when nothing is pending. Caller should poll with a delay on this.

Spec system-job-queue AC-03, AC-04, AC-05.

func (*Job) Lease added in v0.8.5

func (j *Job) Lease() Lease

Lease returns the job's current lease.

type Lease added in v0.8.5

type Lease struct {
	JobID uuid.UUID
	Token uuid.UUID
}

Lease identifies one claim of a job: the job and the token its claim minted. The zero Lease holds nothing.

func Claim added in v0.8.5

func Claim(ctx context.Context, pool Execer, jobType string, payload any) (Lease, bool, error)

Claim inserts a job already claimed by the caller: status processing, attempts 1, a fresh lease token. It is for work run in the caller's own goroutine (an operator's synchronous request) that must still hold the job's slot. Like EnqueueIfAbsent it reports claimed=false, inserting nothing, when a unique index refuses the row.

Spec system-job-queue AC-15.

func (Lease) Valid added in v0.8.5

func (l Lease) Valid() bool

Valid reports whether the lease names a job and a token.

type StaleJob added in v0.8.5

type StaleJob struct {
	ID      uuid.UUID
	Payload []byte
}

StaleJob is a job RetireStale retired.

func RetireStale added in v0.8.5

func RetireStale(ctx context.Context, tx pgx.Tx, jobType string, deadline time.Duration, errMsg string) ([]StaleJob, error)

RetireStale fails every processing job of jobType claimed more than deadline ago (by the database clock), clearing its lease so the claim that held it can no longer complete it or write results. It returns the retired jobs so the caller can record what their failure means in the same transaction.

Spec system-job-queue AC-17.

type Status

type Status string

Status is the queue-row lifecycle. Stored as text; CHECK constraint in 0003_job_queue.sql enforces the closed set.

const (
	StatusPending    Status = "pending"
	StatusProcessing Status = "processing"
	StatusCompleted  Status = "completed"
	StatusFailed     Status = "failed"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL