foreman

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: Apache-2.0 Imports: 34 Imported by: 0

README

Foreman

Foreman is a Postgres-backed job queue for Go: enqueue jobs in the same transaction as your data, run them with retries, cron, unique jobs and fair per-tenant concurrency, with no broker to operate.

Status: v0.1.0, the first release. Before 1.0, a minor release may change the public API; every change is listed in the changelog.

CI Go Report Card Release License

Why it exists

Go services need background work: emails, file processing, long LLM calls, syncs. Goroutines lose that work on restart, and Redis or RabbitMQ queues add a second system and break transactional guarantees: the job is enqueued but the transaction rolls back, or the reverse. Postgres queues solve this, but the features multi-tenant and AI workloads need most, such as per-key concurrency limits, fairness between tenants and dead-letter handling, are often missing or paid extras. Foreman puts them in a small, typed library that stores everything in the Postgres you already run.

Quickstart

Needs Go 1.27+ and Docker. From a clone (git clone https://github.com/thnhdatle/foreman && cd foreman):

docker compose -f deploy/docker-compose.yml up -d --wait postgres
go run ./examples/basic

It prints job completed: id=1 state=completed. Stop Postgres with docker compose -f deploy/docker-compose.yml down -v. In your own code:

type EmailArgs struct {
	UserID int64  `json:"user_id"`
	Tmpl   string `json:"tmpl"`
}

func (EmailArgs) Kind() string { return "email" }

type EmailWorker struct{ mailer Mailer }

func (w *EmailWorker) Work(ctx context.Context, job *foreman.Job[EmailArgs]) error {
	return w.mailer.Send(ctx, job.Args.UserID, job.Args.Tmpl)
}

workers := foreman.NewWorkers()
foreman.AddWorker(workers, &EmailWorker{mailer: m})

client, err := foreman.NewClient(pool, foreman.Config{
	Queues:  map[string]foreman.QueueConfig{"default": {MaxWorkers: 50, PerKeyLimit: 5, Fairness: true}},
	Workers: workers,
})

tx, _ := pool.Begin(ctx)
// ... insert user ...
_, err = client.InsertTx(ctx, tx, EmailArgs{UserID: id, Tmpl: "welcome"},
	&foreman.InsertOpts{ConcurrencyKey: tenantID})
err = tx.Commit(ctx)

See getting started for migrations and shutdown.

Install

Library (Go 1.27+):

go get github.com/thnhdatle/foreman@v0.1.0

Admin CLI (migrations and job administration), one of:

go install github.com/thnhdatle/foreman/cmd/foreman@v0.1.0
docker run --rm ghcr.io/thnhdatle/foreman:v0.1.0 version

or a foreman_0.1.0_<os>_<arch>.tar.gz archive for Linux or macOS (amd64, arm64) from the releases page, checked against checksums.txt.

Architecture

flowchart LR
  APP[app tx] -->|InsertTx| T[(foreman_jobs)]
  T -->|NOTIFY foreman_insert| LS[listener]
  LS --> PR[producer per queue]
  PR -->|fetch: SKIP LOCKED + fairness + per-key limits| T
  PR --> WP[worker pool]
  WP -->|batched completions| T
  WP --> HB[heartbeats] --> T
  subgraph leader only
    EL[elector] --> SCH[scheduler]
    EL --> PER[periodic enqueuer]
    EL --> RES[rescuer]
    EL --> CLN[cleaner + reindexer]
  end
  SCH & PER & RES & CLN --> T

Jobs are rows in foreman_jobs, inserted with your transaction. Each client runs one producer per queue that wakes on NOTIFY, finished jobs or a poll, and fetches with FOR UPDATE SKIP LOCKED, honouring per-key limits (advisory locks) and fairness. Results are written in batches under a completion guard, so a stale worker can never overwrite a newer attempt. One client, elected by a lease row, runs maintenance: due jobs, rescue of jobs whose worker died, retention cleanup, reindexing and periodic jobs. Every time value comes from the client clock, so the whole system runs in simulated time in tests.

Features

  • Typed jobs and workers: generic Worker[T], results Snooze, Discard, Cancel, panic recovery, timeouts, middleware, OpenTelemetry spans — workers.
  • Transactional enqueue and completion: InsertTx, InsertManyTx (COPY), CompleteTx — transactional enqueue.
  • Retries and dead letters: exponential backoff with full jitter, per-kind policies, discarded jobs, bulk retry, rescue of stuck jobs — retries and dead letters.
  • Periodic jobs: cron (with seconds and time zones) or Every, exactly once per tick across leader changes, catch-up window — periodic jobs.
  • Unique jobs: by args, selected fields, queue, period and states, with one canonical form in SQL shared by every language — unique jobs.
  • Per-key concurrency and fairness: cap running jobs per tenant across the cluster and stop one tenant's backlog from starving others — concurrency and fairness.
  • Any language can enqueue: the SQL function foreman_insert_job — insert from other languages.
  • Operations: cancel and pause, admin JSON API (foremanhttp), CLI, Prometheus metrics, PgBouncer support (PollOnly), test helpers (foremantest) — operations.

Benchmarks

Foreman v0.1.0 pre-release build on a MacBook Pro M3 Pro 36 GB, macOS 26.1, Docker Desktop VM 8 CPU / 20 GB, Postgres 17, Go 1.27.2; clients run natively on the host; medians of 3 runs. Full results and method: bench/RESULTS.md.

Scenario Result Target
Throughput, no-op jobs, 4 clients x 50 workers, 1M backlog, 5 min 35,518 jobs/s >= 5,000
Same with fairness and per-key limit 50 over 1,000 keys 6,378 jobs/s reported
Pickup latency p99 at 1,000 inserts/s 8.7 ms < 100 ms
Small tenant p95 wait behind a 240k backlog, fair vs unfair 38 ms vs 64.6 s <= 100 ms
Soak, 1 h at 1,000 jobs/s: size and p99 drift 0.3% / 0.1% <= 20% / 50%

Correctness under failures is checked by the acceptance suite rather than benchmarked: for example, 1M jobs with repeated kill -9 of workers and the leader finish with no lost job (report).

Configuration

Clients are configured in code with foreman.Config; the CLI reads YAML, FOREMAN_* variables and flags. Everything is in configuration. The five options most often changed:

  • Queues["name"].MaxWorkers — jobs run at once per client and queue (default 10).
  • Queues["name"].PerKeyLimit and Fairness — per-tenant limits and fairness.
  • RetryPolicy and WithMaxAttempts — backoff and attempts (default exponential, 25).
  • CompletedJobRetention — how long completed jobs are kept (default 24h).
  • PollOnly — required behind PgBouncer in transaction pooling mode.

Known limitations

  • Delivery is at least once: a job whose worker dies is rescued and runs again, so Work must be idempotent.
  • The admin handler in foremanhttp has no authentication; protect it in your application (SECURITY.md).
  • The leader lease TTL is fixed at 15 s; failover takes up to about 20 s.
  • Behind PgBouncer in transaction pooling mode, LISTEN/NOTIFY is unavailable: set PollOnly and expect pickup latency close to the poll interval.

When not to use it

  • You need more than a few tens of thousands of jobs per second sustained, or very large payloads: a log-based broker (Kafka, NATS JetStream) fits better.
  • Your workers span regions with no single primary Postgres close to all of them.
  • You need workflows (DAGs, step checkpoints) or rate limiting per key; these are on the roadmap, not in v0.1.
  • Your workers are not written in Go: other languages can enqueue, but only Go runs jobs.

Roadmap

Deferred features and good first issues are listed in ROADMAP.md.

Contributing and license

Contributions are welcome: see CONTRIBUTING.md and the code of conduct. Foreman is licensed under Apache-2.0.

Documentation

Overview

Package foreman is a Postgres-backed job queue for Go: enqueue jobs in the same transaction as your data, run them with retries, cron, unique jobs and fair per-tenant concurrency, with no broker to operate.

Main types: Client (inserts jobs, runs worker pools and maintenance), Worker (typed job handler), JobArgs (job payload), Config.

type EmailArgs struct {
	UserID int64 `json:"user_id"`
}

func (EmailArgs) Kind() string { return "email" }

workers := foreman.NewWorkers()
foreman.AddWorker(workers, &EmailWorker{})
client, err := foreman.NewClient(pool, foreman.Config{
	Queues:  map[string]foreman.QueueConfig{"default": {MaxWorkers: 50}},
	Workers: workers,
})
Example

Example shows the whole lifecycle: migrate, register workers, start a client, enqueue in a transaction, stop.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/jackc/pgx/v5/pgxpool"

	"github.com/thnhdatle/foreman"
	"github.com/thnhdatle/foreman/migrate"
)

