worker

package
v0.18.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 18 Imported by: 1

Documentation

Overview

Package worker runs the background work of a service: supervised components, recurring loops, bounded fan-out and claim-based batches.

Instead of every service hand-rolling its own run loops and supervisors, 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.ErrorContext(ctx, "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).

Example

A Processor drains a source in a paced Loop that a Group supervises. Here the source is a slice: the first tick claims a full batch, so the next runs at once; a tick that finds the source empty stops the example.

package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/assanoff/skit/worker"
)

func main() {
	type job struct {
		id   int
		name string
	}
	errBadInput := errors.New("bad input")
	pending := []job{{1, "ann"}, {2, "bob"}, {3, ""}}
	ctx, stop := context.WithCancel(context.Background())

	steps := worker.Steps[job]{
		Claim: func(_ context.Context, _ time.Time, limit int) ([]job, error) {
			n := min(limit, len(pending))
			batch := pending[:n]
			pending = pending[n:]
			if n == 0 {
				stop()
			}
			return batch, nil
		},
		Handle: func(_ context.Context, j job) error {
			if j.name == "" {
				return fmt.Errorf("job %d: %w", j.id, errBadInput)
			}
			fmt.Println("hello,", j.name)
			return nil
		},
		MarkDone: func(_ context.Context, j job, _ time.Time) error {
			fmt.Println("done", j.id)
			return nil
		},
		MarkFailed: func(_ context.Context, j job, msg string, terminal bool, _ time.Time) error {
			fmt.Printf("failed %d: %s, terminal %t\n", j.id, msg, terminal)
			return nil
		},
	}
	proc := worker.NewProcessor(nil, steps, worker.ProcessorConfig{
		Name:      "greetings",
		BatchSize: 2,
		IsTerminal: func(err error) bool {
			return errors.Is(err, errBadInput)
		},
	})
	loop := worker.NewPacedLoop(nil, worker.LoopConfig{
		Name:               "greetings",
		Interval:           10 * time.Millisecond, // the wait after an idle tick
		ImmediateFirstTick: true,
	}, proc.PacedTick())

	g := worker.NewGroup(nil, worker.GroupConfig{ShutdownTimeout: time.Second})
	g.Add(loop)
	fmt.Println("run:", g.Run(ctx))
}
Output:
hello, ann
done 1
hello, bob
done 2
failed 3: job 3: bad input, terminal true
run: <nil>

Index

Examples

Constants

This section is empty.

Variables

View Source
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.

Example

The first Runnable to fail tears the Group down: the others are stopped in reverse order of Add, and Run returns the error.

package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/assanoff/skit/worker"
)

func main() {
	stopFn := func(name string) func(context.Context) error {
		return func(context.Context) error {
			fmt.Println("stop", name)
			return nil
		}
	}

	g := worker.NewGroup(nil, worker.GroupConfig{ShutdownTimeout: time.Second})
	g.Add(
		// No StartFn: the Runnable runs until the Group stops.
		worker.RunnableFunc{NameValue: "http", StopFn: stopFn("http")},
		worker.RunnableFunc{NameValue: "consumer", StopFn: stopFn("consumer")},
		worker.RunnableFunc{
			NameValue: "import",
			StartFn: func(context.Context) error {
				return errors.New("import: source is down")
			},
		},
	)
	fmt.Println("run:", g.Run(context.Background()))
}
Output:
stop consumer
stop http
run: import: source is down

func NewGroup

func NewGroup(log *slog.Logger, cfg GroupConfig) *Group

NewGroup builds a Group. log may be nil.

func (*Group) Add

func (g *Group) Add(r ...Runnable)

Add registers one or more Runnables, skipping any nil entries — so a constructor that returns nil for a disabled component can be passed straight through without the caller filtering it first. Not safe to call once Run has started.

func (*Group) Run

func (g *Group) Run(ctx context.Context) error

Run starts all Runnables and blocks until shutdown. It always attempts to Stop every Runnable before returning, and returns the first triggering error (nil on a clean, ctx-driven shutdown).

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 JobFn

type JobFn func(ctx context.Context)

JobFn is a unit of work submitted to a Pool.

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.

Example

An error of a tick is logged, and the Loop ticks on until its context is canceled: here by its third tick.

package main

import (
	"context"
	"errors"
	"fmt"
	"log/slog"
	"os"
	"time"

	"github.com/assanoff/skit/worker"
)

