mongoqueue

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: Apache-2.0 Imports: 14 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.

README

mongoqueue

Go Reference test License

mongoqueue is a fair, multi-tenant job queue on MongoDB for Go. It is a durable lease primitive: callers enqueue jobs and run their own workers, and the queue dispatches jobs fairly across tenants using virtual time, leases each claimed job, and records how each one ends. It does not run workers, retry, dead-letter, or orchestrate workflows; those belong to the caller.

Install

go get github.com/xdg-go/mongoqueue

License

Apache License 2.0. See LICENSE.

Documentation

Overview

Package mongoqueue implements a fair, multi-tenant job queue on MongoDB. Callers enqueue jobs and run their own workers; the queue stores the jobs, hands them to workers in a fair order, leases each job to one worker at a time, and records how each one ends. It does not run workers, retry failed jobs, or move them to a dead-letter queue.

Jobs and kinds

Each job is one document in a MongoDB collection. The library owns the envelope: the job id, tenant, partition, and cost the caller supplies at enqueue, plus the fields the queue maintains for ordering and leasing (see Job). The rest is the payload: a kind name and a body. The body is the caller's own data, stored as a BSON subdocument that the queue never reads.

A Kind ties a kind name to the Go type of its body. Declare each one once with NewKind, typically as a package-level variable. Kind.Enqueue stores a body of that type, and Kind.Decode reads it back, failing if the job was enqueued under a different kind. One queue can carry jobs of many kinds.

Fair ordering

Each tenant has its own virtual clock in each partition. Enqueue stamps a job with the tenant's virtual time, then moves that clock forward by the job's cost divided by the tenant's weight. Queue.Claim hands out the job with the lowest stamp in a partition. A tenant with a higher weight moves its clock forward more slowly, so its jobs keep lower stamps and are claimed more often; for the same reason, cheap jobs move a clock less than expensive ones. A tenant that enqueues a flood of work pushes back only its own later jobs.

Fairness has no memory. A tenant that is new, or returns after being idle, starts at the point the partition is currently serving: it gets no credit for the time it was idle and does not wait behind other tenants' backlogs. Ordering is decided at enqueue, so a claim is a single atomic update.

Leases

A claim does not remove the job. It leases it: the job is hidden from other workers until the lease expires, and it gets a new claim ID. The worker then extends the lease with ClaimedJob.Heartbeat, gives the job back early with ClaimedJob.Release, or finishes it with ClaimedJob.Complete. These succeed only while the job still carries the worker's claim ID. If the lease expires, the job becomes claimable again without any background process, and the next claim replaces the claim ID, so a stalled worker cannot complete a job that another worker now holds.

Queue.Cancel resolves a pending job from outside any lease. Whether a job ends by Complete or Cancel, only one resolution is recorded. Queue.Get reads a job's current state.

Caller requirements

The library does not check or enforce the requirements below. If a caller ignores one, the queue can misbehave without returning an error.

  • Call Queue.EnsureIndexes before use; the queue never creates indexes.
  • Call Queue.Reconcile on a ticker to bound cached virtual-time drift.
  • Call Queue.EnsureTTLIndex if resolved jobs should be deleted.
  • Enqueue to each (tenant, partition) from a single writer (EnqueueOpts).
  • Pass the same weight from all of a tenant's producers (EnqueueOpts.Weight).
  • Use acknowledged writes, and w: "majority" for single resolution across failover (New).
  • Use a read concern that observes the queue's own inserts (New).
  • Give the collection the simple default collation (New).
  • Do not set BSONOptions.OmitEmpty on the client (New).
  • Make workers idempotent, because effects are at-least-once (Queue.Claim).
  • Expect a delayed job to run ahead of its tenant's later work when it comes due (EnqueueOpts.Delay).
  • Bound retries in the worker by checking Job.Attempts.
Example

A worker pool: enqueue a job, then run a fixed set of workers that claim, decode, work, and complete until interrupted.

package main

import (
	"context"
	"errors"
	"log"
	"os"
	"os/signal"
	"sync"
	"time"

	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
	"go.mongodb.org/mongo-driver/v2/mongo/writeconcern"

	"github.com/xdg-go/mongoqueue"
)

// Resize is the body of a "resize" job: caller domain data, stored as a
// BSON subdocument.
type Resize struct {
	URL   string `bson:"url"`
	Width int    `bson:"width"`
}