type EmailArgs struct {
	UserID int64  `json:"user_id"`
	Tmpl   string `json:"tmpl"`
}

func (EmailArgs) Kind() string { return "email" }

type EmailWorker struct{}

func (w *EmailWorker) Work(ctx context.Context, job *foreman.Job[EmailArgs]) error {
	fmt.Printf("sending %s to user %d\n", job.Args.Tmpl, job.Args.UserID)
	return nil
}

func main() {
	if err := run(context.Background()); err != nil {
		log.Fatal(err)
	}
}

func run(ctx context.Context) error {
	pool, err := pgxpool.New(ctx, "postgres://foreman:foreman@localhost:55432/foreman")
	if err != nil {
		return err
	}
	defer pool.Close()
	if err := migrate.Up(ctx, pool); err != nil {
		return err
	}
	workers := foreman.NewWorkers()
	foreman.AddWorker(workers, &EmailWorker{})
	client, err := foreman.NewClient(pool, foreman.Config{
		Queues:  map[string]foreman.QueueConfig{"default": {MaxWorkers: 50, PerKeyLimit: 5, Fairness: true}},
		Workers: workers,
	})
	if err != nil {
		return err
	}
	if err := client.Start(ctx); err != nil {
		return err
	}
	defer func() { _ = client.Stop(ctx) }()

	tx, err := pool.Begin(ctx)
	if err != nil {
		return err
	}
	defer func() { _ = tx.Rollback(ctx) }()

	if _, err := client.InsertTx(ctx, tx, EmailArgs{UserID: 42, Tmpl: "welcome"},
		&foreman.InsertOpts{ConcurrencyKey: "tenant-7"}); err != nil {
		return err
	}
	return tx.Commit(ctx)
}

Index

Examples

Constants

View Source
const (
	DefaultListLimit = 50
	MaxListLimit     = 500
)

Pagination limits of JobList.

View Source
const (
	DefaultMaxWorkers            = 10
	DefaultFetchInterval         = time.Second
	DefaultHeartbeatInterval     = 30 * time.Second
	DefaultRescueStuckJobsAfter  = time.Hour
	DefaultCompletedJobRetention = 24 * time.Hour
	DefaultCancelledJobRetention = 7 * 24 * time.Hour
	DefaultDiscardedJobRetention = 7 * 24 * time.Hour
	DefaultReindexInterval       = 24 * time.Hour
	DefaultCleanerInterval       = 30 * time.Second
	DefaultMaxArgsBytes          = 1 << 20
	DefaultSchema                = "public"
)

Defaults of Config.

View Source
const (
	DefaultQueue       = "default"
	DefaultPriority    = 2
	DefaultMaxAttempts = 25
)

Default insert values.

Variables

View Source
var (
	// ErrArgsTooLarge reports args whose JSON exceeds Config.MaxArgsBytes.
	ErrArgsTooLarge = errors.New("foreman: args too large")
	// ErrUniqueArgsNotCanonical reports a non-integral number in the
	// identity of a unique job; use strings for decimals in unique fields.
	ErrUniqueArgsNotCanonical = unique.ErrArgsNotCanonical
	// ErrInvalidConfig wraps every problem found by NewClient.
	ErrInvalidConfig = errors.New("foreman: invalid config")
	// ErrInvalidInsertOpts wraps every problem with InsertOpts or UniqueOpts.
	ErrInvalidInsertOpts = errors.New("foreman: invalid insert options")
	// ErrInvalidArgument reports a nil or malformed argument.
	ErrInvalidArgument = errors.New("foreman: invalid argument")
	// ErrNotFound reports a job id that does not exist.
	ErrNotFound = job.ErrNotFound
	// ErrInvalidTransition reports an admin operation not allowed in the
	// job's current state (for example retrying a running job).
	ErrInvalidTransition = job.ErrInvalidTransition
	// ErrUniqueConflict reports a retry that would duplicate a unique job.
	ErrUniqueConflict = job.ErrUniqueConflict
	// ErrStaleJob reports that CompleteTx found the attempt no longer owned
	// by this client (it was rescued, cancelled or discarded).
	ErrStaleJob = job.ErrStale
	// ErrNotInWorker reports a call that is only valid inside Worker.Work.
	ErrNotInWorker = errors.New("foreman: not called from inside Work")
	// ErrAlreadyStarted reports a second Start of a running client.
	ErrAlreadyStarted = errors.New("foreman: client already started")
	// ErrNotStarted reports Stop of a client that is not running.
	ErrNotStarted = errors.New("foreman: client not started")
	// ErrSchemaNotMigrated reports a database without the Foreman schema at
	// the version this module needs; run the migrations first.
	ErrSchemaNotMigrated = errors.New("foreman: schema not migrated")
	// ErrNoWorker reports a kind without a registered worker: the error of
	// attempts of such jobs (they are retried) and of JobWork.
	ErrNoWorker = job.ErrNoWorker
	// ErrClientStopping is the context.Cause of a job's context when the
	// client cancels it on shutdown (StopAndCancel or a Stop deadline);
	// operator cancels use a different cause and end the job as cancelled.
	ErrClientStopping = job.ErrClientStopping
)

Errors returned by Foreman. They are listed with their meaning in docs/guides/errors.md and are part of the public API.

Functions

func AddWorker

func AddWorker[T JobArgs](w *Workers, worker Worker[T], opts ...WorkerOption)

AddWorker registers worker for the kind of T. T must be a non-pointer type whose zero value returns the kind. Registering a kind twice is a programming error and panics.

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/thnhdatle/foreman"
)

type EmailArgs struct {
	UserID int64  `json:"user_id"`
	Tmpl   string `json:"tmpl"`
}

func (EmailArgs) Kind() string { return "email" }

func main() {
	workers := foreman.NewWorkers()
	foreman.AddWorker(workers, foreman.WorkFunc[EmailArgs](func(ctx context.Context, job *foreman.Job[EmailArgs]) error {
		return nil
	}), foreman.WithTimeout(time.Minute), foreman.WithMaxAttempts(5),
		foreman.WithRetryPolicy(foreman.ConstantBackoff{Delay: 10 * time.Second}))
	fmt.Println(workers.Kinds())
}
Output:
[email]

func Cancel

func Cancel(err error) error

Cancel returns an error that cancels the job; err is recorded.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/thnhdatle/foreman"
)

func main() {
	err := foreman.Cancel(errors.New("user deleted"))
	fmt.Println(err)
}
Output:
job cancelled: user deleted

func CompleteTx