func main() {
	h := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if len(groups) == 0 && a.Key == slog.TimeKey {
				return slog.Attr{}
			}
			return a
		},
	})
	ctx, stop := context.WithCancel(context.Background())

	n := 0
	loop := worker.NewLoop(slog.New(h), worker.LoopConfig{
		Name:               "report",
		Interval:           10 * time.Millisecond,
		ImmediateFirstTick: true,
	}, func(context.Context) error {
		n++
		switch n {
		case 1:
			return errors.New("report: source is down")
		case 3:
			stop()
		}
		return nil
	})
	fmt.Println("start:", loop.Start(ctx))
}
Output:
level=ERROR msg="worker tick error" worker=report err="report: source is down"
start: context canceled

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.

func (*Loop) Name

func (l *Loop) Name() string

Name implements Runnable.

func (*Loop) Start

func (l *Loop) Start(ctx context.Context) error

Start implements Runnable: it ticks until ctx is canceled.

func (*Loop) Stop

func (l *Loop) Stop(context.Context) error

Stop implements Runnable; the loop stops when its context is canceled.

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.

const (
	// Idle means the tick found no (or only partial) work; the loop waits the
	// idle interval before the next tick.
	Idle Pace = iota
	// Busy means the tick drained a full batch, so a backlog likely remains; the
	// loop runs again after the (short) busy interval.
	Busy
)

type PacedTickFunc

type PacedTickFunc func(ctx context.Context) (Pace, error)

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.

Example

A Pool runs at most MaxConcurrent jobs at once. Submit returns the key that Cancel takes to stop that one job.

package main

import (
	"context"
	"fmt"
	"slices"
	"sync"

	"github.com/assanoff/skit/worker"
)

func main() {
	ctx := context.Background()
	pool := worker.NewPool(worker.PoolConfig{MaxConcurrent: 2})

	var (
		mu   sync.Mutex
		sent []string
		wg   sync.WaitGroup
	)
	for _, to := range []string{"eve", "ann", "bob"} {
		wg.Add(1)
		_, err := pool.Submit(ctx, func(context.Context) {
			defer wg.Done()
			mu.Lock()
			defer mu.Unlock()
			sent = append(sent, to)
		})
		if err != nil {
			fmt.Println("submit:", err)
			return
		}
	}
	wg.Wait()
	slices.Sort(sent)
	fmt.Println("sent:", sent)

	canceled := make(chan error)
	key, err := pool.Submit(ctx, func(ctx context.Context) {
		<-ctx.Done()
		canceled <- ctx.Err()
	})
	if err != nil {
		fmt.Println("submit:", err)
		return
	}
	pool.Cancel(key)
	fmt.Println("job:", <-canceled)
	fmt.Println("shutdown:", pool.Shutdown(ctx))
}
Output:
sent: [ann bob eve]
job: context canceled
shutdown: <nil>

func NewPool

func NewPool(cfg PoolConfig) *Pool

NewPool constructs a Pool.

func (*Pool) Cancel

func (p *Pool) Cancel(key string)

Cancel stops a single in-flight job by its key. Unknown keys (already finished or never issued) are a no-op.

func (*Pool) Running

func (p *Pool) Running() int

Running reports the number of jobs currently executing.

func (*Pool) Shutdown

func (p *Pool) Shutdown(ctx context.Context) error

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

func (p *Pool) Submit(ctx context.Context, job JobFn) (string, error)

Submit blocks until a slot is free, then launches job on its own goroutine. The job receives a context with the values and the deadline of ctx but not its cancellation: the caller of Submit returning does not stop the job, Cancel and Shutdown do. 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

func NewProcessor[T any](log *slog.Logger, s Steps[T], cfg ProcessorConfig) *Processor[T]

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.

func (*Processor[T]) Tick

func (p *Processor[T]) Tick() TickFunc

Tick returns the processor's drain cycle as a TickFunc suitable for NewLoop (fixed interval).

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.

func (RunnableFunc) Name

func (r RunnableFunc) Name() string

Name implements Runnable.

func (RunnableFunc) Start

func (r RunnableFunc) Start(ctx context.Context) error

Start implements Runnable.

func (RunnableFunc) Stop

func (r RunnableFunc) Stop(ctx context.Context) error

Stop implements Runnable.

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.

type TickFunc

type TickFunc func(ctx context.Context) error

TickFunc performs one unit of periodic work. Returning an error logs it but does not stop the loop; the loop stops only when its context is canceled.

Jump to

Keyboard shortcuts

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