// resize stands in for the caller's work. Effects are at-least-once, so it
// must be idempotent.
func resize(_ context.Context, _ Resize) error { return nil }

func main() {
	// Majority writes keep single resolution across failover.
	client, err := mongo.Connect(options.Client().
		ApplyURI("mongodb://localhost:27017").
		SetWriteConcern(writeconcern.Majority()))
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()
	q := mongoqueue.New(client.Database("app").Collection("jobs"))
	if err := q.EnsureIndexes(ctx); err != nil {
		log.Fatal(err)
	}
	// Run q.Reconcile on a ticker for the life of the queue; see the
	// Queue.Reconcile example.

	// One binding pairs the kind name with its body type for both Enqueue
	// and Decode.
	resizeKind := mongoqueue.NewKind[Resize]("resize")
	// The job id is the idempotency key: a duplicate is already enqueued.
	err = resizeKind.Enqueue(ctx, q, Resize{URL: "s3://img/1.png", Width: 640},
		mongoqueue.EnqueueOpts{JobID: "resize-1", TenantID: "acme"})
	if err != nil && !errors.Is(err, mongoqueue.ErrDuplicateJob) {
		log.Fatal(err)
	}

	ctx, stop := signal.NotifyContext(ctx, os.Interrupt)
	defer stop()

	const idleBackoff = time.Second
	var wg sync.WaitGroup
	for range 4 {
		wg.Go(func() {
			for ctx.Err() == nil {
				job, err := q.Claim(ctx, "", 30*time.Second)
				if err != nil {
					if !errors.Is(err, mongoqueue.ErrNoJob) {
						log.Printf("claim: %v", err)
					}
					select { // Wait before polling again, or stop at shutdown.
					case <-ctx.Done():
					case <-time.After(idleBackoff):
					}
					continue
				}
				body, err := resizeKind.Decode(&job.Job)
				switch {
				case err != nil: // Poison: no retry will decode it.
					err = job.Complete(ctx, "undecodable")
				case resize(ctx, body) != nil:
					// On shutdown, skip Release: the lease expires instead.
					if ctx.Err() == nil {
						err = job.Release(ctx, time.Minute)
					}
				default:
					err = job.Complete(ctx, mongoqueue.ResolutionCompleted)
				}
				if err != nil {
					log.Printf("job %s: %v", job.ID, err)
				}
			}
		})
	}
	wg.Wait()
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrDuplicateJob = errors.New("mongoqueue: job id already exists")

ErrDuplicateJob signals an enqueue under an id already present. The stored record wins.

View Source
var ErrEmptyResolution = errors.New("mongoqueue: resolution must be non-empty")

ErrEmptyResolution signals a Complete with an empty Resolution. Termination requires recording a resolution, so the zero value is rejected before any server round trip. (Cancel takes no resolution; it writes ResolutionCanceled unconditionally.)

View Source
var ErrInvalidDelay = errors.New("mongoqueue: delay must be >= 0")

ErrInvalidDelay signals a negative delay: EnqueueOpts.Delay or the delay passed to ClaimedJob.Release. Zero means immediately visible (for Release, immediately reclaimable); a job cannot be made visible in the past.

View Source
var ErrInvalidLease = errors.New("mongoqueue: lease must be > 0")

ErrInvalidLease signals a non-positive lease duration: lease <= 0 on Claim or extend <= 0 on Heartbeat. A lease must push visibility into the future.

View Source
var ErrInvalidWeight = errors.New("mongoqueue: weight must be >= 1 (zero means 1)")

ErrInvalidWeight signals a negative EnqueueOpts.Weight. Weight must be >= 1; the zero value means 1.

View Source
var ErrJobNotFound = errors.New("mongoqueue: job not found")

ErrJobNotFound signals a Get for an unknown job id.

View Source
var ErrJobResolved = errors.New("mongoqueue: job already resolved")

ErrJobResolved signals a Cancel whose pending-only update matched nothing while a record with that id existed at the diagnostic read. It does not prove the job (or the record now present) was resolved by anyone in particular, nor that this cancel won; a caller that needs to know inspects Resolution via Get.

View Source
var ErrKindMismatch = errors.New("mongoqueue: job kind does not match binding")

ErrKindMismatch signals a Decode through a binding whose kind does not match the job's stored kind -- kind↔type drift caught at the boundary instead of silently decoding one kind's body as another's type. The wrapping error carries both kind strings; match with errors.Is.

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

ErrLeaseLost signals that a claim is no longer held. Returned by Heartbeat, Release, and Complete when the job no longer carries this claim's claim ID: the job was reclaimed by another worker, released, canceled, already completed, or deleted. A worker that needs to tell these apart calls Get and reads the record.

View Source
var ErrMissingJobID = errors.New("mongoqueue: job id is required")

ErrMissingJobID signals an empty job id: an enqueue with an empty EnqueueOpts.JobID, or a Get or Cancel with an empty jobID (rejected before any server round trip). The job id is the record's _id and the idempotency key, so the library cannot invent one; the caller must supply it.

View Source
var ErrNoJob = errors.New("mongoqueue: no claimable job")

ErrNoJob signals an empty visible set in the partition -- expected, not failure. Returned by Claim. It plays the role of mongo.ErrNoDocuments at the queue boundary but does not wrap it.

View Source
var ErrVTimeOverflow = errors.New("mongoqueue: virtual time overflow")

ErrVTimeOverflow signals an enqueue whose virtual timestamp would exceed int64: the cost is too large to scale, or the (tenant, partition) timeline has exhausted its virtual clock. Nothing is inserted. The fixed-point budget is sized to be out of reach; hitting it means costs are expressed in units far finer than the budget assumes.

Functions

This section is empty.

Types

type ClaimedJob

type ClaimedJob struct {
	Job
	// contains filtered or unexported fields
}

ClaimedJob is the handle a worker receives from Claim: the claimed record plus the claim ID that authorizes Heartbeat, Release, and Complete. Each claim assigns the job a new random claim ID, and those methods succeed only while the stored job still carries it, so a worker whose job was reclaimed by another worker cannot touch it.

The embedded Job is an immutable claim-time snapshot. Later operations do not update it; call Get for fresh state. Mutating its exported fields (including Job.ID and Job.ClaimID) changes nothing server-side and does not affect later operations on the handle, which use the job id and claim ID captured privately at claim time. Methods on a ClaimedJob read only that immutable private state and are safe to call concurrently.

func (*ClaimedJob) ClaimID

func (c *ClaimedJob) ClaimID() string

ClaimID returns the claim ID assigned by this claim: 24 lowercase hex characters, never empty.

func (*ClaimedJob) Complete

func (c *ClaimedJob) Complete(ctx context.Context, r Resolution) error

Complete resolves the claimed job with r: liveness becomes resolved, Resolution r, and ResolvedAt server time. A resolved job never becomes claimable again. A holder whose lease expired but was not reclaimed still holds its claim and may complete.

r must be non-empty; an empty r returns ErrEmptyResolution before any server round trip. If the job no longer carries this claim's ID (reclaimed, released, canceled, already completed, or deleted) Complete returns ErrLeaseLost. Complete is not success-idempotent: repeating it after a success returns ErrLeaseLost. Other errors wrap the driver error; a context timeout or network error leaves the outcome unknown, and Get can show the current state but cannot prove which call caused it.

func (*ClaimedJob) Heartbeat

func (c *ClaimedJob) Heartbeat(ctx context.Context, extend time.Duration) error

Heartbeat extends the lease: visible_at becomes server time plus extend. The extension is measured from now, not from the current visible_at, so repeated heartbeats do not stack. A holder whose lease expired but was not reclaimed still holds its claim and may heartbeat.

extend must be positive; extend <= 0 returns ErrInvalidLease before any server round trip. Sub-millisecond extensions round up to one millisecond. If the job no longer carries this claim's ID (reclaimed, released, canceled, completed, or deleted) Heartbeat returns ErrLeaseLost. Other errors wrap the driver error; a context timeout or network error leaves the outcome unknown.

Example

Long work keeps its lease alive with a heartbeat goroutine and stops when the lease is lost, since another worker may then hold the job. queue and resizeKind are set up as in the package example; resize is the caller's (idempotent) work.

package main

import (
	"context"
	"log"
	"time"

	"github.com/xdg-go/mongoqueue"
)

// Resize is the body of a "resize" job: caller domain data, stored as a
// BSON subdocument.
type Resize struct {
	URL   string `bson:"url"`
	Width int    `bson:"width"`
}

// resizeKind pairs the "resize" kind with its body type at one site.
var resizeKind = mongoqueue.NewKind[Resize]("resize")

// resize stands in for the caller's work. Effects are at-least-once, so it
// must be idempotent.
func resize(_ context.Context, _ Resize) error { return nil }

// queue stands for a Queue set up as in the package example.
var queue *mongoqueue.Queue

func main() {
	ctx := context.Background()
	job, err := queue.Claim(ctx, "", 30*time.Second)
	if err != nil {
		return // see Example for ErrNoJob backoff
	}

	workCtx, cancel := context.WithCancel(ctx)
	defer cancel()
	done := make(chan struct{})
	go func() {
		defer close(done)
		ticker := time.NewTicker(10 * time.Second) // well inside the lease
		defer ticker.Stop()
		for {
			select {
			case <-workCtx.Done():
				return
			case <-ticker.C:
				if err := job.Heartbeat(workCtx, 30*time.Second); err != nil {
					log.Printf("heartbeat %s: %v", job.ID, err)
					cancel() // ErrLeaseLost or not, stop working blind
					return
				}
			}
		}
	}()

	body, err := resizeKind.Decode(&job.Job)
	if err == nil {
		err = resize(workCtx, body)
	}
	cancel()
	<-done // no late heartbeat may race the Complete
	if err == nil {
		err = job.Complete(ctx, mongoqueue.ResolutionCompleted)
	}
	if err != nil {
		log.Printf("job %s: %v", job.ID, err)
	}
}

func (*ClaimedJob) Release

func (c *ClaimedJob) Release(ctx context.Context, delay time.Duration) error

Release gives up the claim early: visible_at becomes server time plus delay and the claim ID is cleared, so the job is reclaimable once delay elapses (immediately for zero). The next claim increments Attempts and assigns a new claim ID; VStamp is unchanged.

delay must be non-negative; delay < 0 returns ErrInvalidDelay before any server round trip. If the job no longer carries this claim's ID, Release returns ErrLeaseLost. Release is not success-idempotent: repeating it after a success returns ErrLeaseLost, as does a later Heartbeat or Complete. Other errors wrap the driver error; a context timeout or network error leaves the outcome unknown.

Example

A transient failure releases the job to be retried after a delay. The queue never caps retries, so the worker gives up itself once Attempts reaches its limit, recording a caller-defined resolution. queue and resizeKind are set up as in the package example; resize is the caller's (idempotent) work.

package main

import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/xdg-go/mongoqueue"
)