func CompleteTx[T JobArgs](ctx context.Context, tx pgx.Tx, job *Job[T]) error

CompleteTx marks job completed inside tx, so the job's effects and its completion commit atomically. When Work then returns nil the client writes no further update; if Work returns an error after CompleteTx the normal retry path applies and the completion guard keeps the result consistent with whatever tx did. It returns ErrStaleJob if the attempt is no longer owned by this client.

Example
package main

import (
	"context"

	"github.com/thnhdatle/foreman"
)

type EmailArgs struct {
	UserID int64  `json:"user_id"`
	Tmpl   string `json:"tmpl"`
}

func (EmailArgs) Kind() string { return "email" }

func main() {
	_ = foreman.WorkFunc[EmailArgs](func(ctx context.Context, job *foreman.Job[EmailArgs]) error {
		tx, err := foreman.ClientFromContext(ctx).Pool().Begin(ctx)
		if err != nil {
			return err
		}
		defer func() { _ = tx.Rollback(ctx) }()
		// ... write the job's effects in tx ...
		if err := foreman.CompleteTx(ctx, tx, job); err != nil {
			return err
		}
		return tx.Commit(ctx) // effects and completion commit together
	})
}

func DecodeArgs

func DecodeArgs[T JobArgs](row *JobRow) (T, error)

DecodeArgs decodes the args of row into T. It fails if row is of another kind.

Example
package main

import (
	"fmt"

	"github.com/thnhdatle/foreman"
)

type EmailArgs struct {
	UserID int64  `json:"user_id"`
	Tmpl   string `json:"tmpl"`
}

func (EmailArgs) Kind() string { return "email" }

func main() {
	row := &foreman.JobRow{ID: 1, Kind: "email", Args: []byte(`{"user_id":7,"tmpl":"welcome"}`)}
	args, err := foreman.DecodeArgs[EmailArgs](row)
	fmt.Println(args.UserID, args.Tmpl, err)
}
Output:
7 welcome <nil>

func Discard

func Discard(err error) error

Discard returns an error that discards the job at once (dead letter), whatever attempts remain; err is recorded.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/thnhdatle/foreman"
)

func main() {
	err := foreman.Discard(errors.New("template does not exist"))
	fmt.Println(err)
}
Output:
job discarded: template does not exist

func Heartbeat

func Heartbeat(ctx context.Context)

Heartbeat refreshes the heartbeat of the running job now, for long jobs between the automatic heartbeats. It is a no-op outside Work.

Example
package main

import (
	"context"

	"github.com/thnhdatle/foreman"
)

type EmailArgs struct {
	UserID int64  `json:"user_id"`
	Tmpl   string `json:"tmpl"`
}

func (EmailArgs) Kind() string { return "email" }

func main() {
	_ = foreman.WorkFunc[EmailArgs](func(ctx context.Context, job *foreman.Job[EmailArgs]) error {
		for i := 0; i < 10; i++ {
			// ... one long step ...
			foreman.Heartbeat(ctx) // keeps the rescuer away between automatic heartbeats
		}
		return nil
	})
}

func Snooze

func Snooze(d time.Duration) error

Snooze returns an error that makes the job run again after d without consuming an attempt.

Example
package main

import (
	"fmt"
	"time"

	"github.com/thnhdatle/foreman"
)

func main() {
	err := foreman.Snooze(30 * time.Second)
	fmt.Println(err)
}
Output:
job snoozed for 30s

Types

type AttemptError

type AttemptError struct {
	// At is when the attempt failed (client clock).
	At time.Time `json:"at"`
	// Attempt is the 1-based attempt number.
	Attempt int `json:"attempt"`
	// Error is the error message, or "panic: <value>".
	Error string `json:"error"`
	// Trace is the stack trace of a panic.
	Trace string `json:"trace,omitempty"`
}

AttemptError records one failed attempt of a job.

type Client

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

Client inserts jobs, runs worker pools for its queues and, when elected leader, the maintenance services. It is safe for concurrent use.

func ClientFromContext

func ClientFromContext(ctx context.Context) *Client

ClientFromContext returns the client running the job, inside Work (or nil).

Example
package main

import (
	"context"

	"github.com/thnhdatle/foreman"
)

type EmailArgs struct {
	UserID int64  `json:"user_id"`
	Tmpl   string `json:"tmpl"`
}

func (EmailArgs) Kind() string { return "email" }

func main() {
	_ = foreman.WorkFunc[EmailArgs](func(ctx context.Context, job *foreman.Job[EmailArgs]) error {
		client := foreman.ClientFromContext(ctx)
		// Enqueue a follow-up job from inside Work.
		_, err := client.Insert(ctx, EmailArgs{UserID: job.Args.UserID, Tmpl: "follow-up"}, nil)
		return err
	})
}

func NewClient

func NewClient(pool *pgxpool.Pool, cfg Config) (*Client, error)

NewClient validates cfg and returns a client using pool. It starts no goroutines; call Start to run workers. A client with no queues is producer-only and never needs Start.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/jackc/pgx/v5/pgxpool"

	"github.com/thnhdatle/foreman"
)

func main() {
	var pool *pgxpool.Pool // your application's pool
	// A client without queues only inserts and administers jobs.
	_, err := foreman.NewClient(pool, foreman.Config{})
	fmt.Println(errors.Is(err, foreman.ErrInvalidArgument))
}
Output:
true

func (*Client) ID

func (c *Client) ID() string

ID returns the client id used in attempted_by and the leader lease.

func (*Client) Insert

func (c *Client) Insert(ctx context.Context, args JobArgs, opts *InsertOpts) (*InsertResult, error)

Insert inserts one job. It is committed immediately.

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/thnhdatle/foreman"
)

type EmailArgs struct {
	UserID int64  `json:"user_id"`
	Tmpl   string `json:"tmpl"`
}

func (EmailArgs) Kind() string { return "email" }

func main() {
	var client *foreman.Client
	res, err := client.Insert(context.Background(), EmailArgs{UserID: 1, Tmpl: "reset"}, &foreman.InsertOpts{
		Queue:      "mail",
		Priority:   1,
		UniqueOpts: &foreman.UniqueOpts{ByArgs: true, ByPeriod: time.Hour},
	})
	if err == nil && res.UniqueSkippedAsDuplicate {
		fmt.Println("already queued as job", res.Job.ID)
	}
}

func (*Client) InsertMany

func (c *Client) InsertMany(ctx context.Context, params []InsertParams) ([]*InsertResult, error)

InsertMany inserts a batch in one transaction; batches of 10 or more go through COPY. Results follow the order of params.

Example
package main

import (
	"context"

	"github.com/thnhdatle/foreman"
)

type EmailArgs struct {
	UserID int64  `json:"user_id"`
	Tmpl   string `json:"tmpl"`
}

func (EmailArgs) Kind() string { return "email" }

func main() {
	var client *foreman.Client
	params := make([]foreman.InsertParams, 0, 100)
	for i := int64(0); i < 100; i++ {
		params = append(params, foreman.InsertParams{Args: EmailArgs{UserID: i, Tmpl: "digest"}})
	}
	_, _ = client.InsertMany(context.Background(), params) // COPY for batches of 10 or more
}

func (*Client) InsertManyTx

func (c *Client) InsertManyTx(ctx context.Context, tx pgx.Tx, params []InsertParams) ([]*InsertResult, error)

InsertManyTx inserts a batch in tx.

Example
package main

import (
	"context"

	"github.com/jackc/pgx/v5"

	"github.com/thnhdatle/foreman"
)

type EmailArgs struct {
	UserID int64  `json:"user_id"`
	Tmpl   string `json:"tmpl"`
}

