worker

package
v0.25.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package worker is the engine behind the root package's workers: the run loop of each kind, the restart backoff, the run outcome classification, the schedule loop and the cron parser. It does not import the root package; the root's Workers registry validates registrations, converts its public types at the boundary and hands each worker's Component to the App as a lifecycle component named "worker:<name>".

Adapted From

Cron expression parsing and next-fire calculation are adapted from robfig/cron v3 (MIT). See NOTICES for full attribution.

Index

Constants

View Source
const DefaultMaxRestartDelay = time.Minute

DefaultMaxRestartDelay is the default cap on the restart delay of a continuous worker; credo.DefaultMaxRestartDelay has the same value.

View Source
const DefaultMinRestartDelay = 3 * time.Second

DefaultMinRestartDelay is the default first and shortest wait before a continuous worker restarts; credo.DefaultMinRestartDelay has the same value.

Variables

View Source
var ErrRunTimeout = errors.New("worker: run timed out")

ErrRunTimeout is the cancellation cause of a run that exceeded its ScheduledConfig.RunTimeout budget; the root package exports it as credo.ErrWorkerRunTimeout. A run cut short by the timeout is recorded as a failure wrapping ErrRunTimeout, even when Run returns nil.

Functions

func ComponentName

func ComponentName(name string) string

ComponentName is the name of a worker's component, under which readiness, the lifecycle's reports and the loop's records name it.

func IsNilWorker

func IsNilWorker(w Worker) bool

IsNilWorker reports whether w is nil or an interface holding a nil value of a nilable kind.

func ValidateName

func ValidateName(call, name string)

ValidateName applies the worker name rules, panicking under call; the registry calls it before it reads the configuration, so a bad name is reported first. Names are never normalized, so the registered name is exactly the one every log line and snapshot reports. No prefix is reserved: health's reserved "credo." prefix applies to the full component name, which always starts with "worker:".

Types

type Component

type Component struct {
	// contains filtered or unexported fields
}

Component is a worker's lifecycle component, named "worker:<name>": its Start launches the loop and its Shutdown stops it. The App starts and stops it once, in its tier.

func NewComponent

func NewComponent(e *Engine, def *Definition, w Worker) *Component

NewComponent returns the component that runs w under def. w is nil for a run function or a worker constructor, whose worker the component's constructor attaches with SetWorker before Start. The loop's records carry component=worker:<name>.

func (*Component) Definition

func (c *Component) Definition() *Definition

Definition returns the worker's registration.

func (*Component) SetWorker

func (c *Component) SetWorker(w Worker)

SetWorker attaches the worker the component's constructor made, from a run function and its resolved parameters or from a worker constructor's value; the constructor calls it before Start.

func (*Component) Shutdown

func (c *Component) Shutdown(context.Context) error

Shutdown cancels the worker's context and returns when Run and the loop have returned — not at ctx's deadline: a Run that ignores cancellation is abandoned by the App, which keeps the components the worker depends on open. A worker that never started shuts down at once.

func (*Component) Snapshot

func (c *Component) Snapshot() Info

Snapshot returns the worker's live state.

func (*Component) Start

func (c *Component) Start(ctx context.Context) error

Start derives the worker's own context from context.WithoutCancel(ctx), with a cancel only Shutdown calls, launches the loop on one goroutine and returns.

type ContinuousConfig

type ContinuousConfig struct {
	// Restart is the restart policy after a failed run.
	Restart Restart
	// UnreadyWhenFailed reports the instance unready once the worker is
	// failed.
	UnreadyWhenFailed bool
}

ContinuousConfig is the engine's half of credo.ContinuousConfig: its tier is the root package's to resolve. Zero means the default in every field.

type Definition

type Definition struct {
	// contains filtered or unexported fields
}

Definition is the immutable registration of a worker: its identity, its kind and its resolved configuration.

func NewContinuous

func NewContinuous(call, name string, cfg ContinuousConfig) *Definition

NewContinuous validates name and cfg and returns the definition of a continuous worker; it panics, naming call (such as `Workers.Continuous("outbox-relay")`), on misuse.

func NewScheduled

func NewScheduled(call, name, expr string, cfg ScheduledConfig) *Definition

NewScheduled validates name, expr and cfg and returns the definition of a scheduled worker; it panics, naming call, on misuse.