// Resize is the body of a "resize" job: caller domain data, stored as a
// BSON subdocument.
type Resize struct {
	URL   string `bson:"url"`
	Width int    `bson:"width"`
}

// resizeKind pairs the "resize" kind with its body type at one site.
var resizeKind = mongoqueue.NewKind[Resize]("resize")

// resize stands in for the caller's work. Effects are at-least-once, so it
// must be idempotent.
func resize(_ context.Context, _ Resize) error { return nil }

// queue stands for a Queue set up as in the package example.
var queue *mongoqueue.Queue

func main() {
	ctx := context.Background()
	job, err := queue.Claim(ctx, "", 30*time.Second)
	if err != nil {
		return // see Example for ErrNoJob backoff
	}
	const maxAttempts = 5

	body, err := resizeKind.Decode(&job.Job)
	if err != nil { // Poison: no retry will decode it.
		err = job.Complete(ctx, "undecodable")
	} else if workErr := resize(ctx, body); workErr == nil {
		err = job.Complete(ctx, mongoqueue.ResolutionCompleted)
	} else if job.Attempts >= maxAttempts {
		log.Printf("job %s: giving up: %v", job.ID, workErr)
		err = job.Complete(ctx, "failed")
	} else {
		// Linear backoff by attempt; any policy works.
		err = job.Release(ctx, time.Duration(job.Attempts)*time.Minute)
	}
	if errors.Is(err, mongoqueue.ErrLeaseLost) {
		return // lease expired or job canceled; someone else owns it now
	}
	if err != nil {
		log.Printf("job %s: %v", job.ID, err)
	}
}