func (EmailArgs) Kind() string { return "email" }

func main() {
	var (
		client *foreman.Client
		tx     pgx.Tx
	)
	_, _ = client.InsertManyTx(context.Background(), tx, []foreman.InsertParams{
		{Args: EmailArgs{UserID: 1}}, {Args: EmailArgs{UserID: 2}},
	})
}

func (*Client) InsertTx

func (c *Client) InsertTx(ctx context.Context, tx pgx.Tx, args JobArgs, opts *InsertOpts) (*InsertResult, error)

InsertTx inserts one job in tx: the job exists only if tx commits, and workers are notified on commit.

Example
package main

import (
	"context"

	"github.com/jackc/pgx/v5"

	"github.com/thnhdatle/foreman"
)

type EmailArgs struct {
	UserID int64  `json:"user_id"`
	Tmpl   string `json:"tmpl"`
}

func (EmailArgs) Kind() string { return "email" }

func main() {
	var (
		client *foreman.Client
		tx     pgx.Tx
	)
	// The job exists only if tx commits.
	_, _ = client.InsertTx(context.Background(), tx, EmailArgs{UserID: 2, Tmpl: "welcome"}, nil)
}

func (*Client) IsLeader

func (c *Client) IsLeader() bool

IsLeader reports whether this client currently runs the leader services.

func (*Client) JobCancel

func (c *Client) JobCancel(ctx context.Context, id int64) (*JobRow, error)

JobCancel cancels a job. Available, scheduled and retryable jobs are cancelled at once. For a running job a cancel is requested: the owning client cancels the job's context and the job ends cancelled when Work returns, whatever it returns. Cancelling a cancelled job returns it unchanged; completed and discarded jobs give ErrInvalidTransition.

Example
package main

import (
	"context"
	"fmt"

	"github.com/thnhdatle/foreman"
)

func main() {
	var client *foreman.Client
	job, err := client.JobCancel(context.Background(), 123)
	if err == nil && job.State == foreman.StateRunning {
		fmt.Println("cancel requested; the job ends as cancelled when Work returns")
	}
}

func (*Client) JobDeleteMany

func (c *Client) JobDeleteMany(ctx context.Context, f *JobFilter) (int, error)

JobDeleteMany deletes every job matching f except running ones and returns how many.

Example
package main

import (
	"context"
	"time"

	"github.com/thnhdatle/foreman"
)

func main() {
	var client *foreman.Client
	_, _ = client.JobDeleteMany(context.Background(), &foreman.JobFilter{
		States: []foreman.State{foreman.StateCompleted}, CreatedBefore: time.Now().Add(-30 * 24 * time.Hour),
	})
}

func (*Client) JobDiscard

func (c *Client) JobDiscard(ctx context.Context, id int64) (*JobRow, error)

JobDiscard moves a job in any non-final state to discarded (dead letter). A running job's context is cancelled and its result ignored. Discarding a discarded job returns it unchanged; completed and cancelled jobs give ErrInvalidTransition.

Example
package main

import (
	"context"

	"github.com/thnhdatle/foreman"
)

func main() {
	var client *foreman.Client
	_, _ = client.JobDiscard(context.Background(), 123)
}

func (*Client) JobDiscardMany

func (c *Client) JobDiscardMany(ctx context.Context, f *JobFilter) (int, error)

JobDiscardMany discards every non-final job matching f and returns how many.

Example
package main

import (
	"context"

	"github.com/thnhdatle/foreman"
)

func main() {
	var client *foreman.Client
	_, _ = client.JobDiscardMany(context.Background(), &foreman.JobFilter{Queues: []string{"legacy"}})
}

func (*Client) JobGet

func (c *Client) JobGet(ctx context.Context, id int64) (*JobRow, error)

JobGet returns one job, or ErrNotFound.

Example
package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/thnhdatle/foreman"
)

func main() {
	var client *foreman.Client
	job, err := client.JobGet(context.Background(), 123)
	if errors.Is(err, foreman.ErrNotFound) {
		return
	}
	fmt.Println(job.State, len(job.Errors))
}

func (*Client) JobList

func (c *Client) JobList(ctx context.Context, p *JobListParams) (*JobListResult, error)

JobList lists jobs newest first with cursor pagination.

Example
package main

import (
	"context"
	"fmt"

	"github.com/thnhdatle/foreman"
)

func main() {
	var client *foreman.Client
	params := &foreman.JobListParams{States: []foreman.State{foreman.StateDiscarded}, Limit: 100}
	for {
		page, err := client.JobList(context.Background(), params)
		if err != nil {
			return
		}
		for _, j := range page.Jobs {
			fmt.Println(j.ID, j.Kind)
		}
		if page.NextCursor == "" {
			return
		}
		params.Cursor = page.NextCursor
	}
}

func (*Client) JobRetry

func (c *Client) JobRetry(ctx context.Context, id int64) (*JobRow, error)

JobRetry moves a discarded, cancelled or completed job back to available with its attempt reset to 0 and a note in its metadata. A job that is already available is returned unchanged; other states give ErrInvalidTransition.

Example
package main

import (
	"context"

	"github.com/thnhdatle/foreman"
)

func main() {
	var client *foreman.Client
	// Move a dead-lettered job back to available with attempt 0.
	_, _ = client.JobRetry(context.Background(), 123)
}

func (*Client) JobRetryMany

func (c *Client) JobRetryMany(ctx context.Context, f *JobFilter) (int, error)

JobRetryMany retries every final job matching f and returns how many.

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/thnhdatle/foreman"
)

func main() {
	var client *foreman.Client
	n, _ := client.JobRetryMany(context.Background(), &foreman.JobFilter{
		Kinds: []string{"email"}, States: []foreman.State{foreman.StateDiscarded},
		CreatedAfter: time.Now().Add(-24 * time.Hour),
	})
	fmt.Println("retried", n)
}

func (*Client) JobWork

func (c *Client) JobWork(ctx context.Context, id int64) (*JobRow, error)

JobWork runs one available job synchronously on this client (for tests and operator tooling): it marks the job running for this client, runs it through the middleware, executor and result mapping, writes the result and returns the updated row. The kind must have a worker on this client.

Example
package main

import (
	"context"
	"fmt"

	"github.com/thnhdatle/foreman"
)

type EmailArgs struct {
	UserID int64  `json:"user_id"`
	Tmpl   string `json:"tmpl"`
}

func (EmailArgs) Kind() string { return "email" }

func main() {
	var client *foreman.Client
	res, _ := client.Insert(context.Background(), EmailArgs{UserID: 3}, nil)
	job, _ := client.JobWork(context.Background(), res.Job.ID) // runs it now, synchronously
	fmt.Println(job.State)
}

func (*Client) LeaderGet

func (c *Client) LeaderGet(ctx context.Context) (*LeaderInfo, error)

LeaderGet returns the current lease, or ErrNotFound when no client holds one.

Example
package main

import (
	"context"
	"fmt"

	"github.com/thnhdatle/foreman"
)

func main() {
	var client *foreman.Client
	if l, err := client.LeaderGet(context.Background()); err == nil {
		fmt.Println(l.LeaderID, l.ExpiresAt)
	}
}

func (*Client) PeriodicList

func (c *Client) PeriodicList(ctx context.Context) ([]*PeriodicInfo, error)

PeriodicList lists periodic jobs that have enqueued at least one tick.

Example
package main

import (
	"context"
	"fmt"

	"github.com/thnhdatle/foreman"
)

func main() {
	var client *foreman.Client
	ps, _ := client.PeriodicList(context.Background())
	for _, p := range ps {
		fmt.Println(p.Name, p.LastTick)
	}
}