func (*Definition) Continuous

func (d *Definition) Continuous() ContinuousConfig

Continuous returns the resolved configuration of a continuous worker.

func (*Definition) Kind

func (d *Definition) Kind() Kind

Kind returns the worker's kind.

func (*Definition) Name

func (d *Definition) Name() string

Name returns the registration name.

func (*Definition) Readies

func (d *Definition) Readies() bool

Readies reports whether the registration sets a readiness condition, so that its component answers Ready.

func (*Definition) Scheduled

func (d *Definition) Scheduled() ScheduledConfig

Scheduled returns the resolved configuration of a scheduled worker.

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine is what the loops of one registry share: the logger they write through and the restart jitter.

func NewEngine

func NewEngine(logger *slog.Logger) *Engine

NewEngine returns an engine whose loops log through logger, each scoped to its worker's component.

type Info

type Info struct {
	Name string
	Kind Kind
	// Schedule is the expression of a scheduled worker, as registered; empty
	// for a continuous worker.
	Schedule string
	// Continuous is the resolved configuration of a continuous worker; nil
	// for a scheduled one. Each snapshot holds its own copy.
	Continuous *ContinuousConfig
	// Scheduled is the resolved configuration of a scheduled worker; nil for
	// a continuous one. Each snapshot holds its own copy.
	Scheduled *ScheduledConfig

	Status Status
	// Restarts counts the restarts of a continuous worker that started.
	Restarts int64
	// ConsecutiveFailures counts the failed runs of a scheduled worker since
	// its last success.
	ConsecutiveFailures int64
	// LastStartedAt is the start time of the most recently admitted run.
	LastStartedAt time.Time
	// LastSucceededAt is the completion time of the last successful run of a
	// scheduled worker; always zero for a continuous worker.
	LastSucceededAt time.Time
	// 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
}

Info is a point-in-time snapshot of a worker: its identity, its resolved configuration and its live state. The root package converts it to credo.WorkerInfo, whose fields document these and which owns the JSON shape.

type Kind

type Kind string

Kind reports whether a worker runs continuously or on a schedule.

const (
	// KindContinuous is a worker whose Run lives until its component stops.
	KindContinuous Kind = "continuous"
	// KindScheduled is a worker that runs once per cron activation.
	KindScheduled Kind = "scheduled"
)

type ReadyComponent

type ReadyComponent struct{ *Component }

ReadyComponent is the component of a worker whose registration sets a readiness condition: the App plans Ready from the type, so a worker without one contributes nothing to readiness.

func (*ReadyComponent) Ready

func (c *ReadyComponent) Ready(context.Context) error

Ready evaluates the registration's readiness conditions against the runner's last state, in memory, without I/O.

type Restart

type Restart struct {
	Disabled bool
	Limit    int
	MinDelay time.Duration
	MaxDelay time.Duration
}

Restart is the engine's credo.RestartPolicy, whose fields document these.

type RunInfo

type RunInfo struct {
	// Worker is the registration name.
	Worker string
	// ID is the run's identifier, equal to the run_id of the engine'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. The root package converts it to credo.WorkerRun.

func CurrentRun

func CurrentRun(ctx context.Context) (RunInfo, bool)

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.

type Schedule

type Schedule struct {
	// contains filtered or unexported fields
}

Schedule represents a compiled cron schedule.

func ParseSchedule

func ParseSchedule(expr string) (*Schedule, error)

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.

func (*Schedule) Next

func (s *Schedule) Next(now time.Time) time.Time

Next returns the next fire time after now.

func (*Schedule) String

func (s *Schedule) String() string

String returns the original cron expression.

type ScheduledConfig

type ScheduledConfig struct {
	RunOnStart               bool
	RunTimeout               time.Duration
	MaxConsecutiveFailures   int
	UnreadyWhenFailed        bool
	UnreadyUntilFirstSuccess bool
	UnreadyAfterSuccessAge   time.Duration
}

ScheduledConfig is the engine's half of credo.ScheduledConfig, whose fields document these.

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 Worker

type Worker interface {
	// Run executes the worker's logic.
	Run(ctx context.Context) error
}

Worker is what the engine runs: the root package's credo.Worker has the same method set, so its values are Workers here without conversion.

Jump to

Keyboard shortcuts

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