type EnqueueOpts

type EnqueueOpts struct {
	// JobID is the caller-supplied job id: the record's Mongo "_id" and
	// the idempotency key for enqueue. Required; enqueue rejects an empty
	// id with ErrMissingJobID.
	JobID string

	// TenantID names the tenant whose virtual timeline the job is stamped
	// on. Single-tenant callers leave it empty -- one tenant named "" is
	// the degenerate case, same code path.
	TenantID string

	// Partition scopes claims; empty means the default partition. The
	// literal "default" names that same partition, so passing it is
	// equivalent to leaving Partition empty.
	Partition string

	// Cost is the job's declared cost in cost-units. Zero and negative
	// values are floored to 1 (the cheapest possible job), never rejected.
	Cost int64

	// Weight is the tenant's fair-share weight for this enqueue. Zero
	// means 1; otherwise it must be >= 1, and a negative value is
	// rejected with ErrInvalidWeight. Every producer for a tenant must
	// pass the same Weight: the stride is computed per enqueue, so mixed
	// weights give the tenant a share that depends on which producer
	// enqueued each job.
	Weight int64

	// Delay postpones the job's first visibility: visible_at is set to
	// enqueue time plus Delay. Zero means immediately visible; a negative
	// value is rejected with ErrInvalidDelay. The vstamp is still assigned
	// at enqueue, so a delayed job keeps its enqueue-time fairness position
	// and, once visible, competes ahead of work its tenant enqueued later.
	Delay time.Duration
}