func (*Client) Pool

func (c *Client) Pool() *pgxpool.Pool

Pool returns the pool the client uses.

func (*Client) QueueList

func (c *Client) QueueList(ctx context.Context) ([]*QueueInfo, error)

QueueList lists the queues known to the database.

Example
package main

import (
	"context"
	"fmt"

	"github.com/thnhdatle/foreman"
)

func main() {
	var client *foreman.Client
	queues, _ := client.QueueList(context.Background())
	for _, q := range queues {
		fmt.Println(q.Name, q.Paused, q.Available, q.Running)
	}
}

func (*Client) QueuePause

func (c *Client) QueuePause(ctx context.Context, name string) error

QueuePause stops every client from fetching jobs of the queue; running jobs finish. It propagates by NOTIFY and by polling.

Example
package main

import (
	"context"

	"github.com/thnhdatle/foreman"
)

func main() {
	var client *foreman.Client
	ctx := context.Background()
	_ = client.QueuePause(ctx, "mail") // running jobs finish; nothing new is fetched
	_ = client.QueueResume(ctx, "mail")
}

func (*Client) QueueResume

func (c *Client) QueueResume(ctx context.Context, name string) error

QueueResume lets clients fetch jobs of the queue again.

Example
package main

import (
	"context"

	"github.com/thnhdatle/foreman"
)

func main() {
	var client *foreman.Client
	_ = client.QueueResume(context.Background(), "mail")
}

func (*Client) Schema

func (c *Client) Schema() string

Schema returns the schema holding the Foreman tables.

func (*Client) Start

func (c *Client) Start(ctx context.Context) error

Start runs the worker pools of the configured queues, the heartbeats, the LISTEN connection and leader election. It returns once everything is running. The schema must be migrated (package migrate). Cancelling ctx later has the effect of StopAndCancel with no grace period.

Example
package main

import (
	"context"
	"log"
	"time"

	"github.com/thnhdatle/foreman"
)

func main() {
	var client *foreman.Client
	ctx := context.Background()
	if err := client.Start(ctx); err != nil {
		log.Fatal(err)
	}
	// On shutdown: finish running jobs for up to 30s, then cancel them.
	stopCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
	defer cancel()
	_ = client.Stop(stopCtx)
}

func (*Client) Stop

func (c *Client) Stop(ctx context.Context) error

Stop shuts down gracefully: it stops fetching, waits for running jobs until ctx is done, then cancels the rest, flushes completions and resigns leadership. It returns ctx.Err() if jobs had to be cancelled.

func (*Client) StopAndCancel

func (c *Client) StopAndCancel(ctx context.Context) error

StopAndCancel cancels the contexts of running jobs at once, waits for them (bounded by ctx), flushes completions and resigns leadership.

Example
package main

import (
	"context"
	"time"

	"github.com/thnhdatle/foreman"
)

func main() {
	var client *foreman.Client
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	_ = client.StopAndCancel(ctx) // running jobs see their context cancelled
}

type Clock

type Clock = clock.Clock

Clock is the time source of a client. Every time Foreman writes or compares in SQL comes from it. foremantest provides a fake.

type Config

type Config struct {
	// Queues served by this client. With no queues the client is
	// producer-only: it inserts and administers but fetches nothing and
	// takes no part in leader election.
	Queues map[string]QueueConfig
	// Workers registered for the kinds this client runs.
	Workers *Workers
	// PeriodicJobs are enqueued by the leader on their schedule.
	PeriodicJobs []*PeriodicJob
	// Logger defaults to slog.Default().
	Logger *slog.Logger
	// Clock defaults to the wall clock.
	Clock Clock
	// ID identifies the client in attempted_by and the leader lease;
	// default hostname-pid-random.
	ID string
	// Schema holding the Foreman tables; default "public".
	Schema string
	// JobTimeout is the default timeout of Work; 0 = none.
	JobTimeout time.Duration
	// RescueStuckJobsAfter returns running jobs without a heartbeat for this
	// long to retryable; default 1h, at least 2 x HeartbeatInterval.
	RescueStuckJobsAfter time.Duration
	// HeartbeatInterval between heartbeats of running jobs; default 30s.
	HeartbeatInterval time.Duration
	// RetryPolicy defaults to ExponentialBackoff{} (1s base, 24h cap, full jitter).
	RetryPolicy RetryPolicy
	// CompletedJobRetention defaults to 24h; negative keeps completed jobs forever.
	CompletedJobRetention time.Duration
	// CancelledJobRetention defaults to 7 days; negative keeps them forever.
	CancelledJobRetention time.Duration
	// DiscardedJobRetention defaults to 7 days; negative keeps them forever.
	DiscardedJobRetention time.Duration
	// ReindexInterval rebuilds the queue indexes concurrently; default 24h,
	// negative disables it.
	ReindexInterval time.Duration
	// CleanerInterval between runs of the cleaner; default 30s.
	CleanerInterval time.Duration
	// ErrorHandler may override the outcome of failed attempts.
	ErrorHandler ErrorHandler
	// Middleware wraps inserts and work, outermost first.
	Middleware []Middleware
	// PollOnly disables LISTEN/NOTIFY (for PgBouncer transaction pooling):
	// wake-ups, cancels and pauses then propagate by polling every FetchInterval.
	PollOnly bool
	// MaxArgsBytes bounds the JSON size of args; default 1 MiB.
	MaxArgsBytes int
	// TracerProvider enables OpenTelemetry spans "foreman.work <kind>".
	TracerProvider trace.TracerProvider
	// Registerer receives the Prometheus metrics; nil keeps them private.
	Registerer prometheus.Registerer
}

Config configures a client. The zero value of every field selects its default; durations that can be switched off use a negative value for "off" (Go zero values cannot mean both "default" and "off").

type ConstantBackoff

type ConstantBackoff struct {
	Delay time.Duration
}

ConstantBackoff always waits Delay.

func (ConstantBackoff) NextRetry

func (c ConstantBackoff) NextRetry(_ JobRow, now time.Time) time.Time

NextRetry implements RetryPolicy.

type ErrorHandler

type ErrorHandler interface {
	HandleError(ctx context.Context, job *JobRow, err error) *ErrorHandlerResult
	HandlePanic(ctx context.Context, job *JobRow, panicVal any, trace string) *ErrorHandlerResult
}

ErrorHandler is notified of failed attempts and may override the outcome. Returning nil keeps the default (retry with backoff, or discard when attempts are exhausted).

type ErrorHandlerResult

type ErrorHandlerResult struct {
	SetCancelled bool
	SetDiscarded bool
	SnoozeFor    time.Duration
}

ErrorHandlerResult overrides the outcome of a failed attempt. The first field set wins, in field order.

type ExponentialBackoff

type ExponentialBackoff struct {
	Base time.Duration
	Cap  time.Duration
}

ExponentialBackoff waits min(Cap, Base*2^(attempt-1)) with full jitter. The zero value uses Base 1s and Cap 24h (the default policy).

Example
package main

import (
	"fmt"
	"time"

	"github.com/thnhdatle/foreman"
)

func main() {
	p := foreman.ExponentialBackoff{Base: time.Second, Cap: time.Hour}
	now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
	next := p.NextRetry(foreman.JobRow{Attempt: 3}, now)
	fmt.Println(next.Sub(now) < 4*time.Second)
}
Output:
true

func (ExponentialBackoff) NextRetry

func (e ExponentialBackoff) NextRetry(job JobRow, now time.Time) time.Time

NextRetry implements RetryPolicy.

type InsertOpts

