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
- Variables
- func ComponentName(name string) string
- func IsNilWorker(w Worker) bool
- func ValidateName(call, name string)
- type Component
- type ContinuousConfig
- type Definition
- type Engine
- type Info
- type Kind
- type ReadyComponent
- type Restart
- type RunInfo
- type Schedule
- type ScheduledConfig
- type Status
- type Worker
Constants ¶
const DefaultMaxRestartDelay = time.Minute
DefaultMaxRestartDelay is the default cap on the restart delay of a continuous worker; credo.DefaultMaxRestartDelay has the same value.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
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) 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.
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 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.
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.
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 ¶
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" )