EnqueueOpts carries the caller-supplied envelope fields for one enqueue. It is the input counterpart of the Job record: the caller never constructs a Job, and fields the library computes (vstamp, liveness, claim state) are not settable here. Envelope fields go here, not in the body, because the library never reads the body.

Enqueues for one (tenant, partition) timeline must come from a single writer: one node and, within it, one Queue. Each Queue caches its own copy of the timeline's virtual time, so two writers stamp from independent copies and give that tenant more than its share until Queue.Reconcile re-seeds them.

type Job

type Job struct {
	// ID is the caller-supplied job id, serving as both the record's
	// Mongo "_id" and the idempotency key for enqueue.
	ID string `bson:"_id"`

	// TenantID identifies the tenant whose virtual timeline the job is
	// stamped on. Stored under the BSON field "tenant".
	TenantID string `bson:"tenant"`

	// Partition scopes claims; the empty string at enqueue means the
	// default partition.
	Partition string `bson:"partition"`

	// Cost is the caller-declared cost used to compute the job's stride
	// on its (tenant, partition) timeline (floored to a small positive
	// minimum at enqueue).
	Cost int64 `bson:"cost"`

	// VStamp is the job's virtual timestamp: fixed-point virtual time as
	// an int64. Workers claim the lowest visible (VStamp, ID) pair.
	VStamp int64 `bson:"vstamp"`

	// Liveness is the job's lifecycle state, always present.
	Liveness Liveness `bson:"liveness"`

	// Resolution records how the job ended, in a caller-defined
	// vocabulary. Set by the terminal write (Complete or Cancel); absent
	// while pending.
	Resolution Resolution `bson:"resolution,omitempty"`

	// ClaimID identifies the current claim; each claim assigns a new one.
	// It is never empty while a claim is live; Release clears it.
	ClaimID string `bson:"claim_id"`

	// VisibleAt gates claim eligibility: a pending job is claimable only
	// once VisibleAt has passed. A claim pushes it forward (the lease),
	// Heartbeat extends it, and Release resets it to now plus a
	// caller-chosen delay.
	VisibleAt time.Time `bson:"visible_at"`

	// Attempts counts claims of this job, incremented at each dispatch.
	// The queue never caps it: a job whose worker keeps failing or dying
	// is reclaimed indefinitely, so a worker that wants bounded retries
	// checks Attempts after Claim and resolves the job itself once it
	// reaches the caller's limit.
	Attempts int `bson:"attempts"`

	// StampedBy is the id of the node that stamped the job's VStamp --
	// the hook for detecting unintended multi-writer enqueue on a
	// (tenant, partition) timeline.
	StampedBy string `bson:"stamped_by"`

	// ResolvedAt is set by the terminal write and keys TTL garbage
	// collection of resolved jobs. Absent (zero) while pending.
	ResolvedAt time.Time `bson:"resolved_at,omitempty"`

	// Kind is the decode discriminator -- the body's content-type,
	// keying the typed Enqueue/Decode facade. Never interpreted by the
	// queue core.
	Kind string `bson:"kind"`

	// Body is the caller's domain data, stored as a native BSON
	// subdocument: opaque to queue code, queryable in the database.
	Body bson.Raw `bson:"body"`
}