type InsertOpts struct {
	// Queue defaults to "default".
	Queue string
	// Priority is 1 (highest) to 4 (lowest); default 2.
	Priority int
	// ScheduledAt in the future inserts the job as scheduled.
	ScheduledAt time.Time
	// MaxAttempts defaults to 25.
	MaxAttempts int
	Tags        []string
	// Metadata must be a JSON object.
	Metadata json.RawMessage
	// ConcurrencyKey groups jobs for per-key limits and fairness (for example a tenant id).
	ConcurrencyKey string
	// UniqueOpts makes the job unique; nil means not unique.
	UniqueOpts *UniqueOpts
	// Timeout overrides the kind and client job timeout.
	Timeout time.Duration
}

InsertOpts are per-job options. Zero fields fall back to the args type's InsertOpts(), then to the worker options, then to the defaults.

type InsertParams

type InsertParams struct {
	Args       JobArgs
	InsertOpts *InsertOpts
}

InsertParams is one job of an InsertMany call.

type InsertResult

type InsertResult struct {
	// Job is the inserted job, or the existing job for a skipped duplicate.
	Job *JobRow
	// UniqueSkippedAsDuplicate is true when a unique job already existed.
	UniqueSkippedAsDuplicate bool
}

InsertResult is the outcome of inserting one job.

type Job

type Job[T JobArgs] struct {
	ID          int64
	Args        T
	Attempt     int
	MaxAttempts int
	Queue       string
	Priority    int
	Tags        []string
	Metadata    json.RawMessage
	CreatedAt   time.Time
	ScheduledAt time.Time
	Errors      []AttemptError
}

Job is a job with decoded, typed args, as passed to Worker.Work.

type JobArgs

type JobArgs interface {
	Kind() string
}

JobArgs is the payload of a job. Kind identifies the job type; exactly one worker handles each kind. Args are stored as JSON.

type JobArgsWithInsertOpts

type JobArgsWithInsertOpts interface {
	JobArgs
	InsertOpts() InsertOpts
}

JobArgsWithInsertOpts is implemented by args types that provide per-kind insert defaults; explicit InsertOpts fields take precedence.

type JobFilter

type JobFilter struct {
	Kinds  []string
	Queues []string
	States []State
	// CreatedAfter and CreatedBefore bound created_at (inclusive, exclusive).
	CreatedAfter  time.Time
	CreatedBefore time.Time
}

JobFilter selects jobs for bulk operations; empty fields match every job.

type JobListParams

type JobListParams struct {
	States []State
	Kinds  []string
	Queues []string
	// Limit defaults to 50, at most 500.
	Limit int
	// Cursor continues from the NextCursor of a previous page.
	Cursor string
}

JobListParams filters JobList; empty fields match every job.

type JobListResult

type JobListResult struct {
	Jobs []*JobRow
	// NextCursor is empty on the last page.
	NextCursor string
}

JobListResult is one page of jobs, newest first.

type JobRow

type JobRow struct {
	ID                int64
	Kind              string
	Queue             string
	Args              json.RawMessage
	State             State
	Priority          int
	Attempt           int
	MaxAttempts       int
	ScheduledAt       time.Time
	CreatedAt         time.Time
	AttemptedAt       *time.Time
	FinalizedAt       *time.Time
	HeartbeatAt       *time.Time
	CancelRequestedAt *time.Time
	AttemptedBy       []string
	Errors            []AttemptError
	Tags              []string
	Metadata          json.RawMessage
	// UniqueKey is the SHA-256 of the canonical unique identity; nil when not unique.
	UniqueKey []byte
	// UniqueStates are the states in which the unique key is enforced.
	UniqueStates []State
	// ConcurrencyKey is empty when the job has none.
	ConcurrencyKey string
	// Timeout is the per-job timeout; zero uses the kind or client default.
	Timeout time.Duration
}

JobRow is a job as stored in the database, with undecoded args.

type LeaderInfo

type LeaderInfo struct {
	LeaderID  string
	ElectedAt time.Time
	ExpiresAt time.Time
}

LeaderInfo describes the current leader lease.

type Middleware

type Middleware interface {
	// InsertMany wraps every insert (single inserts are batches of one).
	InsertMany(ctx context.Context, params []InsertParams, next func(ctx context.Context) ([]*InsertResult, error)) (
		[]*InsertResult, error)
	// Work wraps each attempt of a job.
	Work(ctx context.Context, job *JobRow, next func(ctx context.Context) error) error
}

Middleware wraps inserts and work, for example for tracing, metrics, logging or adding metadata. Middleware runs in Config.Middleware order: the first one is the outermost.

type MiddlewareDefaults

type MiddlewareDefaults struct{}

MiddlewareDefaults implements Middleware as a pass-through; embed it to implement only one of the hooks.

func (MiddlewareDefaults) InsertMany

func (MiddlewareDefaults) InsertMany(
	ctx context.Context, _ []InsertParams, next func(ctx context.Context) ([]*InsertResult, error),
) ([]*InsertResult, error)

InsertMany calls next.

func (MiddlewareDefaults) Work

func (MiddlewareDefaults) Work(ctx context.Context, _ *JobRow, next func(ctx context.Context) error) error

Work calls next.

type PeriodicInfo

type PeriodicInfo struct {
	Name     string
	LastTick time.Time
	Ticks    int64
}

PeriodicInfo summarises the ticks enqueued for one periodic job.

type PeriodicJob

type PeriodicJob struct {
	// Name identifies the job in the tick table; it must be unique and stable.
	Name string
	// Schedule is Cron(...) or Every(...).
	Schedule Schedule
	// Args returns the job to insert for each tick.
	Args func() (JobArgs, *InsertOpts)
	// RunOnStart also enqueues the job when a client becomes leader.
	RunOnStart bool
	// CatchUp is how far back missed ticks are enqueued after a leader gap
	// (oldest first); older ticks are skipped and counted.
	CatchUp time.Duration
	// TimeZone evaluates cron expressions; default UTC.
	TimeZone *time.Location
}

PeriodicJob is a job enqueued on a schedule by the leader, exactly once per tick across the cluster.

type QueueConfig

type QueueConfig struct {
	// MaxWorkers is the number of jobs run at once; default 10.
	MaxWorkers int
	// FetchInterval is the polling fallback; default 1s.
	FetchInterval time.Duration
	// PerKeyLimit caps running jobs per concurrency key across the cluster; 0 = no limit.
	PerKeyLimit int
	// Fairness alternates between concurrency keys when jobs are backlogged.
	Fairness bool
}

QueueConfig configures one queue served by a client.

type QueueInfo

type QueueInfo struct {
	Name       string
	Paused     bool
	PausedAt   *time.Time
	LastSeenAt *time.Time
	Available  int64
	Scheduled  int64
	Running    int64
	Retryable  int64
}

QueueInfo describes a queue: its pause state, when a client last reported serving it, and its pending jobs per state.

type RetryPolicy

type RetryPolicy interface {
	NextRetry(job JobRow, now time.Time) time.Time
}

RetryPolicy decides when a failed job runs again. job.Attempt is the attempt that just failed (1-based).

type RetryPolicyFunc

type RetryPolicyFunc func(job JobRow, now time.Time) time.Time

RetryPolicyFunc adapts a function to RetryPolicy.

func (RetryPolicyFunc) NextRetry

func (f RetryPolicyFunc) NextRetry(job JobRow, now time.Time) time.Time

NextRetry calls f.

type Schedule

type Schedule interface {
	// Next returns the first tick strictly after t.
	Next(t time.Time) time.Time
}

