Documentation
¶
Overview ¶
Package worker unifies the background-execution patterns found across the reference services into one small vocabulary.
Instead of every service hand-rolling its own run loops, supervisors, and retry math, worker provides a handful of composable pieces:
- Runnable: anything the app supervises (HTTP/gRPC servers, consumers, loops). RunnableFunc adapts a plain start function into one.
- Group: a supervisor that starts Runnables concurrently and shuts them down together (LIFO), tearing the whole group down on the first failure.
- Loop: a recurring tick loop with panic recovery — fixed-interval (NewLoop) or adaptively paced (NewPacedLoop).
- Pool: bounded-concurrency fan-out of one-shot jobs.
- Processor[T]: a reliable claim -> handle -> ack/retry batch pipeline, built from Steps (functions) and run as a Loop.
Loops and pacing ¶
A Loop runs a tick on a schedule, each tick wrapped in panic recovery (safetick) so one bad tick cannot crash the process. A fixed Loop ticks every Interval. An adaptive Loop (NewPacedLoop) varies its delay from the Pace its tick reports: Busy (a full batch — drain again after BusyInterval, or immediately) versus Idle (no work — wait Interval, optionally backing off geometrically toward MaxIdleInterval).
Processors ¶
A Processor[T] is the reliable batch-processing FSM behind the queue workers and other claim-based consumers. Its Steps are functions: each tick Claim leases a batch (canonically SELECT ... FOR UPDATE SKIP LOCKED, so replicas can run concurrently), Handle runs on each item, then MarkDone or MarkFailed records the outcome (terminal or retryable, as IsTerminal decides). An error IsHalt accepts stops the batch, and Release, when set, returns the rest to the source untouched: a dependency that is down costs one failed item per tick, not a batch. A canceled tick and BatchTimeout stop the batch before its next item and release the rest the same way, so no item is handled past the lease of its source. Marks and releases run without the cancellation of the tick, each under its own timeout: an item handled at shutdown is still acknowledged. A panic in Handle is recovered per item and logged with its stack; by default the item is retried, and OnPanic can decide otherwise. Claim, Handle, MarkDone and MarkFailed are required: NewProcessor panics when one is nil. In-process retry of an item is retry.Do inside Handle. A Processor is not itself a Runnable: call Tick (or PacedTick) to get a tick function and wrap it in a Loop.
Usage ¶
Wire a Processor into a Loop and supervise it (plus any other Runnables) in a Group:
steps := worker.Steps[Job]{
Claim: store.Claim,
Handle: handle,
MarkDone: store.MarkDone,
MarkFailed: store.MarkFailed,
Release: store.Release, // optional
}
proc := worker.NewProcessor(log, steps, worker.ProcessorConfig{
Name: "jobs",
BatchSize: 200,
IsTerminal: func(err error) bool {
return errors.Is(err, ErrBadInput)
},
})
loop := worker.NewPacedLoop(log, worker.LoopConfig{
Name: "jobs",
Interval: time.Second, // idle wait
BusyInterval: 0, // drain backlog immediately
MaxIdleInterval: 30 * time.Second,
}, proc.PacedTick())
g := worker.NewGroup(log, worker.GroupConfig{ShutdownTimeout: 10 * time.Second})
g.Add(loop)
g.Add(worker.RunnableFunc{
NameValue: "http",
StartFn: func(ctx context.Context) error {
return srv.ListenAndServe()
},
StopFn: func(ctx context.Context) error {
return srv.Shutdown(ctx)
},
})
if err := g.Run(ctx); err != nil {
log.Error("group stopped", "err", err)
}
For discrete fan-out work, submit jobs to a Pool:
pool := worker.NewPool(worker.PoolConfig{MaxConcurrent: 8})
key, err := pool.Submit(ctx, func(ctx context.Context) { do(ctx) })
_ = key // pool.Cancel(key) stops that one job
defer pool.Shutdown(context.Background())
Metrics ¶
With LoopConfig.Metrics set, a Loop records every tick under its Name:
- skit_worker_ticks_total by worker and result (ok, error, panic);
- skit_worker_tick_duration_seconds by worker;
- skit_worker_last_success_timestamp_seconds by worker, from the first tick that ended without an error.
A Processor is counted by the ticks of the Loop it runs in.
Tracing ¶
A tick has no request behind it, so by default a Loop runs it under otel.Suppress: the queries of an idle poll export no traces. A Processor lifts the mark for each item's handler, which then sets the item's trace — the queue of events continues the trace that created the event — while the claim and the marks stay suppressed. With LoopConfig.Trace a Loop records every tick as the root span of its own trace, named after the Loop, and everything the tick does nests under it; a failed tick sets the span's error, a panic sets error.type "panic".
Config ¶
LoopConfig: Name (default "worker"), Interval (default 1s; the idle interval for an adaptive loop), ImmediateFirstTick, TickTimeout, Metrics, Trace, TracerProvider (nil → the global provider), and the adaptive fields BusyInterval and MaxIdleInterval. Option WithOnPanic sets a handler invoked when a tick panics.
ProcessorConfig: Name (default "processor"), BatchSize (default 100), HandleTimeout, BatchTimeout, IsTerminal (nil = all failures retryable), IsHalt (nil = no error stops the batch), OnPanic (nil = a panicked item is retried), Now (default time.Now().UTC; override in tests).
GroupConfig: ShutdownTimeout (0 = no bound on how long Run waits for Runnables to Stop).
PoolConfig: MaxConcurrent (default 1).
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ErrPoolShutdown = errors.New("worker: pool is shutting down")
ErrPoolShutdown is returned by Pool.Submit once Shutdown has been called.
Functions ¶
This section is empty.
Types ¶
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group supervises a set of Runnables. Run starts them all concurrently and returns when ctx is canceled or any Runnable returns a non-nil, non-canceled error — whichever comes first — after which every Runnable is asked to Stop.
This replaces hand-rolled run loops that juggle separate slices of servers, consumers, and workers: register everything as a Runnable and supervise it here.
func NewGroup ¶
func NewGroup(log *slog.Logger, cfg GroupConfig) *Group
NewGroup builds a Group. log may be nil.
type GroupConfig ¶ added in v0.14.0
type GroupConfig struct {
// ShutdownTimeout bounds the graceful-shutdown phase: it caps both each
// Runnable's Stop call and the subsequent wait for every Start goroutine to
// return, so a Runnable whose Start ignores ctx cannot hang Run forever
// (0 means no bound — wait indefinitely).
ShutdownTimeout time.Duration
}
GroupConfig configures a Group.
type Loop ¶
type Loop struct {
// contains filtered or unexported fields
}
Loop is a Runnable that calls a tick on an interval, each tick wrapped in panic recovery so a single bad tick cannot crash the process. Built with NewLoop it runs on a fixed interval; built with NewPacedLoop it paces adaptively from the tick's reported Pace. This is the common shape behind the outbox/queue background workers.
func NewLoop ¶
func NewLoop(log *slog.Logger, cfg LoopConfig, tick TickFunc, opts ...LoopOption) *Loop
NewLoop builds a fixed-interval Loop. A non-positive Interval defaults to 1s (so a zero-value config never panics in time.NewTicker), matching NewPacedLoop. log may be nil.
func NewPacedLoop ¶
func NewPacedLoop(log *slog.Logger, cfg LoopConfig, tick PacedTickFunc, opts ...LoopOption) *Loop
NewPacedLoop builds an adaptive Loop: after each tick it waits BusyInterval (default: immediately) when the tick reported Busy, or Interval — growing toward MaxIdleInterval over consecutive idle ticks — when it reported Idle. This drains a backlog quickly yet idles cheaply. log may be nil.
type LoopConfig ¶
type LoopConfig struct {
// Name identifies the loop in logs and metrics (default "worker"); give
// each loop its own.
Name string
// Interval between ticks (defaults to 1s if non-positive). In an adaptive loop
// (NewPacedLoop) this is the idle interval — the wait after a tick that found
// no work.
Interval time.Duration
// ImmediateFirstTick runs a tick at startup before the first interval.
ImmediateFirstTick bool
// TickTimeout bounds each tick (0 = inherit the loop context with no extra bound).
TickTimeout time.Duration
// Metrics is the registry of the tick metrics (skit_worker_ticks_total,
// skit_worker_tick_duration_seconds,
// skit_worker_last_success_timestamp_seconds, by worker = Name); nil
// disables them.
Metrics prometheus.Registerer
// Trace records each tick as the root span of its own trace, named Name.
// false (the default) suppresses the tick instead (otel.Suppress): nothing
// under it is traced but the items a Processor handles, which lift the mark.
Trace bool
// TracerProvider records the tick spans when Trace is set; nil → the global
// provider.
TracerProvider trace.TracerProvider
// BusyInterval is the wait after a Busy tick in an adaptive loop (0 = run
// again immediately to drain the backlog). Ignored by a fixed loop.
BusyInterval time.Duration
// MaxIdleInterval, when greater than Interval, makes an adaptive loop back
// off geometrically (×2 per consecutive idle tick) from Interval up to this
// cap, so a long-idle loop polls less often. 0 disables backoff (the loop
// always waits Interval when idle). Ignored by a fixed loop.
MaxIdleInterval time.Duration
}
LoopConfig configures a Loop.
type LoopOption ¶ added in v0.14.0
type LoopOption func(*Loop)
LoopOption customizes a Loop.
func WithOnPanic ¶ added in v0.14.0
func WithOnPanic(h safetick.PanicHandler) LoopOption
WithOnPanic sets a handler invoked when a tick panics. The panic is always recovered, logged and counted regardless.
type Pace ¶
type Pace int
Pace is the signal an adaptive tick returns to tell the loop how soon to run again: drain a backlog fast while there is work, idle cheaply when there is none.
type PacedTickFunc ¶
PacedTickFunc is a tick that reports its Pace so an adaptive loop can vary the delay between runs. Like TickFunc, a returned error is logged but does not stop the loop.
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
Pool runs one-shot jobs with a bounded degree of concurrency. Submit blocks until a slot is free (or ctx is canceled / the pool is shutting down), then launches the job on its own goroutine. Shutdown cancels every in-flight job and waits for them to return.
Use Pool for bounded fan-out of discrete tasks. For recurring work use Loop; for reliable claim/process/ack pipelines use Processor.
func (*Pool) Cancel ¶
Cancel stops a single in-flight job by its key. Unknown keys (already finished or never issued) are a no-op.
func (*Pool) Shutdown ¶
Shutdown signals the pool to stop accepting work, cancels every in-flight job, and waits for them to return or until ctx is canceled. It is idempotent.
func (*Pool) Submit ¶
Submit blocks until a slot is free, then launches job on its own goroutine. The job receives a context that is canceled either when the submission ctx is canceled or when Shutdown is called, whichever comes first. It returns a key that can be passed to Cancel to stop that single job early.
type PoolConfig ¶ added in v0.14.0
type PoolConfig struct {
// MaxConcurrent is the most jobs the Pool runs at once (defaults to 1 if
// non-positive).
MaxConcurrent int
}
PoolConfig configures a Pool.
type Processor ¶
type Processor[T any] struct { // contains filtered or unexported fields }
Processor is the reliable batch-processing FSM shared by the queue workers and push pipelines: each tick claims a batch, handles each item, then records its outcome (MarkDone on success, MarkFailed, terminal or retryable, on error). A panic in Handle is recovered per item and becomes its outcome through OnPanic.
A Processor is not itself a Runnable; call Tick to get a TickFunc and wrap it in a Loop to run it on a schedule. Run several processors over the same source for higher throughput — SKIP LOCKED coordinates the claims.
func NewProcessor ¶
NewProcessor builds a Processor that runs s. log may be nil. It panics when a required step of s is nil: a wiring mistake, caught as the service starts.
func (*Processor[T]) PacedTick ¶
func (p *Processor[T]) PacedTick() PacedTickFunc
PacedTick returns the drain cycle as a PacedTickFunc for NewPacedLoop: it reports Busy when it handled a full batch (a backlog likely remains, so the adaptive loop drains again promptly) and Idle otherwise. A batch stopped by IsHalt is Idle: a dependency that is down is retried at the idle pace.
type ProcessorConfig ¶
type ProcessorConfig struct {
// Name labels the processor in logs (defaults to "processor").
Name string
// BatchSize is the max number of items leased per tick (defaults to 100).
BatchSize int
// HandleTimeout bounds each Handle call. 0 = inherit the tick context with
// no extra bound. A mark or a release is not bounded by it: each runs on
// the tick context without its cancellation, under its own 5s timeout, so
// the outcome of a handled item is recorded even when the Handle was slow
// or the tick was canceled meanwhile.
HandleTimeout time.Duration
// BatchTimeout stops a batch that has run this long since its claim: no
// further item starts, and the rest goes back to the source through
// Steps.Release. Set it to the lease of the source minus HandleTimeout
// and a margin, so that no item is handled past its lease. 0 = no bound.
BatchTimeout time.Duration
// IsTerminal classifies a Handle error as permanent (true) or retryable
// (false). When nil, every failure is treated as retryable.
IsTerminal func(err error) bool
// IsHalt reports whether a Handle error stops the batch: that item is
// marked failed as IsTerminal says, and the rest goes back to the source
// untouched through Steps.Release. Have it accept the errors that
// mean a dependency is down, so the rest of the batch would fail the same
// way. When nil, no error stops the batch.
IsHalt func(err error) bool
// OnPanic decides the outcome of an item whose Handle panicked. The panic
// is recovered and logged with its stack, then the item is marked with the
// error OnPanic returns: nil marks it done, an error IsTerminal accepts
// marks it terminal, any other reschedules it. item is the T of the
// Processor. nil returns p: the item is retried like a retryable failure.
OnPanic func(ctx context.Context, item any, p *safetick.PanicError) error
// Now returns the tick clock; defaults to time.Now().UTC. Override in tests.
Now func() time.Time
}
ProcessorConfig configures a Processor.
type Runnable ¶
type Runnable interface {
Start(ctx context.Context) error
Stop(ctx context.Context) error
Name() string
}
Runnable is a supervised unit of work. Start blocks until ctx is canceled or the unit fails; Stop performs a graceful shutdown. Name identifies it in logs.
type RunnableFunc ¶
type RunnableFunc struct {
NameValue string
StartFn func(ctx context.Context) error
StopFn func(ctx context.Context) error
}
RunnableFunc adapts a plain start function (plus name and optional stop) into a Runnable, so callers can supply behavior as functions instead of types.
type Steps ¶ added in v0.15.0
type Steps[T any] struct { // Claim leases a batch of pending items for processing. It must be safe to // run from multiple replicas concurrently — the canonical SQL backing is // SELECT ... FOR UPDATE SKIP LOCKED, which hands each item to exactly one // caller. now is the processor's wall clock for the tick (passed in so it // is testable); limit bounds the batch size. Claim func(ctx context.Context, now time.Time, limit int) ([]T, error) // Handle processes one claimed item. A nil error means success (the item // goes to MarkDone); a non-nil error routes it to MarkFailed, with // terminality decided by the processor's IsTerminal classifier. Handle func(ctx context.Context, item T) error // MarkDone records the success of an item. MarkDone func(ctx context.Context, item T, now time.Time) error // MarkFailed records a failure, where terminal distinguishes a permanent // failure (move to a dead state) from a retryable one (return to pending // for a later tick). errMsg has already been passed through errs.Sanitize // by the processor. MarkFailed func(ctx context.Context, item T, errMsg string, terminal bool, now time.Time) error // Release returns claimed items to their source untouched: no attempt is // counted and each item keeps its place. A Processor releases the rest of // a batch it stops — at an error IsHalt accepts, at BatchTimeout or when // its tick is canceled. items is never empty. When nil, the rest stays // claimed until the source reclaims it on its own, such as by a lease that // expires. Release func(ctx context.Context, items []T) error }
Steps are what a Processor does with the items of its source. Claim, Handle, MarkDone and MarkFailed are required; Release is optional.