Job is the durable record of an enqueued job: the library-owned envelope (fields the library writes, and may guard or sort on) plus the payload (the kind discriminator and the caller's opaque body).

A Job returned by the library is a detached, read-only snapshot of the stored record. Mutating it changes nothing server-side. Callers never construct a Job: enqueue input is the separate EnqueueOpts struct, and the library computes the rest.

Fields are exported because the MongoDB Go driver marshals only exported fields; the bson tags give the wire names.

type Kind

type Kind[T any] struct {
	// contains filtered or unexported fields
}

Kind pairs a stable kind string with a body type T. The binding is the single place that pairs a kind name with a body type; declare it once, typically as a package-level var, and use it for both Enqueue and Decode. The queue stores the kind string without interpreting it; it is the body's content-type, read only by Decode and by worker-side dispatch.

One Queue carries many kinds over the shared fairness timeline.

func NewKind

func NewKind[T any](kind string) Kind[T]

NewKind returns the binding of kind to body type T. It panics on an empty kind: a binding is declared once at init time, so an empty kind is a programmer error surfaced immediately.

func (Kind[T]) Decode

func (k Kind[T]) Decode(j *Job) (T, error)

Decode unmarshals j's body as a T after asserting j.Kind matches the binding's kind. A mismatch returns ErrKindMismatch wrapped with both kind strings rather than silently decoding another kind's body into the wrong type. Decode assumes a facade-produced body: a record inserted outside the facade with a nil body decodes to T's zero value without error.

func (Kind[T]) Enqueue

func (k Kind[T]) Enqueue(ctx context.Context, q *Queue, body T, opts EnqueueOpts) error

Enqueue marshals body to BSON and enqueues it on q under the binding's kind. The binding owns the marshal, so the stored body is always the BSON form of a T. A Kind[bson.Raw] accepts a caller-built body (bson.Marshal still rejects malformed framing) but opts out of the kind-to-type pairing.

Bodies must marshal to a BSON document: bson.Marshal rejects top-level scalars and arrays, and that error is surfaced as-is. See EnqueueOpts for the envelope fields and Queue-level errors (ErrMissingJobID, ErrInvalidWeight, ErrDuplicateJob).

func (Kind[T]) Kind

func (k Kind[T]) Kind() string

Kind returns the binding's kind string -- the value stored in Job.Kind for every job the binding enqueues. Worker-side dispatch switches on the envelope's Kind field and calls the matching binding's Decode.

type Liveness

type Liveness string

Liveness is the two-value lifecycle state of a job: pending (awaiting or undergoing service) or resolved (terminal). There is no separate "claimed" state -- a claimed job is pending with a live lease, and an expired lease re-enters the visible set with no state transition.

Liveness is stored under the BSON field "liveness", always present, and the stored value matches the constants exactly (e.g. for caller queries).

const (
	// LivenessPending marks a job awaiting or undergoing service.
	LivenessPending Liveness = "pending"

	// LivenessResolved marks a terminal job. Exactly one terminal write
	// (complete or cancel) wins the transition; a resolved job never
	// re-enters the visible set.
	LivenessResolved Liveness = "resolved"
)

type Option

type Option func(*Queue)

Option configures a Queue at construction time. Options are applied by New in the order given.

func WithNodeID

func WithNodeID(id string) Option

WithNodeID overrides the default per-process node id. The node id is recorded as stamped_by on every enqueue; setting it explicitly is useful for tests that simulate several writers from one process and for deployments that want a stable, human-meaningful identifier.

type Queue

type Queue struct {
	// contains filtered or unexported fields
}

Queue is a handle to a fair, multi-tenant job queue backed by a single MongoDB collection. It is constructed with New and carries no live resources of its own; the caller owns the *mongo.Collection and its client lifecycle. A Queue is safe to share across goroutines once constructed.

func New

func New(coll *mongo.Collection, opts ...Option) *Queue

New returns a Queue over coll. It performs no I/O -- no index creation, no ping, no round trip -- so it never fails and never blocks on the server. Index creation is caller-invoked via EnsureIndexes and EnsureTTLIndex.

By default the queue mints a node id of the form hostname-pid-<random hex>; pass WithNodeID to override it.

Claim checks rely on acknowledged writes: the queue never inspects or overrides coll's write concern, so that choice is the caller's. An unacknowledged write concern (w: 0) breaks them, because the queue cannot see that a write matched no job. Single resolution across a failover requires w: "majority"; a w: 1 write can roll back, letting a second resolution win.

The queue also requires coll's default collation to be simple (binary): a non-simple collation makes partition matching and the _id tie-break follow it (a case-insensitive one matches partition "A" to "a"). The client must not omit empty values (BSONOptions.OmitEmpty or equivalent): the envelope relies on zero values such as attempts: 0 and vstamp: 0 being stored, and omitting them breaks attempt counting and claim ordering. Seed reads (which go to the primary) must observe the queue's own acknowledged inserts: use the default "local" read concern, or pair "majority" reads with w: "majority" writes. With w: 1 writes and "majority" reads, an acknowledged insert can be missing from the snapshot the seed reads, and the timeline re-issues that job's vstamp.

func (*Queue) Cancel

func (q *Queue) Cancel(ctx context.Context, jobID string) error

Cancel resolves a pending job with ResolutionCanceled, whether or not it is claimed. It needs no claim ID and leaves claim_id intact, so a holder's next Heartbeat, Release, or Complete returns ErrLeaseLost.

An empty jobID returns ErrMissingJobID before any server round trip. If the update matches no pending job, one primary read classifies the miss:

  • absent: ErrJobNotFound.
  • resolved: ErrJobResolved.
  • pending: ErrJobResolved, without retrying against what may be a different job. The id was inserted after the update missed: either the target resolved, was TTL-deleted, and the id was reused, or the id did not exist yet and a concurrent first enqueue inserted it.

See ErrJobResolved for what that error does and does not prove. Other errors wrap the driver error; a context timeout or network error leaves the outcome unknown.

func (*Queue) Claim

func (q *Queue) Claim(ctx context.Context, partition string, lease time.Duration) (*ClaimedJob, error)

Claim leases the visible pending job in partition with the lowest (VStamp, ID) and returns a handle to it. An empty partition means the default partition, as at enqueue.

The claim is one atomic server-side write: it assigns a new claim ID, pushes visible_at to server time plus lease, and increments Attempts. Concurrent claimers never receive the same job while its lease is live; an expired lease makes the job claimable again with no sweeper.

Effects are at-least-once: a worker that stalls past its lease, crashes, or loses its Complete to a timeout can leave work done while the job is claimed again, so workers must be idempotent.

lease must be positive; lease <= 0 returns ErrInvalidLease before any server round trip. Sub-millisecond leases round up to one millisecond. An empty visible set returns ErrNoJob. Other errors wrap the driver error; a context timeout or network error leaves the outcome unknown (the job may have been claimed and will become visible again when the lease lapses). On any error the returned handle is nil.

func (*Queue) EnsureIndexes

func (q *Queue) EnsureIndexes(ctx context.Context) error

EnsureIndexes creates the three partial indexes the queue's reads depend on.

  • claim {partition: 1, vstamp: 1, _id: 1, visible_at: 1}, partial on {liveness: "pending"}, serves Claim and the frontier's fallback: the leading keys match the claim filter and its (vstamp, _id) sort, and visible_at rides in the index so the visibility predicate filters in-index without fetching documents.
  • seed {tenant: 1, partition: 1, vstamp: -1}, partial on {liveness: "pending"}, serves the seed query, which reads a (tenant, partition) timeline's maximum pending vstamp.
  • clock {partition: 1, vstamp: -1}, partial on {claim_id: {$gt: ""}}, serves the frontier's service clock, the maximum vstamp among a partition's claimed, unreleased jobs.

Each index is partial, so it holds only the jobs its queries can match.

Indexes are named, so re-calling EnsureIndexes with identical specifications is a server-side no-op and returns no error. The names mongoqueue_claim, mongoqueue_seed, and mongoqueue_clock are reserved on the collection. Indexes from earlier versions of this library are not dropped: the auto-named partition_1_liveness_1_vstamp_1__id_1_visible_at_1_claim_id_1 and tenant_1_partition_1_liveness_1_vstamp_-1 serve no query, and the operator can safely drop them. Index creation is never automatic, because runtime credentials often lack createIndex and index builds on a populated collection are a scheduled operational event.

func (*Queue) EnsureTTLIndex

func (q *Queue) EnsureTTLIndex(ctx context.Context, retention time.Duration) error

EnsureTTLIndex creates the garbage-collection TTL index, named mongoqueue_ttl (reserved on the collection), on resolved_at with expireAfterSeconds derived from retention. The index is partial on liveness: resolved, so it holds resolved jobs only and the TTL can never delete a pending or claimed job, whatever fields that job carries.

There is no default retention and no TTL index unless the caller invokes this.

Re-calling with the same retention is a no-op. Re-calling with a different retention returns the driver's index-conflict error rather than silently dropping and recreating the index; the caller resolves the change with a collMod command against expireAfterSeconds.

retention must be at least one second and at most math.MaxInt32 seconds (~68 years). MongoDB TTL granularity is whole seconds, so a sub-second retention would truncate to expireAfterSeconds: 0 -- deleting every resolved job the instant it resolves. Rather than create that silent-data-loss index, EnsureTTLIndex rejects an out-of-range retention before any server round trip.

Keep retention well above the time between claims in a partition: the dispatch frontier reads resolved jobs' stamps, and a retention short enough to remove them all degrades where new tenants join.

func (*Queue) Get

func (q *Queue) Get(ctx context.Context, jobID string) (*Job, error)

Get returns a fresh copy of the stored record for jobID, read from the primary so a secondary cannot return stale state. It is the source of fresh state for ClaimedJob holders, whose handle is a claim-time snapshot. Mutating the returned Job changes nothing server-side.

An empty jobID returns ErrMissingJobID before any server round trip. An absent job returns ErrJobNotFound. Other errors wrap the driver error. On any error the returned Job is nil.

func (*Queue) Reconcile

func (q *Queue) Reconcile(ctx context.Context) error

Reconcile brings this Queue's in-memory fairness state back in line with the jobs stored in the database. Callers must run it periodically for the life of the Queue, typically on a ticker (see the example). Every 10 to 60 seconds suits most workloads; 30 seconds is a reasonable default.

To avoid a database read on every enqueue, a Queue keeps each tenant's virtual clock (one per tenant and partition) in memory. A clock that is in use can fall out of step with the stored jobs:

  • A tenant whose backlog was fully served keeps an old clock, so its next jobs sort ahead of work other tenants have been waiting on.
  • Canceling a tenant's most recently enqueued jobs leaves its clock counting them, so its later jobs sort further back than they should.
  • Another writer enqueuing for the same tenant and partition (against the single-writer requirement in EnqueueOpts, or briefly while enqueuing moves between nodes) advances the stored jobs but not this Queue's clock.

Each call makes every clock used since the previous call re-read its position from the database at its next enqueue, so an error lasts at most about one interval. A shorter interval keeps fairness tighter at the cost of more reads: each call does one or two indexed reads per partition with a clock in memory, and each clock used during the interval does one more at its next enqueue. Clocks unused for two consecutive calls are dropped from memory. A new tenant, or one whose clock was dropped, starts in the right place without Reconcile.

Failures from individual partitions are joined into the returned error; the other partitions still proceed. Retrying on the next tick is sufficient. Reconcile is safe to call concurrently with itself and with all other Queue methods.

Example

Run Reconcile on a ticker for the life of the queue. A failed call is logged and retried on the next tick.

package main

import (
	"context"
	"log"
	"time"

	"github.com/xdg-go/mongoqueue"
)

// queue stands for a Queue set up as in the package example.
var queue *mongoqueue.Queue

func main() {
	q := queue // set up as in the package example

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	go func() {
		ticker := time.NewTicker(30 * time.Second)
		defer ticker.Stop()
		for {
			select {
			case <-ctx.Done():
				return
			case <-ticker.C:
				if err := q.Reconcile(ctx); err != nil {
					log.Printf("reconcile: %v", err)
				}
			}
		}
	}()

	// ... enqueue and claim jobs until shutdown, then cancel ctx ...
}

type Resolution

type Resolution string

Resolution records how a job ended. It is set by the terminal write (Complete or Cancel) and is absent while pending. Complete rejects an empty value with ErrEmptyResolution; Cancel writes ResolutionCanceled.

The vocabulary is open: beyond the two canonical values, callers may define their own, including a "failed" one for reporting, which the library does not interpret. There is no ResolutionFailed because the library has no retry concept: a failure to retry is a Release, not a Complete.

Keep caller-defined values low-cardinality, stable, and machine-matchable; human-readable detail (error text, hostnames) does not belong here.

const (
	// ResolutionCompleted is the default vocabulary for a job its lease
	// holder finished normally. Callers with a richer outcome vocabulary
	// pass their own values to Complete instead.
	ResolutionCompleted Resolution = "completed"

	// ResolutionCanceled is written by Cancel unconditionally -- the
	// canceller supplies no resolution. By convention callers never pass
	// this value to Complete, which keeps a stored "canceled" a reliable
	// marker of the cancel path.
	ResolutionCanceled Resolution = "canceled"
)

Directories

Path Synopsis
internal
mongotest
Package mongotest provides a hermetic MongoDB test harness.
Package mongotest provides a hermetic MongoDB test harness.

Jump to

Keyboard shortcuts

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