Schedule computes the ticks of a periodic job. Ticks must be deterministic: every client computes the same instants, which is what lets the tick table enforce exactly-once enqueueing across leaders.

func Cron

func Cron(expr string) (Schedule, error)

Cron parses a cron expression: 5 fields, 6 fields with leading seconds, or a descriptor such as @hourly or @daily. It is evaluated in the PeriodicJob's TimeZone (UTC by default). Wall times skipped by a DST spring-forward do not fire that day; wall times repeated by a fall-back fire once per occurrence. Use UTC to avoid both.

Example
package main

import (
	"fmt"
	"log"
	"time"

	"github.com/thnhdatle/foreman"
)

func main() {
	s, err := foreman.Cron("0 9 * * MON")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(s.Next(time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)))
}
Output:
2026-01-05 09:00:00 +0000 UTC

func Every

func Every(d time.Duration) Schedule

Every returns a schedule ticking every d, aligned to multiples of d since the Unix epoch so that all clients agree on the ticks. d must be positive (checked by NewClient).

Example
package main

import (
	"fmt"
	"time"

	"github.com/thnhdatle/foreman"
)

func main() {
	s := foreman.Every(15 * time.Minute)
	fmt.Println(s.Next(time.Date(2026, 1, 1, 10, 7, 0, 0, time.UTC)))
}
Output:
2026-01-01 10:15:00 +0000 UTC

func MustCron

func MustCron(expr string) Schedule

MustCron is Cron that panics on an invalid expression, for package-level declarations of periodic jobs.

Example
package main

import (
	"fmt"
	"time"

	"github.com/thnhdatle/foreman"
)

type EmailArgs struct {
	UserID int64  `json:"user_id"`
	Tmpl   string `json:"tmpl"`
}

func (EmailArgs) Kind() string { return "email" }

func main() {
	job := &foreman.PeriodicJob{
		Name:     "daily-report",
		Schedule: foreman.MustCron("@daily"),
		Args:     func() (foreman.JobArgs, *foreman.InsertOpts) { return EmailArgs{Tmpl: "report"}, nil },
		CatchUp:  time.Hour,
	}
	fmt.Println(job.Name, job.Schedule != nil, job.Args != nil, job.CatchUp)
}
Output:
daily-report true true 1h0m0s

type State

type State string

State is the lifecycle state of a job.

const (
	StateAvailable State = "available"
	StateScheduled State = "scheduled"
	StateRunning   State = "running"
	StateRetryable State = "retryable"
	StateCompleted State = "completed"
	StateCancelled State = "cancelled"
	StateDiscarded State = "discarded"
)

Job states.

type Ticker

type Ticker = clock.Ticker

Ticker is a ticker created by a Clock.

type UniqueOpts

type UniqueOpts struct {
	// ByArgs includes all args; mutually exclusive with ByArgFields.
	ByArgs bool
	// ByArgFields includes only these top-level args fields.
	ByArgFields []string
	// ByPeriod includes the start of the current period (whole seconds).
	ByPeriod time.Duration
	// ByQueue includes the queue.
	ByQueue bool
	// ByState defaults to available, scheduled, running, retryable and
	// completed; it must include the first four.
	ByState []State
}

UniqueOpts selects the identity of a unique job: its kind plus, optionally, its args (all, or selected top-level fields), its queue and a time period. While a job with the same identity exists in one of ByState, inserting another returns the existing job with UniqueSkippedAsDuplicate set.

type WorkFunc

type WorkFunc[T JobArgs] func(ctx context.Context, job *Job[T]) error

WorkFunc adapts a function to the Worker interface.

func (WorkFunc[T]) Work

func (f WorkFunc[T]) Work(ctx context.Context, job *Job[T]) error

Work calls f.

type Worker

type Worker[T JobArgs] interface {
	Work(ctx context.Context, job *Job[T]) error
}

Worker handles jobs of one kind. Work is called with the job context: it is cancelled on timeout, on JobCancel, and on StopAndCancel. Return nil on success, an error to retry with backoff, or the result of Snooze, Discard or Cancel. Execution is at least once (a job whose worker dies is rescued and runs again): make Work idempotent.

type WorkerOption

type WorkerOption func(*workerEntry)

WorkerOption configures the jobs of one kind.

func WithMaxAttempts

func WithMaxAttempts(n int) WorkerOption

WithMaxAttempts sets the default max attempts of jobs of the kind inserted by clients that registered this worker.

func WithRetryPolicy

func WithRetryPolicy(p RetryPolicy) WorkerOption

WithRetryPolicy sets the retry policy of the kind (default: client policy).

func WithTimeout

func WithTimeout(d time.Duration) WorkerOption

WithTimeout sets the default timeout of the kind (job InsertOpts.Timeout wins).

type Workers

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

Workers is the registry of workers by kind.

func NewWorkers

func NewWorkers() *Workers

NewWorkers returns an empty registry.

Example
package main

import (
	"context"
	"fmt"

	"github.com/thnhdatle/foreman"
)

type EmailArgs struct {
	UserID int64  `json:"user_id"`
	Tmpl   string `json:"tmpl"`
}

func (EmailArgs) Kind() string { return "email" }

type EmailWorker struct{}

func (w *EmailWorker) Work(ctx context.Context, job *foreman.Job[EmailArgs]) error {
	fmt.Printf("sending %s to user %d\n", job.Args.Tmpl, job.Args.UserID)
	return nil
}

func main() {
	workers := foreman.NewWorkers()
	foreman.AddWorker(workers, &EmailWorker{})
	fmt.Println(len(workers.Kinds()))
}
Output:
1

func (*Workers) Kinds

func (w *Workers) Kinds() []string

Kinds returns the registered kinds, sorted.

Directories

