jobs

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: Apache-2.0 Imports: 16 Imported by: ? 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

durable-jobs

durable-jobs is a Go library for durable background jobs: jobs are persisted before anything else happens, claimed atomically, executed under fenced leases with heartbeats, retried with bounded exponential backoff, recovered when a worker disappears, and scheduled once or at fixed intervals. It is for Go services that need work to survive crashes and restarts, from a single process with an embedded database to many replicas sharing PostgreSQL.

Features

  • DurableClient: validated enqueue that persists the job before it publishes a queue wakeup, plus Get and Cancel.
  • Worker: claims jobs under a coordination lease whose fencing token guards every heartbeat, completion and failure, so a worker that lost its lease can never commit a result. Run polls; RunOne executes at most one job.
  • Retries with bounded exponential backoff (RetryPolicy, RetryDelay); handler panics and missing handlers are recorded as non-retryable failures.
  • Cooperative cancellation of pending and running jobs.
  • NewRecoveryEngine: returns expired attempts to their queue through a fenced compare-and-swap, built on reconciliation.
  • Scheduler: one-shot and fixed-interval schedules with idempotent occurrence IDs and revision-fenced cursors.
  • Dependency workflows (DependsOn): a job runs only after its prerequisites succeed; failed or canceled prerequisites fail their dependents transitively.
  • Catalog: bounded, queue-scoped, cursor-paginated job listing for operator tools.
  • Typed lifecycle Events published through messaging.
  • Three stores with identical semantics: in-memory, bbolt (embedded, crash-safe) and PostgreSQL (multi-replica), all verified by the public storetest contract suites.

Installation

go get github.com/justusschock/durable-jobs@latest
# optional, PostgreSQL store (separate module, pulls in pgx):
go get github.com/justusschock/durable-jobs/backend/postgres@latest

Requires Go 1.25 or newer. The PostgreSQL store requires PostgreSQL 12 or newer.

Quick start

This is Example, compiled and run by go test:

package main

import (
	"context"
	"fmt"
	"time"

	coordinationmemory "github.com/justusschock/distributed-coordination/memory"
	jobs "github.com/justusschock/durable-jobs"
	"github.com/justusschock/durable-jobs/backend/memory"
	messagingmemory "github.com/justusschock/messaging/memory"
)

// systemClock is the production jobs.Clock: it reads the wall clock.
type systemClock struct{}

func (systemClock) Now() time.Time { return time.Now() }

func main() {
	ctx := context.Background()
	store := memory.New()

	client, err := jobs.NewClient(store, messagingmemory.NewBroker[jobs.Wakeup](time.Second), systemClock{})
	if err != nil {
		panic(err)
	}
	if _, err := client.Enqueue(ctx, jobs.EnqueueRequest{
		ID:      "greet-1",
		Queue:   "default",
		Kind:    "greet",
		Payload: []byte("world"),
		Retry:   jobs.RetryPolicy{MaxAttempts: 3, InitialBackoff: time.Second, MaxBackoff: time.Minute, Multiplier: 2},
	}); err != nil {
		panic(err)
	}

	registry := jobs.MapRegistry{
		"greet": func(_ context.Context, job jobs.Job) (jobs.Result, error) {
			return jobs.Result{Payload: append([]byte("hello, "), job.Payload...)}, nil
		},
	}
	worker, err := jobs.NewWorker(store, coordinationmemory.NewBackend(nil), messagingmemory.NewBroker[jobs.Event](time.Second), registry, jobs.WorkerOptions{
		WorkerID:          "worker-1",
		Queues:            []jobs.Queue{"default"},
		PollInterval:      time.Second,
		LeaseTTL:          30 * time.Second,
		HeartbeatInterval: 10 * time.Second,
		ClaimLimit:        10,
		Clock:             systemClock{},
	})
	if err != nil {
		panic(err)
	}
	// Run(ctx) polls until ctx ends; RunOne executes at most one job.
	if _, err := worker.RunOne(ctx); err != nil {
		panic(err)
	}

	job, err := client.Get(ctx, "greet-1")
	if err != nil {
		panic(err)
	}
	fmt.Println(job.State == jobs.StateSucceeded, string(job.Result)) // true hello, world
}

In production, use backend/bolt or backend/postgres as the store, a distributed distributed-coordination backend for leases, and a real messaging publisher. ExampleDurableClient and ExampleScheduler show enqueueing and schedules.

