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 one interface. A worker is anything with a Run(ctx) error method; the name that identifies it is given at registration, and the registration method chooses its kind.
Quick Start ¶
workers := worker.Use(app)
workers.Continuous("heartbeat", worker.Func(func(ctx context.Context) error {
<-ctx.Done()
return nil
}))
app.Provide[*Cleanup](NewCleanup)
workers.ScheduledProvided[*Cleanup]("cleanup", "@every 5m", worker.ScheduledConfig{
RunOnStart: true,
RunTimeout: time.Minute,
})
Contract ¶
Each registration adds the worker to the App as a lifecycle component named "worker:<name>": the start walk launches it, and the App stops it in its tier — a scheduled worker with the HTTP drain (ingress), a continuous worker after it and before the components it depends on (internal). A provided worker is built from the container in the start walk, after its dependencies, so the dependency graph orders it in both directions.
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 a delay that backs off with jitter while failures repeat (Restart). A scheduled worker's Run performs one activation: activations never overlap, those that come due during a run are skipped, and ScheduledConfig.RunTimeout bounds each run cooperatively. Panics are recovered and recorded as failures. Supervisor.Snapshot and Supervisor.Lookup report each worker's resolved configuration and live state; readiness participation is opt-in per condition.
Registration validates names, configurations and cron expressions at the call and panics on misuse; ParseSchedule returns the error for an expression that comes from configuration.
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
- type ContinuousConfig
- type Func
- type Info
- type Kind
- type Restart
- type RunInfo
- type Schedule
- type ScheduledConfig
- type Status
- type Supervisor
- func (s *Supervisor) Continuous(name string, w Worker, cfg ...ContinuousConfig)
- func (s *Supervisor) ContinuousProvided[T Worker](name string, cfg ...ContinuousConfig)
- func (s *Supervisor) Lookup(name string) (Info, bool)
- func (s *Supervisor) Scheduled(name, expr string, w Worker, cfg ...ScheduledConfig)
- func (s *Supervisor) ScheduledProvided[T Worker](name, expr string, cfg ...ScheduledConfig)
- func (s *Supervisor) Snapshot() []Info
- type Worker
Examples ¶
Constants ¶
const DefaultMaxRestartDelay = time.Minute
DefaultMaxRestartDelay is the default cap on the restart delay of a continuous worker (Restart.MaxDelay).
const DefaultMinRestartDelay = 3 * time.Second
DefaultMinRestartDelay is the default first and shortest wait before a continuous worker restarts (Restart.MinDelay).
Variables ¶
var ErrRunTimeout = errors.New("worker: run timed out")
ErrRunTimeout is the cancellation cause of a run that exceeded its ScheduledConfig.RunTimeout budget. Inside Run,
errors.Is(context.Cause(ctx), worker.ErrRunTimeout)
tells the budget running out from the worker being stopped. A run cut short by the timeout is recorded as a failure wrapping ErrRunTimeout, even when Run returns nil.
Functions ¶
This section is empty.
Types ¶
type ContinuousConfig ¶ added in v0.24.0
type ContinuousConfig struct {
// Tier is the drain tier of the worker's component; zero is
// credo.TierInternal: the worker stops after the HTTP drain, before the
// components it depends on. A worker that consumes an external queue
// declares credo.TierIngress, so it stops taking work with the listener.
Tier credo.Tier `json:"tier"`
// Restart is the restart policy after a failed run.
Restart Restart `json:"restart"`
// UnreadyWhenFailed reports the instance unready once the worker is
// failed.
UnreadyWhenFailed bool `json:"unready_when_failed"`
}
ContinuousConfig configures a continuous worker. Zero means the default in every field.
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"`
// Schedule is the expression of a scheduled worker, as registered; empty
// for a continuous worker.
Schedule string `json:"schedule,omitzero"`
// Continuous is the resolved configuration of a continuous worker; nil
// for a scheduled one. Each snapshot holds its own copy.
Continuous *ContinuousConfig `json:"continuous,omitzero"`
// Scheduled is the resolved configuration of a scheduled worker; nil for
// a continuous one. Each snapshot holds its own copy.
Scheduled *ScheduledConfig `json:"scheduled,omitzero"`
Status Status `json:"status"`
// Restarts counts the restarts of a continuous worker that started.
Restarts int64 `json:"restarts"`
// ConsecutiveFailures counts the failed runs of a scheduled worker since
// its last success.
ConsecutiveFailures int64 `json:"consecutive_failures"`
// LastStartedAt is the start time of the most recently admitted run.
LastStartedAt time.Time `json:"last_started_at,omitzero"`
// LastSucceededAt is the completion time of the last successful run of a
// scheduled worker; always zero for a continuous worker.
LastSucceededAt time.Time `json:"last_succeeded_at,omitzero"`
// LastError is the error of the most recent failed run, without any stack
// trace; a successful scheduled run clears it, a graceful stop does not.
LastError string `json:"last_error,omitzero"`
}
Info is a point-in-time snapshot of a worker: its identity, its resolved 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 schedule, continuous, scheduled, last_started_at, last_succeeded_at and last_error 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 Restart ¶ added in v0.24.0
type Restart struct {
// Disabled makes the first failed run terminal. It cannot be combined
// with any other field.
Disabled bool `json:"disabled"`
// Limit allows the first run plus at most Limit restarts; zero means
// unlimited.
Limit int `json:"limit"`
// MinDelay is the first and shortest wait; zero is
// [DefaultMinRestartDelay].
MinDelay time.Duration `json:"min_delay"`
// MaxDelay is the longest wait; zero is the larger of
// [DefaultMaxRestartDelay] and MinDelay. A positive MaxDelay below
// MinDelay is rejected.
MaxDelay time.Duration `json:"max_delay"`
}
Restart is the restart policy of a continuous worker. After a failed run the worker waits and runs again; the wait starts at MinDelay and backs off, with jitter, up to MaxDelay while failures repeat:
ceiling = min(MinDelay × 2^(k−1), MaxDelay) delay = uniform in [max(MinDelay, ceiling/2), ceiling]
where k counts the failures of the current sequence, so the first delay is exactly MinDelay. A run that lasted at least MaxDelay starts a new sequence. Equal delays give a fixed delay.
type RunInfo ¶ added in v0.24.0
type RunInfo struct {
// Worker is the registration name.
Worker string
// ID is the run's identifier, equal to the run_id of the framework's log
// lines for that run.
ID string
// ScheduledAt is the intended activation of a scheduled run; zero for
// continuous runs and for the RunOnStart run.
ScheduledAt time.Time
}
RunInfo is the execution metadata of one run, carried by the context passed to Run.
func CurrentRun ¶ added in v0.24.0
CurrentRun returns the metadata of the run that ctx belongs to, and false with a zero RunInfo for a context that is not a run context.
Example ¶
package main
import (
"context"
"fmt"
"log/slog"
"github.com/credo-go/credo"
"github.com/credo-go/credo/worker"
)
func main() {
app, err := credo.New(credo.WithLogger(slog.New(slog.DiscardHandler)))
if err != nil {
panic(err)
}
workers := worker.Use(app)
done := make(chan struct{})
workers.Scheduled("report", "@every 1h", worker.Func(func(ctx context.Context) error {
defer close(done)
run, ok := worker.CurrentRun(ctx)
fmt.Println("run context:", ok)
fmt.Println("worker:", run.Worker)
fmt.Println("run id set:", run.ID != "")
fmt.Println("run on start, so no activation time:", run.ScheduledAt.IsZero())
return nil
}), worker.ScheduledConfig{RunOnStart: true})
_, ok := worker.CurrentRun(context.Background())
fmt.Println("outside a run:", ok)
if err = app.Start(context.Background()); err != nil {
panic(err)
}
<-done
if err = app.Shutdown(context.Background()); err != nil {
panic(err)
}
}
Output: outside a run: false run context: true worker: report run id set: true run on start, so no activation time: true
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 ScheduledConfig ¶ added in v0.24.0
type ScheduledConfig struct {
// Tier is the drain tier of the worker's component; zero is
// credo.TierIngress: the worker stops with the listener, so no run starts
// during the drain.
Tier credo.Tier `json:"tier"`
// RunOnStart adds one run as soon as the worker starts, before the first
// computed activation.
RunOnStart bool `json:"run_on_start"`
// RunTimeout bounds every run, the RunOnStart run included: the run
// context is cancelled with the cause [ErrRunTimeout], and the run is a
// failure whatever Run returns. The timeout is cooperative; it never
// abandons the goroutine. Zero means no timeout.
RunTimeout time.Duration `json:"run_timeout"`
// MaxConsecutiveFailures makes the worker failed after that many failed
// runs in a row; zero means unlimited.
MaxConsecutiveFailures int `json:"max_consecutive_failures"`
// UnreadyWhenFailed reports the instance unready once the worker is
// failed.
UnreadyWhenFailed bool `json:"unready_when_failed"`
// UnreadyUntilFirstSuccess keeps the instance unready until the worker's
// first run succeeds; once met it stays met. Pair it with RunOnStart
// unless waiting for the first activation is intended.
UnreadyUntilFirstSuccess bool `json:"unready_until_first_success"`
// UnreadyAfterSuccessAge reports the instance unready when the last
// success is older than this; zero turns the check off. It is not applied
// before the first success.
UnreadyAfterSuccessAge time.Duration `json:"unready_after_success_age"`
}
ScheduledConfig configures a scheduled worker. Zero means the default in every field.
type Status ¶
type Status string
Status is a worker's lifecycle state.
const ( // StatusPending means the worker's component has not started, or a // continuous worker has not yet been admitted to its first run. StatusPending Status = "pending" // StatusRunning means a run has been admitted and is executing. StatusRunning Status = "running" // StatusBackoff means a continuous worker is waiting to restart after a // failure: unhealthy, recovering. StatusBackoff Status = "backoff" // StatusWaiting means a scheduled worker is waiting for its next // activation, whatever its last run did. StatusWaiting Status = "waiting" // StatusStopped means the loop ended because the worker's component was // shut down; the worker will not run again. StatusStopped Status = "stopped" // StatusFailed means a positive failure limit was exhausted, restarts are // disabled and a run failed, or the schedule has no future activation. It // is permanent until the application restarts. StatusFailed Status = "failed" )
type Supervisor ¶ added in v0.24.0
type Supervisor struct {
// contains filtered or unexported fields
}
Supervisor registers an App's workers and reports their state. It is a registry, not a lifecycle: each registration adds the worker to the App as a component named "worker:<name>", which the App starts and stops in its tier like every other component. The supervisor has no Start, no Shutdown and no DI binding.
func Use ¶ added in v0.24.0
func Use(app *credo.App) *Supervisor
Use returns a new supervisor for app's workers. It registers nothing: it binds nothing into the container, installs no hook and adds no component. The supervisor logs through app.Logger with module=worker. Use may be called more than once; each supervisor is an independent registry, and the App refuses a worker name that another supervisor already registered.
A module that registers workers takes the supervisor as a parameter; an application that wants it injected binds it itself with app.ProvideValue.
Example ¶
package main
import (
"context"
"fmt"
"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)
}
workers := worker.Use(app)
// A continuous worker: Run stays active until the application shuts down.
workers.Continuous("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:
run, _ := worker.CurrentRun(ctx)
slog.InfoContext(ctx, "heartbeat", "worker", run.Worker)
}
}
}), worker.ContinuousConfig{Restart: worker.Restart{MinDelay: 5 * time.Second}})
// A scheduled worker: one run per activation, never overlapping.
workers.Scheduled("metrics-report", "@every 1m", worker.Func(func(context.Context) error {
return nil
}))
for _, info := range workers.Snapshot() {
var tier credo.Tier
if info.Continuous != nil {
tier = info.Continuous.Tier
} else {
tier = info.Scheduled.Tier
}
fmt.Println(info.Name, info.Kind, tier, info.Status)
}
}
Output: heartbeat continuous internal pending metrics-report scheduled ingress pending
func (*Supervisor) Continuous ¶ added in v0.24.0
func (s *Supervisor) Continuous(name string, w Worker, cfg ...ContinuousConfig)
Continuous registers w under name as a continuous worker: Run is called once when the worker starts and must stay active until its context is cancelled; a failed run — an error, a panic, or a nil return before shutdown — is restarted under cfg's Restart policy. A restart calls Run again on the same value, so Run must be re-enterable.
The worker is a component of the App, in cfg's tier (internal by default). Registered by value it has no edges the dependency graph can see: it takes its place in its tier by registration order. A worker that uses infrastructure is registered with Supervisor.ContinuousProvided.
Continuous takes at most one configuration and panics on misuse: a nil worker, an invalid or duplicate name, more than one configuration, a rejected value, or a call after Finalize.
func (*Supervisor) ContinuousProvided ¶ added in v0.24.0
func (s *Supervisor) ContinuousProvided[T Worker](name string, cfg ...ContinuousConfig)
ContinuousProvided registers, under name, the continuous worker the DI container provides as T:
app.Provide[*OrderConsumer](NewOrderConsumer)
workers.ContinuousProvided[*OrderConsumer]("order-consumer")
The worker's component is a constructor over T: the start walk builds it after T's component dependencies have started, and the worker stops before them. Provide[T] may come before or after this call, both before Finalize; T may be an interface bound with app.Alias. A T without a binding fails Finalize; a constructor error, a panic or a nil T fails the start. One T registered under two names panics, in any supervisor of the App, since the container hands every registration the same instance.
The configuration follows Supervisor.Continuous.
func (*Supervisor) Lookup ¶ added in v0.24.0
func (s *Supervisor) Lookup(name string) (Info, bool)
Lookup returns the worker registered under exactly name, or false. A name it does not know is the caller's error to report, never a pass.
func (*Supervisor) Scheduled ¶ added in v0.24.0
func (s *Supervisor) Scheduled(name, expr string, w Worker, cfg ...ScheduledConfig)
Scheduled registers w under name as a scheduled worker that runs once per activation of the cron expression expr. Runs never overlap: activations that pass during a run are skipped and logged. A failed run counts toward cfg.MaxConsecutiveFailures.
The worker is a component of the App, in cfg's tier (ingress by default: it stops with the listener, so no run starts during the drain). Registered by value it has no edges; a worker that uses infrastructure is registered with Supervisor.ScheduledProvided. Every replica runs every schedule.
Scheduled panics on misuse — a nil worker, an invalid or duplicate name, more than one configuration, a rejected value, an expression that does not parse (ParseSchedule returns that error instead), a call after Finalize.
func (*Supervisor) ScheduledProvided ¶ added in v0.24.0
func (s *Supervisor) ScheduledProvided[T Worker](name, expr string, cfg ...ScheduledConfig)
ScheduledProvided registers, under name, the scheduled worker the DI container provides as T, running once per activation of expr. T is resolved as in Supervisor.ContinuousProvided; the configuration and the schedule follow Supervisor.Scheduled.
Example ¶
package main
import (
"context"
"fmt"
"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 {
run, _ := worker.CurrentRun(ctx)
s.log.InfoContext(ctx, "sweeping invoices", "run_id", run.ID)
return nil
}
func main() {
app, err := credo.New()
if err != nil {
panic(err)
}
workers := worker.Use(app)
// The worker is built in the start walk, so the provider and the
// registration may come in either order, both before Finalize.
app.Provide[*invoiceSweeper](newInvoiceSweeper)
workers.ScheduledProvided[*invoiceSweeper]("invoice-sweeper", "@every 1m", worker.ScheduledConfig{
RunOnStart: true,
RunTimeout: 15 * time.Second,
MaxConsecutiveFailures: 3,
})
info, ok := workers.Lookup("invoice-sweeper")
fmt.Println(ok, info.Kind, info.Schedule)
fmt.Println(info.Scheduled.Tier, info.Scheduled.RunOnStart, info.Scheduled.RunTimeout,
info.Scheduled.MaxConsecutiveFailures)
}
Output: true scheduled @every 1m ingress true 15s 3
func (*Supervisor) Snapshot ¶ added in v0.24.0
func (s *Supervisor) Snapshot() []Info
Snapshot returns one Info per registered worker, in registration order: its resolved configuration and its live state.
type Worker ¶
Worker is a background task run by the framework. The name that identifies it is given at registration (Supervisor.Continuous, Supervisor.Scheduled and their provided forms), 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.