Path Synopsis
acceptance
cmd/runner command
Command runner runs the acceptance suite behind `make acceptance`: it builds the project from scratch, brings up the compose stack, runs every acceptance criterion with no test cache, and writes acceptance/report.md.
Command runner runs the acceptance suite behind `make acceptance`: it builds the project from scratch, brings up the compose stack, runs every acceptance criterion with no test cache, and writes acceptance/report.md.
cmd/worker command
Command worker is a Foreman client process used by the multi-process acceptance criteria (kill -9, SIGSTOP, concurrent unique inserts).
Command worker is a Foreman client process used by the multi-process acceptance criteria (kill -9, SIGSTOP, concurrent unique inserts).
internal/accjobs
Package accjobs holds the job types and workers shared by the acceptance tests and the acceptance worker process.
Package accjobs holds the job types and workers shared by the acceptance tests and the acceptance worker process.
bench
cmd/explain command
Command explain loads 1M and 10M jobs, records EXPLAIN (ANALYZE, BUFFERS) of the fetch queries and times fetch rounds, and prints the results as Markdown.
Command explain loads 1M and 10M jobs, records EXPLAIN (ANALYZE, BUFFERS) of the fetch queries and times fetch rounds, and prints the results as Markdown.
cmd/results command
Command results runs the performance criteria several times through the acceptance tests and writes bench/RESULTS.md with the median and min-max of each measurement.
Command results runs the performance criteria several times through the acceptance tests and writes bench/RESULTS.md with the median and min-max of each measurement.
cmd
foreman command
Command foreman is the Foreman admin CLI.
Command foreman is the Foreman admin CLI.
examples
basic command
Command basic registers a worker, enqueues a job in a transaction together with a business row, and waits for the job to complete.
Command basic registers a worker, enqueues a job in a transaction together with a business row, and waits for the job to complete.
cancel-long-job command
Command cancel-long-job cancels a running job: its context is cancelled and it ends as cancelled whatever Work returns.
Command cancel-long-job cancels a running job: its context is cancelled and it ends as cancelled whatever Work returns.
insert-from-python command
Command insert-from-python runs a Go worker for jobs enqueued by a Python script through the SQL contract foreman_insert_job (CONTRACTS C5).
Command insert-from-python runs a Go worker for jobs enqueued by a Python script through the SQL contract foreman_insert_job (CONTRACTS C5).
internal/exampledb
Package exampledb connects the examples to Postgres and gives each its own freshly migrated schema, so examples can run repeatedly and in any order.
Package exampledb connects the examples to Postgres and gives each its own freshly migrated schema, so examples can run repeatedly and in any order.
multi-tenant-fairness command
Command multi-tenant-fairness shows a small tenant served promptly despite a large tenant's backlog, with a per-tenant concurrency limit.
Command multi-tenant-fairness shows a small tenant served promptly despite a large tenant's backlog, with a per-tenant concurrency limit.
otel command
Command otel traces job work with OpenTelemetry.
Command otel traces job work with OpenTelemetry.
periodic command
Command periodic enqueues a job every second through the leader and stops after three ticks.
Command periodic enqueues a job every second through the leader and stops after three ticks.
transactional-enqueue command
Command transactional-enqueue shows that a job inserted with InsertTx exists only if its transaction commits.
Command transactional-enqueue shows that a job inserted with InsertTx exists only if its transaction commits.
unique command
Command unique inserts the same unique job twice; the second insert returns the first job instead of creating a duplicate.
Command unique inserts the same unique job twice; the second insert returns the first job instead of creating a duplicate.
Package foremanhttp provides an embeddable admin JSON API for a Foreman client.
Package foremanhttp provides an embeddable admin JSON API for a Foreman client.
Package foremantest provides helpers for testing code that uses Foreman: asserting that jobs were inserted, running a worker synchronously through the real executor, and a fake clock.
Package foremantest provides helpers for testing code that uses Foreman: asserting that jobs were inserted, running a worker synchronously through the real executor, and a fake clock.
internal
adapter/pgstore
Package pgstore holds every SQL statement of Foreman (pgx v5): inserts (multi-row and COPY), the fetch queries with SKIP LOCKED, fairness and per-key limits, batched completions and heartbeats under the completion guard, leases, maintenance, admin operations and the LISTEN connection.
Package pgstore holds every SQL statement of Foreman (pgx v5): inserts (multi-row and COPY), the fetch queries with SKIP LOCKED, fairness and per-key limits, batched completions and heartbeats under the completion guard, leases, maintenance, admin operations and the LISTEN connection.
app/completer
Package completer batches job state updates and heartbeats.
Package completer batches job state updates and heartbeats.
app/elector
Package elector elects one leader per cluster with a lease row whose times come from the client clock.
Package elector elects one leader per cluster with a lease row whose times come from the client clock.
app/executor
Package executor runs one attempt of a job: it applies the job, kind or client timeout, recovers panics with their stack, consults the error handler, honours cancel requests, and maps the result to a completion.
Package executor runs one attempt of a job: it applies the job, kind or client timeout, recovers panics with their stack, consults the error handler, honours cancel requests, and maps the result to a completion.
app/maintenance
Package maintenance holds the leader-only services (scheduler, rescuer, cleaner, reindexer, periodic enqueuer, queue-depth sampler) and the PollOnly cancel poller.
Package maintenance holds the leader-only services (scheduler, rescuer, cleaner, reindexer, periodic enqueuer, queue-depth sampler) and the PollOnly cancel poller.
app/notifier
Package notifier multiplexes a single Postgres LISTEN connection to the producers, the cancel handler and the elector, and reconnects with jittered backoff when the connection is lost.
Package notifier multiplexes a single Postgres LISTEN connection to the producers, the cancel handler and the elector, and reconnects with jittered backoff when the connection is lost.
app/producer
Package producer runs the fetch loop of one queue: it wakes on NOTIFY, on finished jobs and on a poll interval, fetches up to its free capacity (honouring pause, per-key limits and fairness) and runs each job on its own goroutine with a cancellable job context.
Package producer runs the fetch loop of one queue: it wakes on NOTIFY, on finished jobs and on a poll interval, fetches up to its free capacity (honouring pause, per-key limits and fairness) and runs each job on its own goroutine with a cancellable job context.
cli
Package cli implements the foreman admin CLI: migrate, jobs, queues, leader, periodic, stats, config and version commands.
Package cli implements the foreman admin CLI: migrate, jobs, queues, leader, periodic, stats, config and version commands.
config
Package config loads and validates the configuration of the foreman CLI: defaults, a YAML file, FOREMAN_* environment variables and flags, in increasing precedence.
Package config loads and validates the configuration of the foreman CLI: defaults, a YAML file, FOREMAN_* environment variables and flags, in increasing precedence.
domain/backoff
Package backoff provides retry delay policies: exponential with full jitter (the default, base 1s, cap 24h), constant, and custom functions.
Package backoff provides retry delay policies: exponential with full jitter (the default, base 1s, cap 24h), constant, and custom functions.
domain/fairness
Package fairness decides how a fetch of k jobs is split between concurrency keys: by fetch order with per-key headroom, or fairly by least recently served key within each priority level.
Package fairness decides how a fetch of k jobs is split between concurrency keys: by fetch order with per-key headroom, or fairly by least recently served key within each priority level.
domain/job
Package job defines the job row, its state machine and the mapping from the result of Work to the state update written to the database.
Package job defines the job row, its state machine and the mapping from the result of Work to the state update written to the database.
domain/schedule
Package schedule wraps the cron parser, provides epoch-aligned Every schedules, and computes which periodic ticks are due after a leader gap (catch-up window) and which are skipped.
Package schedule wraps the cron parser, provides epoch-aligned Every schedules, and computes which periodic ticks are due after a leader gap (catch-up window) and which are skipped.
domain/unique
Package unique validates unique-job options, selects the identifying argument fields and computes the period bucket.
Package unique validates unique-job options, selects the identifying argument fields and computes the period bucket.
platform/clock
Package clock provides the injectable time source used by app and adapter code: Real for production and Fake for tests and simulations driven by a manually advanced clock.
Package clock provides the injectable time source used by app and adapter code: Real for production and Fake for tests and simulations driven by a manually advanced clock.
platform/metrics
Package metrics defines the Prometheus collectors of a Foreman client, the shared histogram buckets, and label capping for values derived from user data.
Package metrics defines the Prometheus collectors of a Foreman client, the shared histogram buckets, and label capping for values derived from user data.
platform/tracing
Package tracing creates OpenTelemetry spans for job work and inserts: "foreman.work <kind>" with job id, kind, queue and attempt attributes.
Package tracing creates OpenTelemetry spans for job work and inserts: "foreman.work <kind>" with job id, kind, queue and attempt attributes.
testutil
Package testutil holds helpers shared by tests only: polling assertions, in-memory fakes of domain ports and Postgres test containers.
Package testutil holds helpers shared by tests only: polling assertions, in-memory fakes of domain ports and Postgres test containers.
testutil/pgtest
Package pgtest provides Postgres for integration tests: a Testcontainers server per test package (or FOREMAN_TEST_DATABASE_URL) and a freshly migrated schema per test.
Package pgtest provides Postgres for integration tests: a Testcontainers server per test package (or FOREMAN_TEST_DATABASE_URL) and a freshly migrated schema per test.
Package migrate installs and removes the Foreman schema with embedded, transactional SQL migrations.
Package migrate installs and removes the Foreman schema with embedded, transactional SQL migrations.

Jump to

Keyboard shortcuts

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