Packages

Package Purpose
github.com/justusschock/durable-jobs (package jobs) Job model, Store/Catalog/ScheduleStore contracts, DurableClient, Worker, Scheduler, recovery engine, errors and events.
.../backend/memory Mutex-backed in-memory store for tests and local use.
.../backend/bolt Crash-safe bbolt store for single-process persistence, with a read-only inspection mode.
.../backend/postgres PostgreSQL store for multi-process and multi-replica deployments (nested module).
.../storetest Contract suites (Run, RunCatalog, RunSchedule) every store implementation must pass.

Packages under internal/ are not part of the API.

bbolt store

bolt.Open(path, bolt.Options{}) creates or opens an owner-only (0600) database file and validates its schema; symlinked paths are rejected. bolt.Options{ReadOnly: true} opens an existing, initialized database without creating, initializing, chmodding or writing it. bbolt allows one writable process per file, and a read-only handle cannot coexist with a writable one.

PostgreSQL store

backend/postgres is a separate module, so only programs that use it depend on pgx.

pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
	return err
}
store, err := postgres.Open(ctx, pool, postgres.Options{Schema: "durable_jobs"})
if err != nil {
	return err
}
if err := store.Migrate(ctx); err != nil {
	return err
}

Open checks connectivity but never changes the database; the caller keeps ownership of the pool. Migrate applies the embedded, versioned SQL migrations under a transaction-scoped advisory lock, so it is safe to call from every replica at startup; applied versions are recorded in <schema>.schema_migrations. Every mutation is one read-committed transaction that locks the affected rows, ClaimReady uses FOR UPDATE SKIP LOCKED, and transactions aborted by deadlocks or serialization failures are retried with bounded backoff. Timestamps keep nanosecond precision. PostgreSQL text cannot hold NUL bytes or invalid UTF-8, so such identities are rejected with ErrInvalidJob; payloads, results and headers are stored exactly.

The integration tests need a disposable database and skip without one:

cd backend/postgres
DURABLE_JOBS_POSTGRES_DSN='postgres://postgres@localhost:5432/postgres?sslmode=disable' \
  go test -race ./...

