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)
}
Output:
Index ¶
- Constants
- Variables
- func AddWorker[T JobArgs](w *Workers, worker Worker[T], opts ...WorkerOption)
- func Cancel(err error) error
- func CompleteTx[T JobArgs](ctx context.Context, tx pgx.Tx, job *Job[T]) error
- func DecodeArgs[T JobArgs](row *JobRow) (T, error)
- func Discard(err error) error
- func Heartbeat(ctx context.Context)
- func Snooze(d time.Duration) error
- type AttemptError
- type Client
- func (c *Client) ID() string
- func (c *Client) Insert(ctx context.Context, args JobArgs, opts *InsertOpts) (*InsertResult, error)
- func (c *Client) InsertMany(ctx context.Context, params []InsertParams) ([]*InsertResult, error)
- func (c *Client) InsertManyTx(ctx context.Context, tx pgx.Tx, params []InsertParams) ([]*InsertResult, error)
- func (c *Client) InsertTx(ctx context.Context, tx pgx.Tx, args JobArgs, opts *InsertOpts) (*InsertResult, error)
- func (c *Client) IsLeader() bool
- func (c *Client) JobCancel(ctx context.Context, id int64) (*JobRow, error)
- func (c *Client) JobDeleteMany(ctx context.Context, f *JobFilter) (int, error)
- func (c *Client) JobDiscard(ctx context.Context, id int64) (*JobRow, error)
- func (c *Client) JobDiscardMany(ctx context.Context, f *JobFilter) (int, error)
- func (c *Client) JobGet(ctx context.Context, id int64) (*JobRow, error)
- func (c *Client) JobList(ctx context.Context, p *JobListParams) (*JobListResult, error)
- func (c *Client) JobRetry(ctx context.Context, id int64) (*JobRow, error)
- func (c *Client) JobRetryMany(ctx context.Context, f *JobFilter) (int, error)
- func (c *Client) JobWork(ctx context.Context, id int64) (*JobRow, error)
- func (c *Client) LeaderGet(ctx context.Context) (*LeaderInfo, error)
- func (c *Client) PeriodicList(ctx context.Context) ([]*PeriodicInfo, error)
- func (c *Client) Pool() *pgxpool.Pool
- func (c *Client) QueueList(ctx context.Context) ([]*QueueInfo, error)
- func (c *Client) QueuePause(ctx context.Context, name string) error
- func (c *Client) QueueResume(ctx context.Context, name string) error
- func (c *Client) Schema() string
- func (c *Client) Start(ctx context.Context) error
- func (c *Client) Stop(ctx context.Context) error
- func (c *Client) StopAndCancel(ctx context.Context) error
- type Clock
- type Config
- type ConstantBackoff
- type ErrorHandler
- type ErrorHandlerResult
- type ExponentialBackoff
- type InsertOpts
- type InsertParams
- type InsertResult
- type Job
- type JobArgs
- type JobArgsWithInsertOpts
- type JobFilter
- type JobListParams
- type JobListResult
- type JobRow
- type LeaderInfo
- type Middleware
- type MiddlewareDefaults
- type PeriodicInfo
- type PeriodicJob
- type QueueConfig
- type QueueInfo
- type RetryPolicy
- type RetryPolicyFunc
- type Schedule
- type State
- type Ticker
- type UniqueOpts
- type WorkFunc
- type Worker
- type WorkerOption
- type Workers
Examples ¶
- Package
- AddWorker
- Cancel
- Client.Insert
- Client.InsertMany
- Client.InsertManyTx
- Client.InsertTx
- Client.JobCancel
- Client.JobDeleteMany
- Client.JobDiscard
- Client.JobDiscardMany
- Client.JobGet
- Client.JobList
- Client.JobRetry
- Client.JobRetryMany
- Client.JobWork
- Client.LeaderGet
- Client.PeriodicList
- Client.QueueList
- Client.QueuePause
- Client.QueueResume
- Client.Start
- Client.StopAndCancel
- ClientFromContext
- CompleteTx
- Cron
- DecodeArgs
- Discard
- Every
- ExponentialBackoff
- Heartbeat
- MustCron
- NewClient
- NewWorkers
- Snooze
Constants ¶
const ( DefaultListLimit = 50 MaxListLimit = 500 )
Pagination limits of JobList.
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.
const ( DefaultQueue = "default" DefaultPriority = 2 DefaultMaxAttempts = 25 )
Default insert values.
Variables ¶
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 ¶
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 ¶
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
})
}
Output:
func DecodeArgs ¶
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 ¶
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 ¶
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
})
}
Output:
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 ¶
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
})
}
Output:
func NewClient ¶
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) 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)
}
}
Output:
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
}
Output:
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}},
})
}
Output:
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)
}
Output:
func (*Client) JobCancel ¶
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")
}
}
Output:
func (*Client) JobDeleteMany ¶
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),
})
}
Output:
func (*Client) JobDiscard ¶
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)
}
Output:
func (*Client) JobDiscardMany ¶
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"}})
}
Output:
func (*Client) JobGet ¶
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))
}
Output:
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
}
}
Output:
func (*Client) JobRetry ¶
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)
}
Output:
func (*Client) JobRetryMany ¶
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)
}
Output:
func (*Client) JobWork ¶
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)
}
Output:
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)
}
}
Output:
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)
}
}
Output:
func (*Client) QueueList ¶
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)
}
}
Output:
func (*Client) QueuePause ¶
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")
}
Output:
func (*Client) QueueResume ¶
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")
}
Output:
func (*Client) Start ¶
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)
}
Output:
func (*Client) Stop ¶
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 ¶
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
}
Output:
type 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 ¶
ConstantBackoff always waits Delay.
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 ¶
ErrorHandlerResult overrides the outcome of a failed attempt. The first field set wins, in field order.
type ExponentialBackoff ¶
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
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 ¶
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.
type PeriodicInfo ¶
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 ¶
RetryPolicy decides when a failed job runs again. job.Attempt is the attempt that just failed (1-based).
type RetryPolicyFunc ¶
RetryPolicyFunc adapts a function to RetryPolicy.
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 ¶
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 ¶
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 ¶
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 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 Worker ¶
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
Source Files
¶
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. |