Documentation
¶
Overview ¶
Package worker provides background task management for Credo applications.
It unifies continuous workers (queue consumers, watchers, processors) and scheduled workers (cron-style maintenance jobs) under a single registration and lifecycle model. A worker is anything with a Run(ctx) error method; the name that identifies it is given at registration.
Quick Start ¶
worker.MustRegister(app, "heartbeat", worker.Func(func(ctx context.Context) error {
<-ctx.Done()
return nil
}))
app.MustProvide[*Cleanup](NewCleanup)
worker.MustRegisterProvided[*Cleanup](app, "cleanup",
worker.WithSchedule("@every 5m"),
worker.WithStartImmediately(),
worker.WithRunTimeout(time.Minute),
)
Contract ¶
A continuous worker's Run must stay active until its context is cancelled; returning nil earlier is a failure. A failed continuous worker is restarted after its restart delay, which backs off with jitter up to a cap while failures repeat (WithRestartDelay, WithMaxRestartDelay). A scheduled worker's Run performs one activation: activations never overlap, those that come due during a run are skipped, and WithRunTimeout bounds each run cooperatively. Panics are recovered and recorded as failures. Workers start in the application's OnStart phase and drain in OnDrain, before DI teardown. Pool.Workers reports each worker's effective Config and live state.
Adapted From ¶
Cron expression parsing and next-fire calculation are adapted from robfig/cron v3 (MIT). See NOTICES for full attribution.
Maturity: beta
Index ¶
- Constants
- Variables
- func MustRegister(app *credo.App, name string, w Worker, opts ...Option)
- func MustRegisterProvided[T Worker](app *credo.App, name string, opts ...Option)
- func Register(app *credo.App, name string, w Worker, opts ...Option) error
- func RegisterProvided[T Worker](app *credo.App, name string, opts ...Option) error
- func RunID(ctx context.Context) string
- func ScheduledAt(ctx context.Context) time.Time
- func WorkerName(ctx context.Context) string
- type Config
- type Func
- type Info
- type Kind
- type Option
- func WithMaxConsecutiveFailures(n int) Option
- func WithMaxRestartDelay(d time.Duration) Option
- func WithMaxRestarts(n int) Option
- func WithReadiness(policy ReadinessPolicy) Option
- func WithRestartDelay(d time.Duration) Option
- func WithRunTimeout(d time.Duration) Option
- func WithSchedule(expr string) Option
- func WithStartImmediately() Option
- type Pool
- type ReadinessPolicy
- type Schedule
- type Status
- type Worker
Examples ¶
Constants ¶
const DefaultMaxRestartDelay = time.Minute
DefaultMaxRestartDelay is the default cap on the restart delay of a continuous worker.
const DefaultRestartDelay = 3 * time.Second
DefaultRestartDelay is the default restart delay of a continuous worker: the first and the minimum wait before a restart.
Variables ¶
var ErrRunTimeout = errors.New("worker: run timed out")
ErrRunTimeout is the cancellation cause of a run that exceeded its WithRunTimeout budget. Inside Run,
errors.Is(context.Cause(ctx), worker.ErrRunTimeout)
tells the budget running out from the application shutting down. A run cut short by the timeout is recorded as a failure wrapping ErrRunTimeout, even when Run returns nil.
Functions ¶
func MustRegister ¶
MustRegister is like Register but panics on error.
func MustRegisterProvided ¶ added in v0.20.0
MustRegisterProvided is like RegisterProvided but panics on error.
func Register ¶
Register adds w to the application's worker pool under name.
The name identifies the registration: it must be unique within the pool, non-empty, and free of surrounding whitespace and control characters. It appears in logs, in Pool.Workers and in the readiness check name, and WorkerName returns it inside Run. Registering the same instance under two names runs it on two independent loops, so it must then be safe for concurrent Run calls.
Workers are started during credo.App.Run and stopped during credo.App.Shutdown. Register must be called before the app is finalized or run. Use RegisterProvided for a worker constructed by the DI container, and MustRegister when bootstrap code should fail fast by panicking.
Example ¶
package main
import (
"context"
"log/slog"
"time"
"github.com/credo-go/credo"
"github.com/credo-go/credo/worker"
)
func main() {
app, err := credo.New()
if err != nil {
panic(err)
}
// A continuous worker: Run stays active until the application shuts down.
heartbeat := worker.Func(func(ctx context.Context) error {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil
case <-ticker.C:
slog.InfoContext(ctx, "heartbeat", "worker", worker.WorkerName(ctx))
}
}
})
if err = worker.Register(app, "heartbeat", heartbeat, worker.WithRestartDelay(5*time.Second)); err != nil {
panic(err)
}
}
Output:
func RegisterProvided ¶ added in v0.20.0
RegisterProvided registers, under name, the worker that the application's DI container provides as T:
app.MustProvide[*InvoiceWorker](NewInvoiceWorker)
worker.MustRegisterProvided[*InvoiceWorker](app, "invoice-worker",
worker.WithSchedule("@every 1m"))
T is resolved once, when the pool starts (after credo.App.Finalize, before the server accepts traffic), so RegisterProvided and the matching Provide may be called in either order. T may be an interface bound with credo.App.Alias. A resolution failure — T not provided, a constructor error or panic, a nil result — fails the application's startup with an error naming the worker and the type, and no worker is started. The name and options follow the same rules as Register.
Example ¶
package main
import (
"context"
"log/slog"
"time"
"github.com/credo-go/credo"
"github.com/credo-go/credo/worker"
)
// invoiceSweeper is a scheduled worker built by the DI container.
type invoiceSweeper struct {
log *slog.Logger
}
func newInvoiceSweeper(infra credo.Infra) *invoiceSweeper {
return &invoiceSweeper{log: infra.Logger}
}
// Run performs one activation.
func (s *invoiceSweeper) Run(ctx context.Context) error {
s.log.InfoContext(ctx, "sweeping invoices", "run_id", worker.RunID(ctx))
return nil
}
func main() {
app, err := credo.New()
if err != nil {
panic(err)
}
// The worker is resolved when the pool starts, so the provider and the
// registration may come in either order.
app.MustProvide[*invoiceSweeper](newInvoiceSweeper)
if err = worker.RegisterProvided[*invoiceSweeper](app, "invoice-sweeper",
worker.WithSchedule("@every 1m"),
worker.WithStartImmediately(),
worker.WithRunTimeout(15*time.Second),
worker.WithMaxConsecutiveFailures(3),
); err != nil {
panic(err)
}
}
Output:
func ScheduledAt ¶
ScheduledAt returns the intended fire time for scheduled workers.
func WorkerName ¶
WorkerName returns the registration name of the worker whose run ctx belongs to.
Types ¶
type Config ¶ added in v0.20.0
type Config struct {
// Schedule is the cron expression of a scheduled worker, as registered.
Schedule string `json:"schedule"`
// StartImmediately reports [WithStartImmediately] (scheduled workers).
StartImmediately bool `json:"start_immediately"`
// RunTimeout is the [WithRunTimeout] budget of each run (scheduled
// workers); 0 means no timeout.
RunTimeout time.Duration `json:"run_timeout"`
// MaxConsecutiveFailures is the [WithMaxConsecutiveFailures] limit
// (scheduled workers); 0 means unlimited.
MaxConsecutiveFailures int `json:"max_consecutive_failures"`
// MaxRestarts is the [WithMaxRestarts] limit (continuous workers); 0
// means unlimited.
MaxRestarts int `json:"max_restarts"`
// RestartDelay is the base restart delay of a continuous worker — the
// first and the minimum wait before a restart — after the option, the
// pool's worker.restart_delay configuration and [DefaultRestartDelay] are
// resolved.
RestartDelay time.Duration `json:"restart_delay"`
// MaxRestartDelay is the cap the restart delay of a continuous worker
// backs off to, resolved as described at [WithMaxRestartDelay]; never
// below RestartDelay.
MaxRestartDelay time.Duration `json:"max_restart_delay"`
// Readiness is a copy of the worker's [ReadinessPolicy]; nil when the
// worker does not take part in readiness.
Readiness *ReadinessPolicy `json:"readiness,omitzero"`
}
Config is the effective, immutable configuration of a registered worker: the policy the runner executes once defaults and the pool configuration are applied, not an echo of the options passed to Register. Fields that do not apply to the worker's Kind are zero, and zero limits mean unlimited.
type Func ¶
Func adapts a plain function into a Worker, in the style of net/http.HandlerFunc.
type Info ¶
type Info struct {
Name string `json:"name"`
Kind Kind `json:"kind"`
Config Config `json:"config"`
Status Status `json:"status"`
// Restarts counts the restarts of a continuous worker.
Restarts int64 `json:"restarts"`
// ConsecutiveFailures counts the failed runs of a scheduled worker since
// its last success.
ConsecutiveFailures int64 `json:"consecutive_failures"`
LastRun time.Time `json:"last_run,omitzero"`
// LastSuccess is the completion time of the last successful run of a
// scheduled worker; zero until then, and always zero for a continuous
// worker, whose Run never completes successfully.
LastSuccess time.Time `json:"last_success,omitzero"`
// LastError is the error of the most recent failed run, without any
// stack trace; a successful scheduled run clears it.
LastError string `json:"last_error,omitzero"`
}
Info is a point-in-time snapshot of a worker: its identity, its effective configuration and its live state.
Info is shaped for direct JSON encoding (for example from an admin endpoint): field names are snake_case, durations encode as integer nanoseconds under Credo's response profile, and last_run, last_success, last_error and config.readiness are omitted while zero.
type Kind ¶ added in v0.20.0
type Kind string
Kind reports whether a worker runs continuously or on a schedule.
type Option ¶
type Option func(*options)
Option configures worker registration.
func WithMaxConsecutiveFailures ¶
WithMaxConsecutiveFailures sets the failure threshold for scheduled workers. Zero (the default) means unlimited failures; the worker is marked failed only once a positive limit is reached.
func WithMaxRestartDelay ¶ added in v0.21.0
WithMaxRestartDelay caps the restart delay of a continuous worker. After each failed run the delay window doubles, from the base restart delay up to this cap, and the delay is drawn from it with jitter:
ceiling = min(base × 2^(k−1), cap) delay = uniform in [max(base, ceiling/2), ceiling]
where k counts the failures of the current sequence, so the first delay is exactly the base. A run that lasted at least the cap starts a new sequence. Setting both delays to the same value gives a fixed delay.
Omitted, the cap is the pool's worker.max_restart_delay, else DefaultMaxRestartDelay, raised to the base when the base is larger. Zero skips the pool configuration and selects the larger of DefaultMaxRestartDelay and the base. A positive cap below the base is a registration error.
func WithMaxRestarts ¶
WithMaxRestarts limits how often a continuous worker is restarted: a positive n allows the first run plus at most n restarts, and the worker is marked failed when a run fails after the n-th restart. Zero (the default) means unlimited restarts.
func WithReadiness ¶ added in v0.16.0
func WithReadiness(policy ReadinessPolicy) Option
WithReadiness binds the worker to the readiness probe under policy. Registration fails when the policy has no condition, when MaxSuccessAge is negative, or when a scheduled-only condition is used on a continuous worker.
func WithRestartDelay ¶
WithRestartDelay sets the base restart delay of a continuous worker: the wait before the first restart of a failure sequence and the minimum wait before any restart. Later restarts back off up to WithMaxRestartDelay. A zero delay selects DefaultRestartDelay, skipping the pool's worker.restart_delay, so that a worker failing immediately on every run never busy-loops.
func WithRunTimeout ¶ added in v0.20.0
WithRunTimeout bounds every run of a scheduled worker, including the startup run of WithStartImmediately: once d has elapsed the run context is cancelled with the cause ErrRunTimeout, and the run counts as a failure whatever Run then returns. The timeout is cooperative — it cancels the context and never abandons the running goroutine — so a Run that ignores its context keeps the worker busy, and activations that pass in the meantime are skipped. Zero (the default) means no timeout.
func WithSchedule ¶
WithSchedule makes the worker scheduled using a cron expression.
func WithStartImmediately ¶
func WithStartImmediately() Option
WithStartImmediately runs a scheduled worker once during startup.
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
Pool manages registered workers and integrates with app lifecycle.
func (*Pool) Shutdown ¶
Shutdown stops all workers and waits for them to exit. The first call cancels the pool context and starts the wait; every call, including a concurrent or later one, returns nil once all workers have returned — completion takes precedence over an already-ended ctx — and ctx.Err() only while workers are still running when ctx ends. A pool that was never started shuts down immediately, and Start is refused afterwards.
func (*Pool) Start ¶
Start resolves every registered worker and launches them. It is all-or-nothing: when any worker fails to resolve, Start returns the joined errors, each naming its worker, and launches none.
Start runs in three steps so that user constructors never run under the pool lock: it claims the pool (refusing further registrations), resolves the workers outside the lock, then publishes the runners — unless a Shutdown arrived meanwhile, which wins.
type ReadinessPolicy ¶ added in v0.16.0
type ReadinessPolicy struct {
// RequireFirstSuccess keeps the instance unready until the worker's first
// run has completed without error — a startup barrier for recovery or
// warm-up jobs. Scheduled workers only; pair it with [WithStartImmediately]
// unless waiting for the first cron activation is intended. Once satisfied
// it stays satisfied, even if later runs fail.
RequireFirstSuccess bool `json:"require_first_success"`
// FailWhenFailed reports the instance unready once the worker reaches
// [StatusFailed], that is, once it exhausted [WithMaxRestarts] or
// [WithMaxConsecutiveFailures]. Use it only for workers the instance cannot
// serve without: every replica hitting the same persistent failure leaves
// rotation together.
FailWhenFailed bool `json:"fail_when_failed"`
// MaxSuccessAge reports the instance unready when the last successful run
// finished longer ago than this duration. Scheduled workers only; zero
// disables the check. Until the first success it is not applied — combine
// it with RequireFirstSuccess to close that window.
MaxSuccessAge time.Duration `json:"max_success_age"`
}
ReadinessPolicy describes how one worker contributes to the application's readiness probe (see credo.App.UseHealth). Every condition is opt-in and the zero policy is rejected by WithReadiness; a worker with no policy never influences readiness, because not every failed worker should take an instance out of rotation.
The contribution is reported as a readiness check named "worker:<name>", next to checks added with credo.App.AddReadinessCheck. It is evaluated in-memory from the worker's last known state and never blocks. Registration order relative to UseHealth does not matter.
type Schedule ¶
type Schedule struct {
// contains filtered or unexported fields
}
Schedule represents a compiled cron schedule.
func ParseSchedule ¶
ParseSchedule parses a cron expression into a compiled schedule.
The supported syntax is standard 5-field Vixie cron — minute, hour, day-of-month, month, day-of-week — with lists ("1,15"), ranges ("1-5"), steps ("*/10", "8-18/2"), month and weekday names ("jan", "sat"), "?" as an alias for "*", and 7 accepted as Sunday. The descriptors @hourly, @daily (alias @midnight), @weekly, @monthly, and "@every <duration>" are also accepted. Schedules are evaluated in the server's local time zone and fire at second 0 of the matching minute; for sub-minute periods use "@every <duration>", whose duration must be a positive whole number of seconds ("@every 90s", "@every 1h30m"; "@every 1500ms" is rejected).
As in crontab(5), when both the day-of-month and day-of-week fields are restricted (neither is "*"), the schedule fires when EITHER matches: "0 0 13 * fri" runs on the 13th of the month AND on every Friday. Note that a step applied to "*" (e.g. "*/2" in day-of-month) counts as restricted for this rule.
type Status ¶
type Status string
Status represents a worker's current lifecycle state.
const ( // StatusIdle means the worker is registered but not yet started. StatusIdle Status = "idle" // StatusRunning means the worker is actively executing. StatusRunning Status = "running" // StatusWaiting means the worker is waiting for restart delay or next tick. StatusWaiting Status = "waiting" // StatusStopped means the worker exited normally and will not run again. StatusStopped Status = "stopped" // StatusFailed means the worker exceeded its configured failure threshold. StatusFailed Status = "failed" )
type Worker ¶
Worker is a background task managed by the framework. The name that identifies it is given at registration (Register, RegisterProvided), not by the worker itself.
A continuous worker's Run must stay active until ctx is cancelled; a scheduled worker's Run performs one activation and returns.