Design and guarantees

  • Durability first. Enqueue persists the job before publishing its wakeup. If publishing fails it returns the created job together with an error wrapping ErrWakeupPublish; the job stays claimable.
  • Fencing. Each claim records the lease's fencing token and an attempt generation. Heartbeat, completion, failure and recovery check both atomically in the store and return ErrStaleAttempt when either is old. Heartbeat deadlines and UpdatedAt never move backward.
  • At-least-once execution. A handler may run again after a crash or lease loss, so handlers should be idempotent. A worker that loses its lease cancels the handler and records nothing.
  • Ordering. Within a queue, ready jobs are claimed by priority (descending), then AvailableAt, then ID.
  • Snapshots. Every Job, Schedule and Attempt returned to callers is independently owned; mutating it never affects the store.
  • Concurrency. Clients, workers, schedulers and all bundled stores are safe for concurrent use. Blocking operations take a context.Context and honour cancellation.
  • Errors. Sentinel errors (ErrInvalidJob, ErrJobExists, ErrJobNotFound, ErrNoReadyJob, ErrStaleAttempt, ErrInvalidTransition, ErrDependencyFailed, ErrWakeupPublish, and each backend's ErrUnsupportedFormat) are wrapped with %w; test them with errors.Is. Errors never contain payloads, and handler error values are not persisted.
  • No logging. The library reports through return values and lifecycle events only.
  • Catalog consistency. Each ListJobPage result is one store snapshot; a traversal across pages is weakly consistent. Catalog results contain raw payloads, so redact them before display.
  • Stability. The module is at v0.x: minor releases may break the API. Every break is listed in CHANGELOG.md.

Releasing the two modules

The repository contains two modules: the core module at the root (tags vX.Y.Z) and backend/postgres (tags backend/postgres/vX.Y.Z). The PostgreSQL module requires the core module and, for development inside this repository, replaces it with ../..; that replace directive has no effect on consumers. Release them in order:

  1. Tag the core module, vX.Y.Z.
  2. In backend/postgres/go.mod, require github.com/justusschock/durable-jobs vX.Y.Z, run go mod tidy, and merge.
  3. Tag backend/postgres/vX.Y.Z on that commit.

Use the same version for both modules.

Documentation

Contributing

Changes go through pull requests against main; nothing is pushed to main directly. Read AGENTS.md first: it describes the docs-first process, the API rules, and the checks every pull request must pass.

License

Apache License 2.0. See LICENSE and NOTICE.

Documentation

Overview

Package jobs provides durable background jobs for Go: atomic queue claims, fenced execution attempts, heartbeats, bounded exponential retries, cancellation, recovery of expired attempts, one-shot and fixed-interval schedules, dependency workflows, and typed lifecycle events.

A DurableClient validates and persists jobs in a Store and publishes a Wakeup for the job's queue. A Worker claims ready jobs under a coordination lease whose fencing token guards every later heartbeat, completion, and failure, so a worker that lost its lease can never commit a result. NewRecoveryEngine returns expired attempts to their queue, and a Scheduler enqueues due Schedule occurrences idempotently.

Time comes from a caller-supplied Clock; worker polling and heartbeats use the time package's timers. Stores are provided by the backend/memory, backend/bolt, and backend/postgres packages, and the storetest package holds the contract suites that every Store implementation must pass.

Unless stated otherwise, exported types are safe for concurrent use once constructed, operations that block or perform I/O take a context and honor its cancellation, and every Job, Schedule, and Attempt returned to a caller is an independently owned snapshot.

Example

Example enqueues a job and runs it once with a worker. Production code would use a persistent store (backend/bolt or backend/postgres), a distributed coordination backend, and a real message broker.

package main

import (
	"context"
	"fmt"
	"time"

	coordinationmemory "github.com/justusschock/distributed-coordination/memory"
	jobs "github.com/justusschock/durable-jobs"
	"github.com/justusschock/durable-jobs/backend/memory"

	messagingmemory "github.com/justusschock/messaging/memory"
)

// systemClock is the production jobs.Clock: it reads the wall clock.
type systemClock struct{}

func (systemClock) Now() time.Time { return time.Now() }

func main() {
	ctx := context.Background()
	store := memory.New()

	client, err := jobs.NewClient(store, messagingmemory.NewBroker[jobs.Wakeup](time.Second), systemClock{})
	if err != nil {
		panic(err)
	}
	if _, err := client.Enqueue(ctx, jobs.EnqueueRequest{
		ID:      "greet-1",
		Queue:   "default",
		Kind:    "greet",
		Payload: []byte("world"),
		Retry:   jobs.RetryPolicy{MaxAttempts: 3, InitialBackoff: time.Second, MaxBackoff: time.Minute, Multiplier: 2},
	}); err != nil {
		panic(err)
	}

	registry := jobs.MapRegistry{
		"greet": func(_ context.Context, job jobs.Job) (jobs.Result, error) {
			return jobs.Result{Payload: append([]byte("hello, "), job.Payload...)}, nil
		},
	}
	worker, err := jobs.NewWorker(store, coordinationmemory.NewBackend(nil), messagingmemory.NewBroker[jobs.Event](time.Second), registry, jobs.WorkerOptions{
		WorkerID:          "worker-1",
		Queues:            []jobs.Queue{"default"},
		PollInterval:      time.Second,
		LeaseTTL:          30 * time.Second,
		HeartbeatInterval: 10 * time.Second,
		ClaimLimit:        10,
		Clock:             systemClock{},
	})
	if err != nil {
		panic(err)
	}
	// Run(ctx) polls until ctx ends; RunOne executes at most one job.
	if _, err := worker.RunOne(ctx); err != nil {
		panic(err)
	}

	job, err := client.Get(ctx, "greet-1")
	if err != nil {
		panic(err)
	}
	fmt.Println(job.State == jobs.StateSucceeded, string(job.Result))
}
Output:
true hello, world

Index

Examples

Constants

View Source
const MaxJobPageSize = 100

MaxJobPageSize is the largest page accepted by a Catalog.

Variables

View Source
var (
	// ErrInvalidJob reports a request, job, schedule, or constructor argument
	// that violates an invariant (identity, retry policy, dependencies,
	// catalog bounds, nil dependencies).
	ErrInvalidJob = errors.New("durable jobs: invalid job")
	// ErrJobExists reports that Create found a job with the same ID.
	ErrJobExists = errors.New("durable jobs: job exists")
	// ErrJobNotFound reports an unknown job or schedule ID.
	ErrJobNotFound = errors.New("durable jobs: job not found")
	// ErrNoReadyJob reports that ClaimReady found no claimable job.
	ErrNoReadyJob = errors.New("durable jobs: no ready job")
	// ErrStaleAttempt reports a fencing token, attempt generation, heartbeat
	// observation, or schedule revision that is no longer current.
	ErrStaleAttempt = errors.New("durable jobs: stale attempt")
	// ErrInvalidTransition reports an operation that the job's current
	// state does not allow, such as canceling a terminal job or moving a
	// heartbeat deadline backward.
	ErrInvalidTransition = errors.New("durable jobs: invalid transition")
	// ErrDependencyFailed reports a prerequisite job that failed or was
	// canceled.
	ErrDependencyFailed = errors.New("durable jobs: dependency failed")
	// ErrWakeupPublish reports that Enqueue persisted the job but could not
	// publish the queue wakeup. The job remains durable and claimable.
	ErrWakeupPublish = errors.New("durable jobs: wakeup publish")
)

Sentinel errors returned by clients, workers, schedulers, and stores. They are part of the API: callers test them with errors.Is, and implementations wrap them with %w to add detail. Error messages never contain job payloads, results, or headers.

Functions

func NewRecoveryEngine

NewRecoveryEngine constructs a one-shot fenced recovery engine.

func RetryDelay

func RetryDelay(policy RetryPolicy, attempt uint) time.Duration

RetryDelay returns the bounded exponential delay before the next attempt after attempt failed: InitialBackoff * Multiplier^(attempt-1), capped at MaxBackoff. Attempt 0 is treated as 1, and overflow saturates at MaxBackoff.

func ValidateDependencies

func ValidateDependencies(ctx context.Context, store Store, dependencies []JobID) error

ValidateDependencies verifies that dependencies exist and have not failed.

func ValidateEnqueue

func ValidateEnqueue(request EnqueueRequest) error

ValidateEnqueue verifies identity, retry, and dependency invariants without retaining or mutating request data.

func ValidateListJobPageRequest

func ValidateListJobPageRequest(request ListJobPageRequest) error

ValidateListJobPageRequest verifies catalog scope, position, and bounds.

Types

type Attempt

type Attempt struct {
	ID                AttemptID
	Job               Job
	WorkerID          string
	FencingToken      coordination.FencingToken
	StartedAt         time.Time
	HeartbeatDeadline time.Time
}

Attempt is a fenced execution claim for a job.

type AttemptID

type AttemptID string

AttemptID identifies one fenced execution attempt.

type Catalog

type Catalog interface {
	ListJobPage(context.Context, ListJobPageRequest) (JobPage, error)
}

Catalog provides bounded, queue-scoped traversal without widening Store. Each page is one store snapshot; a traversal spanning pages is not a point-in-time snapshot when jobs are created concurrently.

type ClaimRequest

type ClaimRequest struct {
	Queue             Queue
	WorkerID          string
	Now               time.Time
	HeartbeatDeadline time.Time
	FencingToken      coordination.FencingToken
}

ClaimRequest identifies a worker's request to claim one ready job.

type Client

type Client interface {
	Enqueue(context.Context, EnqueueRequest) (Job, error)
	Get(context.Context, JobID) (Job, error)
	Cancel(context.Context, JobID) error
}

Client exposes durable job submission and cancellation operations.

type Clock

type Clock interface {
	Now() time.Time
}

Clock supplies the current time to clients, workers, schedulers, and recovery. Implementations must be safe for concurrent use.

type CompleteRequest

type CompleteRequest struct {
	AttemptID    AttemptID
	FencingToken coordination.FencingToken
	Result       Result
	CompletedAt  time.Time
}

CompleteRequest records a successful attempt result.

type DurableClient

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

DurableClient persists jobs and publishes queue wakeups.

Example
now := time.Unix(100, 0).UTC()
store := memory.New()
client, _ := jobs.NewClient(store, examplePublisher[jobs.Wakeup]{}, exampleClock{now: now})
job, _ := client.Enqueue(context.Background(), exampleRequest("job-1"))

fmt.Println(job.ID, job.State == jobs.StatePending)
Output:
job-1 true

func NewClient

func NewClient(store Store, publisher messaging.Publisher[Wakeup], clock Clock) (*DurableClient, error)

NewClient constructs a durable job client.

func (*DurableClient) Cancel

func (client *DurableClient) Cancel(ctx context.Context, id JobID) error

Cancel requests cancellation using the client's clock.

func (*DurableClient) Enqueue

func (client *DurableClient) Enqueue(ctx context.Context, request EnqueueRequest) (Job, error)

Enqueue validates and durably creates a pending job before publishing a wakeup.

func (*DurableClient) Get

func (client *DurableClient) Get(ctx context.Context, id JobID) (Job, error)

Get returns the current durable job snapshot.

type EnqueueRequest

type EnqueueRequest struct {
	ID          JobID
	Queue       Queue
	Kind        string
	Payload     []byte
	Headers     map[string]string
	Priority    int
	AvailableAt time.Time
	Retry       RetryPolicy
	DependsOn   []JobID
}

EnqueueRequest describes one new durable job. A zero AvailableAt makes the job available at the client's current time. See ValidateEnqueue for the invariants.

func (EnqueueRequest) Clone

func (request EnqueueRequest) Clone() EnqueueRequest

Clone returns a request with independently owned payload, headers, and dependencies.

type Event

type Event struct {
	Kind      EventKind
	JobID     JobID
	AttemptID AttemptID
	Queue     Queue
	At        time.Time
	Failure   *Failure
}

Event is a typed durable job lifecycle notification. Failure is set for events that follow a failed attempt.

type EventKind

type EventKind string

EventKind identifies a durable job lifecycle event. Workers publish events on the subject "jobs.event.<kind>".

const (
	// EventEnqueued is reserved for job creation; the library does not
	// publish it.
	EventEnqueued EventKind = "enqueued"
	// EventStarted is published when a worker starts a handler.
	EventStarted EventKind = "started"
	// EventHeartbeat is published after each successful heartbeat.
	EventHeartbeat EventKind = "heartbeat"
	// EventSucceeded is published after a successful completion.
	EventSucceeded EventKind = "succeeded"
	// EventRetryScheduled is published when a failed attempt will be retried.
	EventRetryScheduled EventKind = "retry_scheduled"
	// EventFailed is published when a job fails terminally.
	EventFailed EventKind = "failed"
	// EventCanceled is published when a running job ends canceled.
	EventCanceled EventKind = "canceled"
	// EventRecovered is reserved for attempt recovery; the library does not
	// publish it.
	EventRecovered EventKind = "recovered"
)

Lifecycle event kinds.

type FailRequest

type FailRequest struct {
	AttemptID       AttemptID
	FencingToken    coordination.FencingToken
	Failure         Failure
	FailedAt        time.Time
	NextAvailableAt time.Time
}

FailRequest records an attempt failure and its next eligibility time.

type Failure

type Failure struct {
	Code      string
	Message   string
	Retryable bool
}

Failure is a sanitized durable failure classification. Workers record the codes "handler_error" (retryable), "handler_panic", and "handler_not_found"; stores record "dependency_failed" when a prerequisite does not succeed. Handler error values are never persisted.

type Handler

type Handler func(context.Context, Job) (Result, error)

Handler executes one durable job attempt.

type HeartbeatRequest

type HeartbeatRequest struct {
	AttemptID    AttemptID
	FencingToken coordination.FencingToken
	Deadline     time.Time
}

HeartbeatRequest extends the deadline of the current attempt.

type Job

type Job struct {
	ID    JobID
	Queue Queue
	// Kind selects the Handler in the worker's Registry.
	Kind    string
	Payload []byte
	Headers map[string]string
	// Priority orders ready jobs in a queue; higher values are claimed first.
	Priority int
	State    State
	// CreatedAt is the enqueue time.
	CreatedAt time.Time
	// AvailableAt is the earliest time the job may be claimed.
	AvailableAt time.Time
	// UpdatedAt is the latest transition time; it never moves backward.
	UpdatedAt time.Time
	// Attempt counts claims, starting at 1 for the first attempt.
	Attempt uint
	Retry   RetryPolicy
	// DependsOn lists jobs that must succeed before this job is claimable.
	DependsOn []JobID
	// CancellationRequested is set by RequestCancel on a running job; the
	// attempt then ends canceled.
	CancellationRequested bool
	// Result holds the handler output of a succeeded job.
	Result []byte
	// LastFailure is the most recent recorded failure, if any.
	LastFailure *Failure
}

Job is one independently owned durable job snapshot. Stores normalize its times to UTC without monotonic clock readings.

func (Job) Clone

func (job Job) Clone() Job

Clone returns a job with independently owned payload, result, header, dependency, and failure storage.

type JobID

type JobID string

JobID identifies one durable job.

type JobPage

type JobPage struct {
	Jobs      []Job
	NextAfter JobID
}

JobPage is one independently owned catalog page. NextAfter is empty when no more matching jobs exist in the call's store snapshot.

type ListJobPageRequest

type ListJobPageRequest struct {
	Queue Queue
	After JobID
	Limit int
}

ListJobPageRequest selects one queue-scoped catalog page in ascending bytewise order of raw JobID strings. After is an exclusive position; an empty value selects the first page.

type ListJobsRequest

type ListJobsRequest struct {
	Queue Queue
	Limit int
}

ListJobsRequest selects a bounded queue-scoped job snapshot.

type MapRegistry

type MapRegistry map[string]Handler

MapRegistry resolves handlers from a map keyed by job kind.

func (MapRegistry) Handler

func (registry MapRegistry) Handler(kind string) (Handler, bool)

Handler returns the handler registered for kind.

type Queue

type Queue string

Queue identifies an ordered claim domain.

type RecoverAttemptRequest

type RecoverAttemptRequest struct {
	AttemptID         AttemptID
	FencingToken      coordination.FencingToken
	HeartbeatDeadline time.Time
	RecoveredAt       time.Time
}

RecoverAttemptRequest identifies one expired attempt observation to recover.

type RecoveryAction

type RecoveryAction struct {
	AttemptID         AttemptID
	FencingToken      coordination.FencingToken
	HeartbeatDeadline time.Time
	RecoveredAt       time.Time
}

RecoveryAction carries the exact observation needed for a fenced recovery CAS.

type RecoveryAdapter

type RecoveryAdapter struct {
	Store Store
	Clock Clock
}

RecoveryAdapter observes and recovers expired durable job attempts.

func (RecoveryAdapter) Apply

Apply performs one fenced recovery. Obsolete observations are idempotent success.

func (RecoveryAdapter) Observe

Observe lists every currently expired candidate so Plan can apply its desired limit.

func (RecoveryAdapter) Plan

Plan deterministically selects expired attempts for non-reversible recovery.

func (RecoveryAdapter) Undo

Undo is a no-op because recovery actions are non-reversible.

type RecoveryCandidate

type RecoveryCandidate struct {
	Attempt    Attempt
	ObservedAt time.Time
}

RecoveryCandidate is an expired running attempt observed by a recovery worker.

type RecoveryObserved

type RecoveryObserved struct {
	Candidates []RecoveryCandidate
	ObservedAt time.Time
}

RecoveryObserved is one independently owned snapshot of expired attempts.

type RecoverySpec

type RecoverySpec struct {
	Limit int
}

RecoverySpec bounds the number of expired attempts recovered in one plan.

type Registry

type Registry interface {
	Handler(kind string) (Handler, bool)
}

Registry resolves handlers by job kind.

type Result

type Result struct {
	Payload []byte
}

Result is opaque handler output.

func (Result) Clone

func (result Result) Clone() Result

Clone returns independently owned result bytes.

type RetryPolicy

type RetryPolicy struct {
	// MaxAttempts is the total number of attempts, including the first;
	// it must be at least 1.
	MaxAttempts uint
	// InitialBackoff is the delay after the first failed attempt; it must be
	// positive.
	InitialBackoff time.Duration
	// MaxBackoff caps every delay; it must be at least InitialBackoff.
	MaxBackoff time.Duration
	// Multiplier scales the delay after each further failure; it must be a
	// finite number of at least 1.
	Multiplier float64
}

RetryPolicy controls bounded exponential retry scheduling. See RetryDelay.

type Schedule

type Schedule struct {
	ID        ScheduleID
	Request   EnqueueRequest
	NextRunAt time.Time
	Interval  time.Duration
	Enabled   bool
	Revision  uint64
}

Schedule describes a one-shot (zero Interval) or fixed-interval job template. Revision is assigned by the ScheduleStore.

func (Schedule) Clone

func (schedule Schedule) Clone() Schedule

Clone returns a schedule with independently owned request resources.

type ScheduleID

type ScheduleID string

ScheduleID identifies one durable schedule.

type ScheduleStore

type ScheduleStore interface {
	// PutSchedule creates (expected revision 0) or replaces (expected
	// current revision) a schedule and returns it with its new revision.
	// Creating an existing schedule returns ErrJobExists, replacing a missing
	// one ErrJobNotFound, and a mismatched revision ErrStaleAttempt.
	PutSchedule(context.Context, Schedule, uint64) (Schedule, error)
	// GetSchedule returns a schedule, or ErrJobNotFound.
	GetSchedule(context.Context, ScheduleID) (Schedule, error)
	// ListDueSchedules returns up to limit enabled schedules whose NextRunAt
	// is at or before the given time, ordered by NextRunAt and ID.
	ListDueSchedules(context.Context, time.Time, int) ([]Schedule, error)
	// AdvanceSchedule moves the schedule's cursor forward to the given time,
	// or disables it when the time is zero, if the revision is still current;
	// otherwise it returns ErrStaleAttempt. A cursor that would not move
	// forward returns ErrInvalidTransition.
	AdvanceSchedule(context.Context, ScheduleID, uint64, time.Time) error
}

ScheduleStore atomically persists schedules with revision fencing. The storetest.RunSchedule suite defines the observable contract.

type Scheduler

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

Scheduler enqueues due schedule occurrences and advances their durable cursor.

Example
now := time.Unix(100, 0).UTC()
store := memory.New()
client, _ := jobs.NewClient(store, examplePublisher[jobs.Wakeup]{}, exampleClock{now: now})
_, _ = store.PutSchedule(context.Background(), jobs.Schedule{
	ID: "hourly", Request: exampleRequest("template"), NextRunAt: now, Interval: time.Hour, Enabled: true,
}, 0)

processed, _ := jobs.NewScheduler(store, client, exampleClock{now: now}).RunDue(context.Background(), 1)
occurrenceID := jobs.JobID("hourly/" + strconv.FormatInt(now.UnixNano(), 10))
occurrence, _ := store.Get(context.Background(), occurrenceID)
fmt.Println(processed, occurrence.Kind)
Output:
1 report

func NewScheduler

func NewScheduler(store ScheduleStore, client Client, clock Clock) *Scheduler

NewScheduler constructs a durable schedule runner. Nil dependencies are reported by RunDue as ErrInvalidJob.

func (*Scheduler) RunDue

func (scheduler *Scheduler) RunDue(ctx context.Context, limit int) (int, error)

RunDue processes at most limit due schedules. Each occurrence is enqueued with the ID "<schedule-id>/<due-unix-nano>" and AvailableAt set to its due time, so a retry after a crash between enqueue and cursor advance is idempotent. An interval schedule then advances to the first due time strictly after now; a one-shot schedule is disabled. RunDue returns the number of schedules processed and stops at the first enqueue or store error without advancing that schedule.

type State

type State uint8

State is the durable job lifecycle state.

const (
	// StatePending jobs wait for AvailableAt and their dependencies.
	StatePending State = iota + 1
	// StateRunning jobs have a current fenced attempt.
	StateRunning
	// StateSucceeded jobs completed and hold their result.
	StateSucceeded
	// StateRetryWaiting jobs failed retryably and wait for AvailableAt.
	StateRetryWaiting
	// StateFailed jobs failed terminally or had a dependency fail.
	StateFailed
	// StateCanceled jobs were canceled before or during execution.
	StateCanceled
)

Job states. StateSucceeded, StateFailed, and StateCanceled are terminal.

type Store

type Store interface {
	// Create persists a new job, or returns ErrJobExists.
	Create(context.Context, Job) (Job, error)
	// Get returns a job, or ErrJobNotFound.
	Get(context.Context, JobID) (Job, error)
	// ListJobs returns up to Limit jobs of one queue, most recently updated
	// first.
	ListJobs(context.Context, ListJobsRequest) ([]Job, error)
	// ClaimReady starts a new attempt for the first claimable job of the
	// queue (pending or retry-waiting, available, all dependencies
	// succeeded), ordered by priority descending, AvailableAt ascending, and
	// ID ascending. It returns ErrNoReadyJob when none is claimable.
	ClaimReady(context.Context, ClaimRequest) (Attempt, error)
	// Heartbeat extends the current attempt's deadline. It returns
	// ErrStaleAttempt for an old attempt or fence and ErrInvalidTransition
	// for an earlier deadline or a job that is not running.
	Heartbeat(context.Context, HeartbeatRequest) error
	// Complete ends the current attempt as succeeded, or canceled when
	// cancellation was requested, under the same fencing checks as Heartbeat.
	Complete(context.Context, CompleteRequest) (Job, error)
	// Fail records a failure of the current attempt: retry-waiting until
	// NextAvailableAt while a retryable failure has attempts left, otherwise
	// failed (or canceled when requested). Terminal outcomes fail pending
	// dependents transitively.
	Fail(context.Context, FailRequest) (Job, error)
	// RequestCancel cancels a pending or retry-waiting job immediately and
	// marks a running job for cancellation. Terminal jobs return
	// ErrInvalidTransition.
	RequestCancel(context.Context, JobID, time.Time) (Job, error)
	// RecoverAttempt returns a running job whose observed attempt expired to
	// pending (or canceled when requested). The attempt ID, fence, and
	// observed deadline must all still be current.
	RecoverAttempt(context.Context, RecoverAttemptRequest) (Job, error)
	// ListRecoveryCandidates returns up to limit running attempts whose
	// heartbeat deadline is at or before the given time, ordered by deadline
	// and attempt ID.
	ListRecoveryCandidates(context.Context, time.Time, int) ([]RecoveryCandidate, error)
}

Store atomically persists durable jobs and their fenced execution attempts.

Every method is atomic, safe for concurrent use, honors ctx, and returns independently owned snapshots. The storetest.Run suite defines the full observable contract; implementations must pass it.

type Wakeup

type Wakeup struct {
	Queue       Queue
	JobID       JobID
	AvailableAt time.Time
}

Wakeup notifies workers that a job may be ready in a queue. DurableClient publishes it on the subject "jobs.wakeup.<queue>" after the job is durable.

type Worker

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

Worker claims and executes durable jobs with fenced attempts. A Worker executes one job at a time; run several workers for parallelism. Handlers receive a context that is canceled when the execution lease is lost, the worker's context ends, or cancellation of the job is requested.

func NewWorker

func NewWorker(store Store, backend coordination.Backend, events messaging.Publisher[Event], registry Registry, options WorkerOptions) (*Worker, error)

NewWorker constructs a fenced durable job worker.

func (*Worker) Run

func (worker *Worker) Run(ctx context.Context) error

Run polls configured queues until ctx is canceled and then returns the context's error. Each poll executes up to ClaimLimit jobs per queue. Store and lease errors other than an unavailable lease or no ready job end Run.

func (*Worker) RunOne

func (worker *Worker) RunOne(ctx context.Context) (bool, error)

RunOne scans the configured queues once in order and attempts to claim and execute at most one job. It does not poll and ignores PollInterval and ClaimLimit. The returned boolean reports whether ClaimReady succeeded, including when execution returns an error or aborts after the durable claim.

type WorkerOptions

type WorkerOptions struct {
	// WorkerID identifies the worker as lease owner and in attempts.
	WorkerID string
	// Queues are scanned in order on every poll.
	Queues []Queue
	// PollInterval is the pause between polls in Run.
	PollInterval time.Duration
	// LeaseTTL is the TTL of the claim and execution leases and the distance
	// of each heartbeat deadline from the heartbeat time.
	LeaseTTL time.Duration
	// HeartbeatInterval is the period of store heartbeats and cancellation
	// checks while a handler runs.
	HeartbeatInterval time.Duration
	// ClaimLimit bounds the jobs executed per queue per poll in Run.
	ClaimLimit int
	// Clock supplies the timestamps recorded in the store.
	Clock Clock
}

WorkerOptions controls durable worker polling and lease behavior. All durations and ClaimLimit must be positive.

Directories

Path Synopsis
backend
bolt
Package bolt provides a crash-safe bbolt-backed jobs.Store.
Package bolt provides a crash-safe bbolt-backed jobs.Store.
memory
Package memory provides an in-memory Store implementation for tests and local use.
Package memory provides an in-memory Store implementation for tests and local use.
postgres module
internal
storestate
Package storestate contains the storage-independent job transitions.
Package storestate contains the storage-independent job transitions.
Package storetest exercises the observable jobs.Store, jobs.Catalog, and jobs.ScheduleStore contracts.
Package storetest exercises the observable jobs.Store, jobs.Catalog, and jobs.ScheduleStore contracts.

Jump to

Keyboard shortcuts

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