Documentation
¶
Overview ¶
Package runnerq is a durable activity queue and worker engine, with pluggable storage (PostgreSQL built in).
Activities run by priority and schedule, retry with exponential backoff and dead-letter when out of attempts. Handlers can checkpoint steps (Run, RunStep), sleep and wait for signals durably, and spawn and await child activities. The conductor package connects workers to a console.
backend, _ := postgres.New(ctx, "postgres://localhost/mydb", "my_app")
engine, _ := runnerq.Builder().
Backend(backend).
QueueName("my_app").
MaxWorkers(8).
Build()
engine.RegisterActivity(&SendEmail{}) // serves activity type "SendEmail"
engine.Start(ctx)
Index ¶
- Constants
- Variables
- func IsActivityNotFound(err error) bool
- func IsCancelled(err error) bool
- func IsCommandConflict(err error) bool
- func IsSignalTimeout(err error) bool
- func IsYield(err error) bool
- func NameOf[T any]() string
- func RunStep[R any](c ActivityContext, name string, fn Step[R]) (R, error)
- func SignalActivity(ctx context.Context, backend storage.Storage, activityID uuid.UUID, ...) error
- func SignalActivityByKey(ctx context.Context, backend storage.Storage, activityType string, ...) error
- func ValidTraceparent(s string) bool
- func WaitAll(ctx context.Context, futures ...*ActivityFuture) ([]json.RawMessage, error)
- type ActivityBuilder
- func (b *ActivityBuilder) AsRoot() *ActivityBuilder
- func (b *ActivityBuilder) Delay(d time.Duration) *ActivityBuilder
- func (b *ActivityBuilder) Execute(ctx context.Context) (*ActivityFuture, error)
- func (b *ActivityBuilder) IdempotencyKeyOption(key string, behavior OnDuplicate) *ActivityBuilder
- func (b *ActivityBuilder) MaxRetries(retries uint32) *ActivityBuilder
- func (b *ActivityBuilder) MaxRetryDelay(d time.Duration) *ActivityBuilder
- func (b *ActivityBuilder) Metadata(key, value string) *ActivityBuilder
- func (b *ActivityBuilder) MetadataMap(metadata map[string]string) *ActivityBuilder
- func (b *ActivityBuilder) Payload(payload json.RawMessage) *ActivityBuilder
- func (b *ActivityBuilder) Priority(p ActivityPriority) *ActivityBuilder
- func (b *ActivityBuilder) Step(name string) *ActivityBuilder
- func (b *ActivityBuilder) Timeout(d time.Duration) *ActivityBuilder
- type ActivityContext
- func (c ActivityContext) Run(name string, fn func() (json.RawMessage, error)) (json.RawMessage, error)
- func (c ActivityContext) RunStep[R any](name string, fn Step[R]) (R, error)
- func (c ActivityContext) Sleep(name string, d time.Duration) (err error)
- func (c ActivityContext) WaitForSignal(name string, timeout time.Duration) (payload json.RawMessage, err error)
- type ActivityError
- type ActivityExecutor
- type ActivityFuture
- type ActivityHandler
- type ActivityOption
- type ActivityPriority
- type ActivityStatus
- type Client
- func (c *Client) Activity[T any]() *ActivityBuilder
- func (c *Client) ActivityNamed(activityType string) *ActivityBuilder
- func (c *Client) Backend() storage.Storage
- func (c *Client) Cancel(ctx context.Context, target Target, opts ...CommandOption) (*CommandResult, error)
- func (c *Client) Delete(ctx context.Context, target Target, opts ...CommandOption) (*CommandResult, error)
- func (c *Client) Future(activityID uuid.UUID) *ActivityFuture
- func (c *Client) Get(ctx context.Context, activityID uuid.UUID) (*storage.ActivityRecord, error)
- func (c *Client) List(ctx context.Context, opts ListOptions) (*storage.ActivityRecordPage, error)
- func (c *Client) Reschedule(ctx context.Context, target Target, at time.Time, opts ...CommandOption) (*CommandResult, error)
- func (c *Client) Result(ctx context.Context, activityID uuid.UUID) (json.RawMessage, error)
- func (c *Client) Retry(ctx context.Context, target Target, opts ...CommandOption) (*CommandResult, error)
- func (c *Client) RunNow(ctx context.Context, target Target, opts ...CommandOption) (*CommandResult, error)
- func (c *Client) SetPriority(ctx context.Context, target Target, priority ActivityPriority, ...) (*CommandResult, error)
- func (c *Client) Signal(ctx context.Context, activityID uuid.UUID, name string, ...) error
- func (c *Client) SignalByKey(ctx context.Context, activityType, idempotencyKey, name string, ...) error
- type CommandItem
- type CommandOption
- type CommandOutcome
- type CommandResult
- type DefaultDeadLetterHandler
- type EndSpan
- type IdempotencyConfig
- type InFlightActivity
- type LabeledMetricsSink
- type ListOptions
- type MetricInfo
- type MetricKind
- type MetricLabels
- type MetricsSink
- type NoopMetrics
- type OnDuplicate
- type ResultState
- type RetentionConfig
- type RetryableError
- type Schedule
- type Schedules
- func (m *Schedules) Delete(ctx context.Context, name string) error
- func (m *Schedules) Get(ctx context.Context, name string) (*storage.Schedule, error)
- func (m *Schedules) List(ctx context.Context) ([]storage.Schedule, error)
- func (m *Schedules) Pause(ctx context.Context, name string) error
- func (m *Schedules) Resume(ctx context.Context, name string) error
- func (m *Schedules) Trigger(ctx context.Context, name string) (*ActivityFuture, error)
- func (m *Schedules) Upsert(ctx context.Context, s Schedule) error
- type Spawner
- type Step
- type Target
- type TraceAttribute
- type Tracer
- type WorkerConfig
- type WorkerEngine
- func (e *WorkerEngine) ActivityTypes() []string
- func (e *WorkerEngine) Announce(a executor.Announcer)
- func (e *WorkerEngine) Backend() storage.Storage
- func (e *WorkerEngine) Changed() <-chan struct{}
- func (e *WorkerEngine) Client() *Client
- func (e *WorkerEngine) Draining() bool
- func (e *WorkerEngine) GetActivityExecutor() *ActivityExecutor
- func (e *WorkerEngine) InFlight() []InFlightActivity
- func (e *WorkerEngine) InstanceID() string
- func (e *WorkerEngine) Interrupt(activityID uuid.UUID) bool
- func (e *WorkerEngine) MaxConcurrentActivities() int
- func (e *WorkerEngine) Observe(o executor.Observer)
- func (e *WorkerEngine) QueueName() string
- func (e *WorkerEngine) RegisterActivity(handler ActivityHandler)
- func (e *WorkerEngine) RegisterActivityWithName(activityType string, handler ActivityHandler)
- func (e *WorkerEngine) RegisterSchedule(s Schedule) error
- func (e *WorkerEngine) Schedules() *Schedules
- func (e *WorkerEngine) SetLabeledMetrics(sink LabeledMetricsSink)
- func (e *WorkerEngine) SetMetrics(sink MetricsSink)
- func (e *WorkerEngine) SetTracer(t Tracer)
- func (e *WorkerEngine) Signal(ctx context.Context, activityID uuid.UUID, name string, ...) error
- func (e *WorkerEngine) SignalByKey(ctx context.Context, activityType string, idempotencyKey string, name string, ...) error
- func (e *WorkerEngine) Snapshot() executor.Snapshot
- func (e *WorkerEngine) Start(ctx context.Context) error
- func (e *WorkerEngine) StartedAt() time.Time
- func (e *WorkerEngine) Stop()
- type WorkerEngineBuilder
- func (b *WorkerEngineBuilder) ActivityTypes(types []string) *WorkerEngineBuilder
- func (b *WorkerEngineBuilder) Backend(backend storage.Storage) *WorkerEngineBuilder
- func (b *WorkerEngineBuilder) Build() (*WorkerEngine, error)
- func (b *WorkerEngineBuilder) GaugeInterval(d time.Duration) *WorkerEngineBuilder
- func (b *WorkerEngineBuilder) LabeledMetrics(sink LabeledMetricsSink) *WorkerEngineBuilder
- func (b *WorkerEngineBuilder) MaxWorkers(max int) *WorkerEngineBuilder
- func (b *WorkerEngineBuilder) Metrics(sink MetricsSink) *WorkerEngineBuilder
- func (b *WorkerEngineBuilder) QueueName(name string) *WorkerEngineBuilder
- func (b *WorkerEngineBuilder) Retention(cfg RetentionConfig) *WorkerEngineBuilder
- func (b *WorkerEngineBuilder) SchedulePollInterval(interval time.Duration) *WorkerEngineBuilder
- func (b *WorkerEngineBuilder) ShutdownGrace(d time.Duration) *WorkerEngineBuilder
- func (b *WorkerEngineBuilder) Tracer(t Tracer) *WorkerEngineBuilder
- type WorkerError
- type WorkerErrorKind
Constants ¶
const ( // MetricActivityStarted is a counter ({attempt}): attempts claimed whose // handler started on this worker. MetricActivityStarted = "activity_started" // MetricActivityCompleted is a counter ({activity}): activities that // completed successfully on this worker. MetricActivityCompleted = "activity_completed" // MetricActivityCompletionError is a counter ({activity}): completions that // could not be recorded for a reason other than a lost claim: a permanent // storage error, or shutdown ended the retries. MetricActivityCompletionError = "activity_completion_error" // MetricActivityCompletionPendingStarted is a counter ({activity}): // completions whose recording started. Started minus finished is how many are // being recorded. MetricActivityCompletionPendingStarted = "activity_completion_pending_started" // MetricActivityCompletionPendingFinished is a counter ({activity}): // completions whose recording finished, successfully or not. MetricActivityCompletionPendingFinished = "activity_completion_pending_finished" // MetricActivityRetry is a counter ({attempt}): attempts that failed with a // retryable error (a timeout counts as activity_timeout instead). MetricActivityRetry = "activity_retry" // MetricActivityFailedNonRetry is a counter ({activity}): activities that // failed permanently with a non-retryable error. MetricActivityFailedNonRetry = "activity_failed_non_retry" // MetricActivityTimeout is a counter ({attempt}): attempts that exceeded the // activity's timeout. MetricActivityTimeout = "activity_timeout" // MetricActivityDeadLettered is a counter ({activity}): activities that ran // out of attempts and were dead-lettered. MetricActivityDeadLettered = "activity_dead_lettered" // MetricActivityDeadLetterHookPanic is a counter ({activity}): dead-letter // hooks that threw or panicked (the failure is recovered and logged). Only // SDKs with a dead-letter hook emit it. MetricActivityDeadLetterHookPanic = "activity_dead_letter_hook_panic" // MetricActivityClaimLost is a counter ({attempt}): attempts that lost their // claim: revoked mid-handler, or the outcome was fenced off because another // execution owns the activity. MetricActivityClaimLost = "activity_claim_lost" // MetricActivityHeartbeatFailed is a counter ({renewal}): claim renewals that // failed and will be retried on the next beat. MetricActivityHeartbeatFailed = "activity_heartbeat_failed" // MetricActivityYielded is a counter ({attempt}): attempts that parked the // activity for a durable wait (sleep, signal or awaited result). MetricActivityYielded = "activity_yielded" // MetricActivityTreesSwept is a counter ({tree}): terminal workflow trees // deleted by retention. MetricActivityTreesSwept = "activity_trees_swept" // MetricStorageRetry is a counter ({retry}): storage writes made for an // attempt (completion, failure, park, checkpoint, spawn) that failed // transiently and are being retried. MetricStorageRetry = "storage_retry" // MetricActivityClaimLag is a histogram (s): how long an activity waited from // when it was due until a worker started it. MetricActivityClaimLag = "activity_claim_lag" // MetricActivityExecution is a histogram (s): how long an attempt took on // this worker, from its start until its outcome was recorded. MetricActivityExecution = "activity_execution" // MetricActivityCompletionPersistence is a histogram (s): how long recording // a completion took, retries included. MetricActivityCompletionPersistence = "activity_completion_persistence" // MetricQueueDepth is a gauge ({activity}): activities in the queue by // status, for the statuses listed under the status label. Sampled from the // storage's aggregate query; a combination that has dropped to zero is // reported as 0. MetricQueueDepth = "queue_depth" // MetricQueueOldestPendingAge is a gauge (s): how long the oldest pending // (due, unclaimed) activity has been due; 0 when none is pending. Sampled // with queue_depth. MetricQueueOldestPendingAge = "queue_oldest_pending_age" // MetricActivitiesInFlight is a gauge ({activity}): attempts running on this // worker now, for every activity type it serves. MetricActivitiesInFlight = "activities_in_flight" )
Metric names (runnerq-spec observability/metrics.json).
const ( // LabelQueue: The queue the worker serves. LabelQueue = "queue" // LabelActivityType: The activity's persisted type name. LabelActivityType = "activity_type" // LabelStatus: A canonical activity status (vectors/canonical_status.json): // pending, scheduled, running, waiting or dead_letter. LabelStatus = "status" )
Metric label names.
const ( // SpanEnqueue (producer): One enqueue, ended once the insert commits (or // failed). Its context is the traceparent stored with the activity. A child // activity's enqueue is a child of the step or attempt that spawned it. SpanEnqueue = "runnerq.enqueue" // SpanAttempt (consumer): One attempt, from claim until its outcome is // recorded. Its parent is the activity's stored traceparent, so retries and // the attempts that resume after a durable sleep or signal wait share the // enqueue span as parent: one connected trace. With no stored traceparent it // starts a new trace. SpanAttempt = "runnerq.attempt" // SpanStep (internal): One checkpointed step that runs its function, a child // of the attempt. A replayed step (its stored result returned) starts no // span. SpanStep = "runnerq.step" // SpanSleep (internal): A durable sleep reached by an attempt, a child of the // attempt. It ends when the sleep returns (elapsed) or parks the activity // (parked); the attempt that resumes after the wake reaches it again and ends // it elapsed. SpanSleep = "runnerq.sleep" // SpanSignalWait (internal): A wait for a named signal, a child of the // attempt; like sleep, a parked wait is reached again by the resuming // attempt. SpanSignalWait = "runnerq.signal.wait" // SpanSignalSend (producer): Delivering a signal to an activity, in the // sender's trace; activity_id is the target. SpanSignalSend = "runnerq.signal.send" )
Span names (runnerq-spec observability/tracing.json).
const ( // AttrQueue (string): The queue. AttrQueue = "runnerq.queue" // AttrActivityType (string): The activity's persisted type name. AttrActivityType = "runnerq.activity.type" // AttrActivityID (string): The activity's id; on an enqueue that found an // existing activity under its idempotency key, the existing one's. AttrActivityID = "runnerq.activity.id" // AttrParentID (string): The parent activity's id; absent for a root. AttrParentID = "runnerq.activity.parent_id" // AttrRootID (string): The root activity's id. AttrRootID = "runnerq.activity.root_id" // AttrAttempt (int): The attempt number, from 1. AttrAttempt = "runnerq.attempt" // AttrStepName (string): The step's name as the handler gave it. AttrStepName = "runnerq.step.name" // AttrSignalName (string): The signal's name. AttrSignalName = "runnerq.signal.name" // AttrWakeAt (string): When a sleep wakes, RFC 3339 in UTC. AttrWakeAt = "runnerq.wake_at" // AttrOutcome (string): How the span ended: one of the span's outcomes. error // is an unexpected failure, such as storage; a tracer marks the span as an // error whenever the SDK passes one, whatever the outcome (a retry or a dead // letter carries the handler's error). AttrOutcome = "runnerq.outcome" )
Span attribute keys.
const ( OutcomeEnqueued = "enqueued" OutcomeExisting = "existing" OutcomeError = "error" OutcomeCompleted = "completed" OutcomeRetry = "retry" OutcomeFailed = "failed" OutcomeTimeout = "timeout" OutcomeDeadLetter = "dead_letter" OutcomeYielded = "yielded" OutcomeClaimLost = "claim_lost" OutcomeOk = "ok" OutcomeElapsed = "elapsed" OutcomeParked = "parked" OutcomeReceived = "received" OutcomeSent = "sent" )
Span outcomes, the values of AttrOutcome.
const DefaultMaxActivityDepth uint16 = 32
DefaultMaxActivityDepth is MaxActivityDepth's default.
const MetadataTraceparent = "traceparent"
MetadataTraceparent is the activity metadata key holding a W3C trace context traceparent (https://www.w3.org/TR/trace-context/), written at enqueue under the rule of vectors/traceparent.json. An attempt continues it: the attempt span's parent is the span it names.
Variables ¶
var MetricCatalog = []MetricInfo{ {Name: MetricActivityStarted, Kind: MetricCounter, Unit: "{attempt}", Labels: []string{LabelQueue, LabelActivityType}, Description: "Attempts claimed whose handler started on this worker."}, {Name: MetricActivityCompleted, Kind: MetricCounter, Unit: "{activity}", Labels: []string{LabelQueue, LabelActivityType}, Description: "Activities that completed successfully on this worker."}, {Name: MetricActivityCompletionError, Kind: MetricCounter, Unit: "{activity}", Labels: []string{LabelQueue, LabelActivityType}, Description: "Completions that could not be recorded for a reason other than a lost claim: a permanent storage error, or shutdown ended the retries."}, {Name: MetricActivityCompletionPendingStarted, Kind: MetricCounter, Unit: "{activity}", Labels: []string{LabelQueue, LabelActivityType}, Description: "Completions whose recording started. Started minus finished is how many are being recorded."}, {Name: MetricActivityCompletionPendingFinished, Kind: MetricCounter, Unit: "{activity}", Labels: []string{LabelQueue, LabelActivityType}, Description: "Completions whose recording finished, successfully or not."}, {Name: MetricActivityRetry, Kind: MetricCounter, Unit: "{attempt}", Labels: []string{LabelQueue, LabelActivityType}, Description: "Attempts that failed with a retryable error (a timeout counts as activity_timeout instead)."}, {Name: MetricActivityFailedNonRetry, Kind: MetricCounter, Unit: "{activity}", Labels: []string{LabelQueue, LabelActivityType}, Description: "Activities that failed permanently with a non-retryable error."}, {Name: MetricActivityTimeout, Kind: MetricCounter, Unit: "{attempt}", Labels: []string{LabelQueue, LabelActivityType}, Description: "Attempts that exceeded the activity's timeout."}, {Name: MetricActivityDeadLettered, Kind: MetricCounter, Unit: "{activity}", Labels: []string{LabelQueue, LabelActivityType}, Description: "Activities that ran out of attempts and were dead-lettered."}, {Name: MetricActivityDeadLetterHookPanic, Kind: MetricCounter, Unit: "{activity}", Labels: []string{LabelQueue, LabelActivityType}, Description: "Dead-letter hooks that threw or panicked (the failure is recovered and logged). Only SDKs with a dead-letter hook emit it."}, {Name: MetricActivityClaimLost, Kind: MetricCounter, Unit: "{attempt}", Labels: []string{LabelQueue, LabelActivityType}, Description: "Attempts that lost their claim: revoked mid-handler, or the outcome was fenced off because another execution owns the activity."}, {Name: MetricActivityHeartbeatFailed, Kind: MetricCounter, Unit: "{renewal}", Labels: []string{LabelQueue, LabelActivityType}, Description: "Claim renewals that failed and will be retried on the next beat."}, {Name: MetricActivityYielded, Kind: MetricCounter, Unit: "{attempt}", Labels: []string{LabelQueue, LabelActivityType}, Description: "Attempts that parked the activity for a durable wait (sleep, signal or awaited result)."}, {Name: MetricActivityTreesSwept, Kind: MetricCounter, Unit: "{tree}", Labels: []string{LabelQueue}, Description: "Terminal workflow trees deleted by retention."}, {Name: MetricStorageRetry, Kind: MetricCounter, Unit: "{retry}", Labels: []string{LabelQueue, LabelActivityType}, Description: "Storage writes made for an attempt (completion, failure, park, checkpoint, spawn) that failed transiently and are being retried."}, {Name: MetricActivityClaimLag, Kind: MetricHistogram, Unit: "s", Labels: []string{LabelQueue, LabelActivityType}, Description: "How long an activity waited from when it was due until a worker started it."}, {Name: MetricActivityExecution, Kind: MetricHistogram, Unit: "s", Labels: []string{LabelQueue, LabelActivityType}, Description: "How long an attempt took on this worker, from its start until its outcome was recorded."}, {Name: MetricActivityCompletionPersistence, Kind: MetricHistogram, Unit: "s", Labels: []string{LabelQueue, LabelActivityType}, Description: "How long recording a completion took, retries included."}, {Name: MetricQueueDepth, Kind: MetricGauge, Unit: "{activity}", Labels: []string{LabelQueue, LabelActivityType, LabelStatus}, Description: "Activities in the queue by status, for the statuses listed under the status label. Sampled from the storage's aggregate query; a combination that has dropped to zero is reported as 0."}, {Name: MetricQueueOldestPendingAge, Kind: MetricGauge, Unit: "s", Labels: []string{LabelQueue}, Description: "How long the oldest pending (due, unclaimed) activity has been due; 0 when none is pending. Sampled with queue_depth."}, {Name: MetricActivitiesInFlight, Kind: MetricGauge, Unit: "{activity}", Labels: []string{LabelQueue, LabelActivityType}, Description: "Attempts running on this worker now, for every activity type it serves."}, }
MetricCatalog lists every metric the SDK emits, in the spec's order.
Functions ¶
func IsActivityNotFound ¶
IsActivityNotFound reports whether err is a signal to, or Client.Get of, an activity that doesn't exist; signal deliverers usually treat it as already settled.
func IsCancelled ¶
IsCancelled reports whether err is an awaited activity's cancellation (Client.Cancel), as GetResult and Client.Result return it.
func IsCommandConflict ¶
IsCommandConflict reports whether err is a management command rejected because its command id (WithCommandID) was already used with other input.
func IsSignalTimeout ¶
IsSignalTimeout reports whether err is a WaitForSignal timeout.
func IsYield ¶
IsYield reports whether err is the sentinel a durable wait (Sleep, WaitForSignal, or GetResult on a handler's context) returns to park the activity. Code between the wait and the handler must return it unchanged (or wrapped with %w) rather than treat it as a failure.
func NameOf ¶
NameOf returns the activity type RegisterActivity and ActivityExecutor.Activity derive from T, for APIs that take it as a string:
engine.RegisterActivity(&ResizeImage{})
runnerq.Builder().ActivityTypes([]string{runnerq.NameOf[ResizeImage]()})
engine.SignalByKey(ctx, runnerq.NameOf[ResizeImage](), key, "approved", p)
T may be the handler struct or a pointer to it. NameOf panics for unnamed types, and knows nothing of names pinned with RegisterActivityWithName.
func RunStep ¶
func RunStep[R any](c ActivityContext, name string, fn Step[R]) (R, error)
RunStep is the typed form of ActivityContext.Run: fn's result is stored as JSON and a replaying attempt decodes it into R, so R must round-trip through encoding/json. Semantics and step-name rules are Run's.
receipt, err := runnerq.RunStep(ctx, "charge", func(c context.Context) (Receipt, error) {
return payments.Charge(c, orderID, amount)
})
A stored result that no longer decodes into R (the type changed between deploys) is a NonRetryError. So is an encode failure, which is stored as a permanent step failure because the side effect has already happened.
On Go 1.27 and later, ctx.RunStep(name, fn) is the same call as a method.
func SignalActivity ¶
func SignalActivity(ctx context.Context, backend storage.Storage, activityID uuid.UUID, name string, payload json.RawMessage) error
SignalActivity delivers a signal to an activity from any process sharing the database; no engine is needed, only a backend. The payload (nil is fine) is stored even if the activity hasn't reached its WaitForSignal yet, and a parked waiter wakes at once. A repeated signal overwrites the payload. It fails with IsActivityNotFound when the activity doesn't exist.
func SignalActivityByKey ¶
func SignalActivityByKey(ctx context.Context, backend storage.Storage, activityType string, idempotencyKey string, name string, payload json.RawMessage) error
SignalActivityByKey delivers a signal to the activity that owns idempotencyKey (as given to IdempotencyKeyOption) for activityType, so a webhook can wake a workflow by its business key. Keys are scoped per type, hence the type. It fails with IsActivityNotFound when no activity owns the key (never enqueued, or swept by retention).
Resolving the key and delivering are separate steps: under AllowReuse or AllowReuseOnFailure a key repointed in between sends the signal to its new owner.
func ValidTraceparent ¶
ValidTraceparent reports whether s is a W3C trace context traceparent this SDK continues: lowercase hex version (not ff), a non-zero 32-digit trace id, a non-zero 16-digit parent id and flags; version 00 has nothing after them.
func WaitAll ¶
func WaitAll(ctx context.Context, futures ...*ActivityFuture) ([]json.RawMessage, error)
WaitAll awaits every future and returns their results in order. Inside a handler the first pending child parks the parent and completed children fast-forward on replay, so awaiting in sequence costs nothing extra. Propagate the error unchanged, as with GetResult.
Types ¶
type ActivityBuilder ¶
type ActivityBuilder struct {
// contains filtered or unexported fields
}
ActivityBuilder configures one spawn; Execute enqueues it.
func Activity ¶
func Activity[T any](w Spawner) *ActivityBuilder
Activity starts a spawn on w of the activity served by handler type T, as registered with RegisterActivity, so the two cannot drift:
fut, err := runnerq.Activity[ResizeImage](ctx.ActivityExecutor).Payload(p).Execute(ctx.Ctx)
T may be the handler struct or a pointer to it. Handlers registered under a pinned name (RegisterActivityWithName) are spawned with ActivityExecutor.ActivityNamed.
From a Client, it submits a root activity:
fut, err := runnerq.Activity[ResizeImage](client).Payload(p).Execute(ctx)
On Go 1.27 and later, w.Activity[T]() is the same call as a method.
func (*ActivityBuilder) AsRoot ¶
func (b *ActivityBuilder) AsRoot() *ActivityBuilder
AsRoot makes the spawn a root (no parent, depth 0) even inside a handler or on its context, for side jobs whose lifecycle is independent of the parent.
func (*ActivityBuilder) Delay ¶
func (b *ActivityBuilder) Delay(d time.Duration) *ActivityBuilder
Delay schedules the activity to run after d.
func (*ActivityBuilder) Execute ¶
func (b *ActivityBuilder) Execute(ctx context.Context) (*ActivityFuture, error)
Execute enqueues the activity and returns its future.
func (*ActivityBuilder) IdempotencyKeyOption ¶
func (b *ActivityBuilder) IdempotencyKeyOption(key string, behavior OnDuplicate) *ActivityBuilder
IdempotencyKeyOption sets an idempotency key, scoped to the activity type, and what to do when it is taken.
func (*ActivityBuilder) MaxRetries ¶
func (b *ActivityBuilder) MaxRetries(retries uint32) *ActivityBuilder
MaxRetries sets the total attempts allowed, including the first (default 3): 1 means no retries, 0 unlimited. The name is kept for compatibility.
func (*ActivityBuilder) MaxRetryDelay ¶
func (b *ActivityBuilder) MaxRetryDelay(d time.Duration) *ActivityBuilder
MaxRetryDelay caps the backoff between retries (default 1 hour, at least 1s); a non-positive duration is ignored.
func (*ActivityBuilder) Metadata ¶
func (b *ActivityBuilder) Metadata(key, value string) *ActivityBuilder
Metadata sets one metadata key.
func (*ActivityBuilder) MetadataMap ¶
func (b *ActivityBuilder) MetadataMap(metadata map[string]string) *ActivityBuilder
MetadataMap merges metadata into what is already set.
func (*ActivityBuilder) Payload ¶
func (b *ActivityBuilder) Payload(payload json.RawMessage) *ActivityBuilder
Payload sets the JSON payload; required.
func (*ActivityBuilder) Priority ¶
func (b *ActivityBuilder) Priority(p ActivityPriority) *ActivityBuilder
Priority sets the priority (default PriorityNormal).
func (*ActivityBuilder) Step ¶
func (b *ActivityBuilder) Step(name string) *ActivityBuilder
Step makes this spawn a named, memoized step of the calling handler: its idempotency key derives from (root, parent, name) with ReturnExisting, so a retried parent gets the same child back, and its stored result if it has completed.
Step names must be stable across retries and unique among the parent's spawns (two spawns sharing a name resolve to one child). Only valid inside a handler (its ActivityExecutor, or any executor of its queue on its context); incompatible with AsRoot and IdempotencyKeyOption.
func (*ActivityBuilder) Timeout ¶
func (b *ActivityBuilder) Timeout(d time.Duration) *ActivityBuilder
Timeout bounds one attempt (default 5 minutes).
type ActivityContext ¶
type ActivityContext struct {
ActivityID uuid.UUID
ActivityType string
// RetryCount is the attempt number minus one (0 on the first attempt).
RetryCount uint32
Metadata map[string]string
// Ctx ends at the activity's timeout, and earlier if this execution loses
// its claim to another worker; context.Cause(Ctx) is then a storage
// ErrClaimLost error. Handlers must stop when it ends: the engine cannot
// interrupt one that ignores it, and its side effects would overlap the
// replacement execution's.
Ctx context.Context
// ActivityExecutor spawns children of this activity.
ActivityExecutor *ActivityExecutor
ParentActivityID *uuid.UUID // nil for a root
RootActivityID uuid.UUID // ActivityID for a root
Depth uint16 // 0 for a root
// contains filtered or unexported fields
}
ActivityContext is what a handler gets about the activity it runs.
func (ActivityContext) Run ¶
func (c ActivityContext) Run(name string, fn func() (json.RawMessage, error)) (json.RawMessage, error)
Run executes fn as a named, checkpointed step: a retried handler reaching the same step gets the stored outcome without re-running fn. Use it for side effects that must not repeat across retries (payments, emails).
- success: the result is stored and returned by later attempts.
- NonRetryError: the failure is stored and returned by later attempts.
- retryable error: nothing is stored; fn runs again next attempt.
- a crash after fn but before the result commits: fn runs again. Make fn as idempotent as the external system allows (e.g. pass it an idempotency key).
Step names must be stable across retries and unique within the handler.
func (ActivityContext) RunStep ¶
func (c ActivityContext) RunStep[R any](name string, fn Step[R]) (R, error)
RunStep is the method form of the package function RunStep:
receipt, err := ctx.RunStep("charge", func(c context.Context) (Receipt, error) {
return payments.Charge(c, orderID, amount)
})
func (ActivityContext) Sleep ¶
func (c ActivityContext) Sleep(name string, d time.Duration) (err error)
Sleep is a durable timer: the wake time is stored on first execution, so a handler that crashes or is redeployed mid-sleep waits only the remainder, and a replay past it returns at once.
A wait that fits in the activity's timeout happens in-process. Otherwise Sleep YIELDS: it returns a sentinel error the caller MUST propagate unchanged, the activity is parked until the wake time without consuming a retry, and the handler then replays (earlier checkpoints fast-forward) to a Sleep that returns nil.
Step names must be stable across retries and unique within the handler.
func (ActivityContext) WaitForSignal ¶
func (c ActivityContext) WaitForSignal(name string, timeout time.Duration) (payload json.RawMessage, err error)
WaitForSignal waits for the signal named name to be delivered to this activity (WorkerEngine.Signal or SignalActivity, from any process sharing the database) and returns its payload. timeout runs from the first attempt to reach this call, not from each replay; 0 waits forever. On timeout it returns a non-retryable error (IsSignalTimeout).
Signals are buffered: one delivered earlier, even before the activity started, is returned at once. A repeated signal overwrites the payload.
Like Sleep, a wait that doesn't fit the timeout YIELDS: propagate the sentinel error unchanged. Signal names must be stable across retries and unique within the handler.
type ActivityError ¶
ActivityError is a handler error that says whether to retry.
func NewNonRetryError ¶
func NewNonRetryError(msg string) *ActivityError
NewNonRetryError returns an error that fails the activity for good.
func NewRetryError ¶
func NewRetryError(msg string) *ActivityError
NewRetryError returns an error that retries the activity.
func (*ActivityError) Error ¶
func (e *ActivityError) Error() string
func (*ActivityError) IsRetryable ¶
func (e *ActivityError) IsRetryable() bool
type ActivityExecutor ¶
type ActivityExecutor struct {
// contains filtered or unexported fields
}
ActivityExecutor spawns activities. An ActivityContext's spawns children of the running activity, fenced on the handler's claim so a superseded execution can't spawn. The engine's (GetActivityExecutor) spawns roots, except on a handler's context (ActivityContext.Ctx or one derived from it), where it records the spawn as a child of that handler's activity, so code a handler calls needn't be handed its executor; those spawns are not fenced and cost what a root spawn does. AsRoot opts out. Name the target with Activity or ActivityNamed.
func (*ActivityExecutor) Activity ¶
func (w *ActivityExecutor) Activity[T any]() *ActivityBuilder
Activity is the method form of the package function Activity:
fut, err := ctx.ActivityExecutor.Activity[ResizeImage]().Payload(p).Execute(ctx.Ctx)
func (*ActivityExecutor) ActivityNamed ¶
func (w *ActivityExecutor) ActivityNamed(activityType string) *ActivityBuilder
ActivityNamed starts a spawn of activityType by name: for handlers registered with RegisterActivityWithName, and for producers that never see the handler type.
type ActivityFuture ¶
type ActivityFuture struct {
// contains filtered or unexported fields
}
ActivityFuture is an activity's result, to be awaited with GetResult.
func FutureFor ¶
func FutureFor(backend storage.Storage, activityID uuid.UUID) *ActivityFuture
FutureFor rebuilds a future from an activity ID, in any process holding a backend for the same queue.
func (*ActivityFuture) ActivityID ¶
func (f *ActivityFuture) ActivityID() uuid.UUID
ActivityID is the awaited activity's ID; another process can rebuild the future from it with FutureFor.
func (*ActivityFuture) GetResult ¶
func (f *ActivityFuture) GetResult(ctx context.Context) (json.RawMessage, error)
GetResult waits for the activity's result, notified by the backend where it can (Postgres can, across processes).
Inside a handler it waits briefly, then YIELDS: it returns a sentinel error that MUST be propagated unchanged (as with Sleep and WaitForSignal), and the parent is parked, holding no goroutine, lease or retry, until the child's completion wakes it. The handler then replays, earlier checkpoints fast-forward, and this call returns the result.
Outside a handler it blocks until the result exists or ctx is done.
type ActivityHandler ¶
type ActivityHandler interface {
// Handle runs one attempt. It returns (result, nil) on success (result
// may be nil), a NonRetryError to fail for good, or any other error to
// retry.
Handle(ctx ActivityContext, payload json.RawMessage) (json.RawMessage, error)
// OnDeadLetter is called when an attempt fails for the last time; embed
// DefaultDeadLetterHandler for a no-op.
OnDeadLetter(ctx ActivityContext, payload json.RawMessage, errorMsg string)
}
ActivityHandler runs activities of the type it is registered under (RegisterActivity, RegisterActivityWithName). It must be safe for concurrent use.
type ActivityOption ¶
type ActivityOption struct {
Priority *ActivityPriority
MaxRetries uint32
TimeoutSeconds uint64
MaxRetryDelaySeconds *uint64
DelaySeconds *uint64
IdempotencyKey *IdempotencyConfig
Metadata map[string]string
}
type ActivityPriority ¶
type ActivityPriority int
ActivityPriority orders execution: higher priorities are claimed first.
const ( PriorityLow ActivityPriority = 1 PriorityNormal ActivityPriority = 2 PriorityHigh ActivityPriority = 3 PriorityCritical ActivityPriority = 4 )
func (ActivityPriority) MarshalJSON ¶
func (p ActivityPriority) MarshalJSON() ([]byte, error)
func (ActivityPriority) String ¶
func (p ActivityPriority) String() string
func (*ActivityPriority) UnmarshalJSON ¶
func (p *ActivityPriority) UnmarshalJSON(data []byte) error
type ActivityStatus ¶
type ActivityStatus string
ActivityStatus is an activity's status as Client reports it (the canonical statuses every backend maps onto): a retry waiting for its backoff is scheduled, and a claimed activity is running.
const ( StatusPending ActivityStatus = storage.RecordStatusPending StatusScheduled ActivityStatus = storage.RecordStatusScheduled StatusRunning ActivityStatus = storage.RecordStatusRunning StatusWaiting ActivityStatus = storage.RecordStatusWaiting StatusCompleted ActivityStatus = storage.RecordStatusCompleted StatusFailed ActivityStatus = storage.RecordStatusFailed StatusDeadLetter ActivityStatus = storage.RecordStatusDeadLetter StatusCancelled ActivityStatus = storage.RecordStatusCancelled )
func (ActivityStatus) Finished ¶
func (s ActivityStatus) Finished() bool
Finished reports whether s is terminal: completed, failed, dead_letter or cancelled.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client submits, signals, awaits, inspects and manages activities. It needs only a backend, no running engine, so any process sharing the database can use it: a web handler, a CLI, a cron job. WorkerEngine.Client returns one bound to the engine.
client := runnerq.NewClient(backend) fut, _ := runnerq.Activity[SendEmail](client).Payload(p).Execute(ctx) res, _ := client.Cancel(ctx, runnerq.IDs(fut.ActivityID()))
Management commands (Cancel, Retry, RunNow, Reschedule, SetPriority, Delete) need a backend implementing storage.CommandStorage, and Get and List one implementing storage.QueryStorage; the Postgres backend implements both. All of them act on the backend's own queue.
func (*Client) Activity ¶
func (c *Client) Activity[T any]() *ActivityBuilder
Activity starts a submission of the activity served by handler type T; the same call as Activity[T](c).
func (*Client) ActivityNamed ¶
func (c *Client) ActivityNamed(activityType string) *ActivityBuilder
ActivityNamed starts a submission of activityType by name.
func (*Client) Cancel ¶
func (c *Client) Cancel(ctx context.Context, target Target, opts ...CommandOption) (*CommandResult, error)
Cancel cancels unfinished activities and, unless NoCascade, their unfinished descendants. Each stores a cancellation error as its result, so awaiting parents and Result callers see IsCancelled. A running handler's context is cancelled promptly, on whichever worker holds it.
func (*Client) Delete ¶
func (c *Client) Delete(ctx context.Context, target Target, opts ...CommandOption) (*CommandResult, error)
Delete removes finished root activities with their whole tree: children, events, results and idempotency keys. Children can't be deleted alone, and an unfinished tree must be cancelled first.
func (*Client) Future ¶
func (c *Client) Future(activityID uuid.UUID) *ActivityFuture
Future returns the future of an activity submitted earlier, here or in another process.
func (*Client) Get ¶
Get returns an activity with its payload, result and last error. It fails with IsActivityNotFound when the queue has no such activity.
func (*Client) List ¶
func (c *Client) List(ctx context.Context, opts ListOptions) (*storage.ActivityRecordPage, error)
List returns a page of the queue's activities.
func (*Client) Reschedule ¶
func (c *Client) Reschedule(ctx context.Context, target Target, at time.Time, opts ...CommandOption) (*CommandResult, error)
Reschedule moves scheduled activities to run at at.
func (*Client) Result ¶
Result waits for the activity's result (ActivityFuture.GetResult). A cancelled activity's result is an error for which IsCancelled is true.
func (*Client) Retry ¶
func (c *Client) Retry(ctx context.Context, target Target, opts ...CommandOption) (*CommandResult, error)
Retry makes failed, dead-lettered or cancelled activities pending again. Completed steps replay from their checkpoints. Pass ResetAttempts to restore the full attempt budget.
func (*Client) RunNow ¶
func (c *Client) RunNow(ctx context.Context, target Target, opts ...CommandOption) (*CommandResult, error)
RunNow makes scheduled activities (delayed, or waiting out a retry backoff) and waiting ones (parked on a sleep, signal or child) runnable now. A woken waiter replays its handler and parks again if what it waits for isn't there.
func (*Client) SetPriority ¶
func (c *Client) SetPriority(ctx context.Context, target Target, priority ActivityPriority, opts ...CommandOption) (*CommandResult, error)
SetPriority changes unfinished activities' priority.
func (*Client) Signal ¶
func (c *Client) Signal(ctx context.Context, activityID uuid.UUID, name string, payload json.RawMessage) error
Signal delivers a signal to an activity (SignalActivity).
func (*Client) SignalByKey ¶
func (c *Client) SignalByKey(ctx context.Context, activityType, idempotencyKey, name string, payload json.RawMessage) error
SignalByKey delivers a signal to the activity of activityType that owns idempotencyKey (SignalActivityByKey).
type CommandItem ¶
type CommandItem struct {
ID uuid.UUID
Outcome CommandOutcome
// Status is the activity's status after the command (its current one
// when not eligible); empty when deleted or not found.
Status ActivityStatus
// Reason says why the command didn't apply.
Reason string
}
CommandItem is a command's outcome for one activity.
type CommandOption ¶
type CommandOption func(*commandConfig)
CommandOption configures a management command.
func DryRun ¶
func DryRun() CommandOption
DryRun reports what the command would do (outcome WouldApply) and changes nothing.
func NoCascade ¶
func NoCascade() CommandOption
NoCascade cancels only the targets, leaving their unfinished descendants running (Cancel only). By default a cancel cancels the whole subtree.
func ResetAttempts ¶
func ResetAttempts() CommandOption
ResetAttempts gives a retried activity its full attempt budget again (Retry only). By default it keeps the attempts it used.
func WithCommandID ¶
func WithCommandID(id string) CommandOption
WithCommandID makes the command idempotent under id: sending the same command again with it (a retry after a timeout, say) replays the first result, reported with Replayed set, for at least 24 hours. The same id with different input fails (IsCommandConflict). Without it each call gets a fresh id.
func WithReason ¶
func WithReason(reason string) CommandOption
WithReason records why, in each activity's history (and a cancelled activity's error).
type CommandOutcome ¶
type CommandOutcome string
CommandOutcome is what a command did to one target.
const ( // Applied: the command changed the activity. Applied CommandOutcome = "applied" // WouldApply: a dry run would have changed it. WouldApply CommandOutcome = "would_apply" // NotEligible: the activity's status doesn't allow the command (cancel // of a finished activity, retry of one that didn't fail, ...). NotEligible CommandOutcome = "not_eligible" // NotFound: the queue has no such activity. NotFound CommandOutcome = "not_found" )
type CommandResult ¶
type CommandResult struct {
// CommandID is the command's id: WithCommandID's, or a generated one.
CommandID string
// Items has one entry per target activity: per id given, in order, or
// per activity a filter selected.
Items []CommandItem
// Applied counts the activities the command changed.
Applied int
// Cascaded counts descendants a cancel also cancelled.
Cascaded int
// More is true when a filter matched more than Max activities.
More bool
// Replayed is true when the result is the recorded one of an earlier
// call with the same command id; nothing was applied this time.
Replayed bool
}
CommandResult is a command's outcome.
func (*CommandResult) Item ¶
func (r *CommandResult) Item(id uuid.UUID) (CommandItem, bool)
Item returns the outcome for id.
type DefaultDeadLetterHandler ¶
type DefaultDeadLetterHandler struct{}
DefaultDeadLetterHandler is a no-op OnDeadLetter to embed in handlers.
func (DefaultDeadLetterHandler) OnDeadLetter ¶
func (DefaultDeadLetterHandler) OnDeadLetter(_ ActivityContext, _ json.RawMessage, _ string)
type EndSpan ¶
type EndSpan func(outcome string, err error, attrs ...TraceAttribute)
EndSpan ends a span with its outcome (an Outcome* constant), the error that caused it if any, and attributes learnt meanwhile.
type IdempotencyConfig ¶
type IdempotencyConfig struct {
Key string
Behavior OnDuplicate
}
type InFlightActivity ¶
InFlightActivity is an activity the engine is executing.
type LabeledMetricsSink ¶
type LabeledMetricsSink interface {
// AddCounter adds value to a counter.
AddCounter(name string, value uint64, labels MetricLabels)
// RecordHistogram records one observation in the metric's unit (seconds
// for durations).
RecordHistogram(name string, value float64, labels MetricLabels)
// SetGauge sets a gauge's current value for these labels.
SetGauge(name string, value float64, labels MetricLabels)
}
LabeledMetricsSink receives every metric of MetricCatalog with its labels, named by the Metric* constants. Methods are called from the engine's hot paths and many goroutines: they must be safe for concurrent use and must not block.
func UnlabeledMetrics ¶
func UnlabeledMetrics(sink MetricsSink) LabeledMetricsSink
UnlabeledMetrics adapts a MetricsSink to LabeledMetricsSink: counters and histograms arrive without their labels, histograms through ObserveDuration, and gauges are dropped.
type ListOptions ¶
type ListOptions struct {
// Statuses keeps activities in any of these statuses.
Statuses []ActivityStatus
// Type keeps activities of this type.
Type string
// RootsOnly leaves out child activities.
RootsOnly bool
// Filter adds conditions in the query model (storage.QueryFilter).
Filter *storage.QueryFilter
// Sort orders the page; nil is newest first.
Sort *storage.QuerySort
// Include fetches heavy fields, left out by default.
Include storage.RecordInclude
// Limit is the page size: 0 is 50, at most 1000.
Limit int
// Cursor continues from a previous page's NextCursor.
Cursor string
}
ListOptions selects and orders the activities List returns. The zero value lists the newest 50 of every status.
type MetricInfo ¶
type MetricInfo struct {
Name string
Kind MetricKind
// Unit is UCUM: "s" for seconds, "{activity}" for a count of activities.
Unit string
Labels []string
Description string
}
MetricInfo describes one metric of MetricCatalog.
type MetricKind ¶
type MetricKind string
MetricKind is how a metric aggregates.
const ( MetricCounter MetricKind = "counter" MetricHistogram MetricKind = "histogram" MetricGauge MetricKind = "gauge" )
type MetricLabels ¶
type MetricLabels struct {
Queue string
ActivityType string
// Status is a canonical activity status (storage.RecordStatus*), on
// MetricQueueDepth only.
Status string
}
MetricLabels are the labels of one observation. MetricCatalog lists which labels each metric carries; the others are empty.
type MetricsSink ¶
type MetricsSink interface {
IncCounter(name string, value uint64)
ObserveDuration(name string, dur time.Duration)
}
MetricsSink receives the engine's counters and durations by name, without labels or gauges. LabeledMetricsSink receives everything; Builder.Metrics adapts a MetricsSink with UnlabeledMetrics.
type NoopMetrics ¶
type NoopMetrics struct{}
NoopMetrics discards all metrics; it is the default sink.
func (NoopMetrics) AddCounter ¶
func (NoopMetrics) AddCounter(string, uint64, MetricLabels)
func (NoopMetrics) IncCounter ¶
func (NoopMetrics) IncCounter(string, uint64)
func (NoopMetrics) ObserveDuration ¶
func (NoopMetrics) ObserveDuration(string, time.Duration)
func (NoopMetrics) RecordHistogram ¶
func (NoopMetrics) RecordHistogram(string, float64, MetricLabels)
func (NoopMetrics) SetGauge ¶
func (NoopMetrics) SetGauge(string, float64, MetricLabels)
type OnDuplicate ¶
type OnDuplicate int
OnDuplicate is what an enqueue does when its idempotency key is taken.
const ( // AllowReuse always creates a new activity and repoints the key at it. AllowReuse OnDuplicate = iota // ReturnExisting returns the existing activity's future. ReturnExisting // AllowReuseOnFailure creates a new activity only if the existing one // failed, dead-lettered or was cancelled. AllowReuseOnFailure // NoReuse fails the enqueue. NoReuse )
type ResultState ¶
type ResultState int
ResultState says whether a stored result is a success or a failure.
const ( ResultOk ResultState = iota ResultErr )
type RetentionConfig ¶
type RetentionConfig struct {
// Completed is how long trees whose root completed are kept; zero is
// forever.
Completed time.Duration `json:"completed,omitempty"`
// Failed is how long trees whose root failed or dead-lettered are kept,
// so failures can be held longer for inspection; zero is forever.
Failed time.Duration `json:"failed,omitempty"`
// Events is how long the events of finished activities are kept, when
// that should be shorter than their tree; zero keeps them with the tree.
// Events of unfinished activities are always kept.
Events time.Duration `json:"events,omitempty"`
// Interval is the sweep cadence (default 10 minutes).
Interval time.Duration `json:"interval,omitempty"`
// BatchSize is the most trees deleted per sweep transaction (default 100).
BatchSize int `json:"batch_size,omitempty"`
}
RetentionConfig opts the engine into deleting old terminal workflow trees; without it everything is kept forever. A tree is deleted whole (a terminal root with no non-terminal descendants), so a retry never finds a child's result missing. The backend elects one sweeper per queue, so every engine may set it.
type RetryableError ¶
type RetryableError interface {
IsRetryable() bool
}
RetryableError is any error that decides whether its activity is retried; a handler error without it is retried.
type Schedule ¶
type Schedule struct {
// Name identifies the schedule in its queue.
Name string
// Cron is a 5-field expression (minute hour day-of-month month
// day-of-week), a 6-field one with seconds first, or a macro such as
// @daily.
Cron string
// Timezone is the IANA zone Cron's wall-clock times are in (default
// "UTC"). On a host without zoneinfo, import _ "time/tzdata".
Timezone string
// Activity is the activity type to enqueue, e.g. NameOf[Report]().
Activity string
// Payload is each fired activity's payload (default JSON null).
Payload json.RawMessage
// Execution options of the fired activities, defaulting as for
// ActivityBuilder: normal priority, 3 attempts, a 300s timeout and a 1h
// retry delay cap.
Priority ActivityPriority
MaxRetries *uint32
Timeout time.Duration
MaxRetryDelay time.Duration
Metadata map[string]string
// CatchUp says what to do with ticks that came due while no engine ran:
// storage.CatchUpOne (default) fires the latest once, CatchUpSkip fires
// nothing late by a minute or more, CatchUpAll fires each of them, up to
// CatchUpLimit (default 100).
CatchUp storage.CatchUp
CatchUpLimit int
}
Schedule enqueues an activity at each fire time of a cron expression. Every engine of the queue fires the queue's schedules, and each tick fires once however many engines run (docs/schedules.md).
type Schedules ¶
type Schedules struct {
// contains filtered or unexported fields
}
Schedules manages a queue's cron schedules from any process, worker or not. Get one with NewSchedules or WorkerEngine.Schedules.
func NewSchedules ¶
NewSchedules manages the schedules of backend's queue. It fails when the backend does not implement storage.ScheduleStorage.
func (*Schedules) Delete ¶
Delete removes a schedule. Activities it already enqueued are unaffected.
func (*Schedules) Resume ¶
Resume restarts a paused schedule from its next fire time after now; ticks missed while paused are not caught up.
type Spawner ¶
type Spawner interface {
ActivityNamed(activityType string) *ActivityBuilder
}
Spawner starts activities by type name: an *ActivityExecutor (children of the running handler, or roots) or a *Client (roots).
type Step ¶
Step is a typed unit of work for RunStep. Its context derives from the activity's, so the activity timeout still bounds it.
type Target ¶
type Target struct {
// IDs names activities; at most 1000.
IDs []uuid.UUID
// Filter selects, oldest first, up to Max activities the command can act
// on (cancel skips finished ones, retry takes only failed ones, ...), so
// repeating a bounded command makes progress.
Filter *storage.QueryFilter
// Max bounds a filter target: 1 to 10000.
Max int
}
Target selects the activities a command acts on: IDs, or a filter.
type TraceAttribute ¶
TraceAttribute is a span attribute keyed by an Attr* constant; Value is a string or an int64.
type Tracer ¶
type Tracer interface {
// Start starts the span name as a child of parent, a W3C traceparent, or
// of ctx's current span when parent is "". It returns ctx carrying the
// new span and the function that ends it.
Start(ctx context.Context, name, parent string, attrs ...TraceAttribute) (context.Context, EndSpan)
// Traceparent returns ctx's current span as a W3C traceparent, or "" when
// ctx carries none.
Traceparent(ctx context.Context) string
}
Tracer starts the spans the engine reports: one per enqueue, attempt, executed step, durable sleep, signal wait and signal sent, named by the Span* constants and described by Attr* attributes (runnerq-spec observability/tracing.json). The module github.com/runnerq/runnerq-go/otel implements it with OpenTelemetry; the SDK itself depends on no tracing library. Implementations must be safe for concurrent use.
Whether or not a Tracer is set, every enqueue stores a W3C traceparent in the activity's metadata (MetadataTraceparent) when there is one to store: the caller's own, the enqueue span's, or the enqueueing handler's activity's. An attempt continues the stored one, so retries and the attempts that resume after a sleep or signal wait join the enqueue's trace.
type WorkerConfig ¶
type WorkerConfig struct {
// QueueName is the queue this engine serves; applications sharing a
// database keep apart by using different queues.
QueueName string `json:"queue_name"`
// MaxConcurrentActivities is how many activities run at once.
MaxConcurrentActivities int `json:"max_concurrent_activities"`
// SchedulePollIntervalSeconds is how often due scheduled activities are
// released (default 5), for backends that don't schedule in Dequeue.
SchedulePollIntervalSeconds *uint64 `json:"schedule_poll_interval_seconds,omitempty"`
// LeaseMS overrides the backend's minimum lease on a claim, in
// milliseconds. Nil keeps the backend's own (postgres.WithConfig's
// defaultLeaseMS; 60s for postgres.New).
LeaseMS *uint64 `json:"lease_ms,omitempty"`
// ReaperIntervalSeconds is how often expired leases are reclaimed
// (default 5).
ReaperIntervalSeconds *uint64 `json:"reaper_interval_seconds,omitempty"`
// ReaperBatchSize is the most expired leases reclaimed per tick
// (default 100).
ReaperBatchSize *int `json:"reaper_batch_size,omitempty"`
// ActivityTypes restricts the types this engine claims; empty means
// every registered type.
ActivityTypes []string `json:"activity_types,omitempty"`
// MaxActivityDepth caps the depth of a parent/child tree (default 32); a
// spawn beyond it fails with ErrDepthExceeded.
MaxActivityDepth uint16 `json:"max_activity_depth,omitempty"`
// Retention enables deleting old terminal workflow trees; nil keeps
// everything.
Retention *RetentionConfig `json:"retention,omitempty"`
// ShutdownGraceSeconds bounds the whole shutdown drain (default 30).
// When it runs out, Start returns with activities still in flight.
ShutdownGraceSeconds *uint64 `json:"shutdown_grace_seconds,omitempty"`
// GaugeInterval turns on the gauges, sampled about this often; 0 (the
// default) leaves them off. See WorkerEngineBuilder.GaugeInterval.
GaugeInterval time.Duration `json:"gauge_interval,omitempty"`
// Labels are free-form tags for this worker (region, deploy version),
// carried in its executor snapshots.
Labels map[string]string `json:"labels,omitempty"`
}
WorkerConfig configures a WorkerEngine.
func DefaultWorkerConfig ¶
func DefaultWorkerConfig() WorkerConfig
DefaultWorkerConfig is the configuration Builder starts from.
type WorkerEngine ¶
type WorkerEngine struct {
// contains filtered or unexported fields
}
WorkerEngine claims activities from its backend and runs their handlers.
func NewWorkerEngineWithBackend ¶
func NewWorkerEngineWithBackend(backend storage.Storage, config WorkerConfig) *WorkerEngine
NewWorkerEngineWithBackend creates a WorkerEngine from a backend and a full configuration; Builder is the shorter way.
func (*WorkerEngine) ActivityTypes ¶
func (e *WorkerEngine) ActivityTypes() []string
ActivityTypes returns the registered activity types, sorted.
func (*WorkerEngine) Announce ¶
func (e *WorkerEngine) Announce(a executor.Announcer)
Announce sends a every lifecycle change this engine makes from now on: submissions through its ActivityExecutors, claims and successes. nil stops. Safe at any time; the conductor agent uses it while a console watches.
func (*WorkerEngine) Backend ¶
func (e *WorkerEngine) Backend() storage.Storage
func (*WorkerEngine) Changed ¶
func (e *WorkerEngine) Changed() <-chan struct{}
Changed returns a channel closed at the engine's next change: an activity starting or finishing, or a drain beginning (executor.Notifier).
func (*WorkerEngine) Client ¶
func (e *WorkerEngine) Client() *Client
Client returns a Client on the engine's backend. Its submissions are announced like the engine's own, a spawn on a handler's context becomes that handler's child (as with GetActivityExecutor), and a Cancel stops a handler this engine is running at once.
func (*WorkerEngine) Draining ¶
func (e *WorkerEngine) Draining() bool
Draining reports whether a shutdown has begun: intake has stopped and in-flight activities are finishing.
func (*WorkerEngine) GetActivityExecutor ¶
func (e *WorkerEngine) GetActivityExecutor() *ActivityExecutor
GetActivityExecutor returns an executor for spawning root activities. On a handler's context it spawns children of that handler's activity instead (see ActivityExecutor).
func (*WorkerEngine) InFlight ¶
func (e *WorkerEngine) InFlight() []InFlightActivity
InFlight returns the activities this engine is executing, oldest first.
func (*WorkerEngine) InstanceID ¶
func (e *WorkerEngine) InstanceID() string
InstanceID is this engine's random, per-construction identity: it prefixes claim tokens and is the executor id in its snapshots.
func (*WorkerEngine) Interrupt ¶
func (e *WorkerEngine) Interrupt(activityID uuid.UUID) bool
Interrupt stops the handler running activityID here, as if its claim had been lost, and reports whether one was running. Call it after cancelling the activity in storage: the heartbeat would notice within an interval; this makes it immediate.
func (*WorkerEngine) MaxConcurrentActivities ¶
func (e *WorkerEngine) MaxConcurrentActivities() int
func (*WorkerEngine) Observe ¶
func (e *WorkerEngine) Observe(o executor.Observer)
Observe tells o when this engine starts and stops, so it can report the engine's Snapshot while it runs. Call before Start.
func (*WorkerEngine) QueueName ¶
func (e *WorkerEngine) QueueName() string
func (*WorkerEngine) RegisterActivity ¶
func (e *WorkerEngine) RegisterActivity(handler ActivityHandler)
RegisterActivity registers a handler under its Go type name: &ResizeImage{} serves "ResizeImage", as NameOf derives for spawns. It panics for an unnamed type (use RegisterActivityWithName), a type already registered, or once the engine is running.
The type is stored with every activity, so renaming the handler struct strands rows already enqueued; pin the name with RegisterActivityWithName where that matters.
func (*WorkerEngine) RegisterActivityWithName ¶
func (e *WorkerEngine) RegisterActivityWithName(activityType string, handler ActivityHandler)
RegisterActivityWithName registers a handler under an explicit activity type, decoupling the stored type from the Go name or serving several types with one handler type. It panics on an empty type, a nil handler, a type already registered, or once the engine is running.
func (*WorkerEngine) RegisterSchedule ¶
func (e *WorkerEngine) RegisterSchedule(s Schedule) error
RegisterSchedule declares a schedule that Start upserts, so the schedules a deployment's code declares are the ones stored. It fails on an invalid schedule, a duplicate name, a backend without schedules, or once the engine is running.
func (*WorkerEngine) Schedules ¶
func (e *WorkerEngine) Schedules() *Schedules
Schedules manages the schedules of the engine's queue; nil when its backend does not support schedules.
func (*WorkerEngine) SetLabeledMetrics ¶
func (e *WorkerEngine) SetLabeledMetrics(sink LabeledMetricsSink)
SetLabeledMetrics sets the metrics sink, replacing any set before. Panics once the engine is running.
func (*WorkerEngine) SetMetrics ¶
func (e *WorkerEngine) SetMetrics(sink MetricsSink)
SetMetrics sets an unlabeled metrics sink (see UnlabeledMetrics), replacing any sink set before. Panics once the engine is running.
func (*WorkerEngine) SetTracer ¶
func (e *WorkerEngine) SetTracer(t Tracer)
SetTracer sets the tracer for this engine's attempts and for the activities its executors enqueue; nil turns tracing off. Panics once the engine is running.
func (*WorkerEngine) Signal ¶
func (e *WorkerEngine) Signal(ctx context.Context, activityID uuid.UUID, name string, payload json.RawMessage) error
Signal is SignalActivity on this engine's backend, traced by its Tracer.
func (*WorkerEngine) SignalByKey ¶
func (e *WorkerEngine) SignalByKey(ctx context.Context, activityType string, idempotencyKey string, name string, payload json.RawMessage) error
SignalByKey is SignalActivityByKey on this engine's backend, delivered through Signal.
func (*WorkerEngine) Snapshot ¶
func (e *WorkerEngine) Snapshot() executor.Snapshot
Snapshot describes this executor now: who it is, what it is running and what it has done since it was built. Safe from any goroutine.
func (*WorkerEngine) Start ¶
func (e *WorkerEngine) Start(ctx context.Context) error
Start runs the engine until ctx ends, Stop is called or the process gets SIGINT/SIGTERM, then drains in-flight activities and returns.
func (*WorkerEngine) StartedAt ¶
func (e *WorkerEngine) StartedAt() time.Time
StartedAt is when Start was last called, or zero.
func (*WorkerEngine) Stop ¶
func (e *WorkerEngine) Stop()
Stop begins a graceful shutdown: intake stops, and Start returns once in-flight activities have finished (bounded by the shutdown grace).
Stop leaves the engine context alive: cancelling it would make a handler that completes during the drain fail its ack and rerun elsewhere. Start drains and then cancels it.
type WorkerEngineBuilder ¶
type WorkerEngineBuilder struct {
// contains filtered or unexported fields
}
WorkerEngineBuilder configures a WorkerEngine; start with Builder.
func Builder ¶
func Builder() *WorkerEngineBuilder
Builder starts configuring a WorkerEngine from DefaultWorkerConfig.
func (*WorkerEngineBuilder) ActivityTypes ¶
func (b *WorkerEngineBuilder) ActivityTypes(types []string) *WorkerEngineBuilder
ActivityTypes restricts the types this engine claims (default: all registered types).
func (*WorkerEngineBuilder) Backend ¶
func (b *WorkerEngineBuilder) Backend(backend storage.Storage) *WorkerEngineBuilder
Backend sets the storage backend; required.
func (*WorkerEngineBuilder) Build ¶
func (b *WorkerEngineBuilder) Build() (*WorkerEngine, error)
Build creates the WorkerEngine. It fails when no backend is set.
func (*WorkerEngineBuilder) GaugeInterval ¶
func (b *WorkerEngineBuilder) GaugeInterval(d time.Duration) *WorkerEngineBuilder
GaugeInterval turns on the gauges (queue depth by status, oldest pending age, in-flight count), sampled about every d (jittered by up to a fifth). Queue depth and age need a backend that implements storage.QueryStorage and cost one aggregate and one single-row query per sample. Off by default.
func (*WorkerEngineBuilder) LabeledMetrics ¶
func (b *WorkerEngineBuilder) LabeledMetrics(sink LabeledMetricsSink) *WorkerEngineBuilder
LabeledMetrics sets the metrics sink, replacing one set by Metrics. The module github.com/runnerq/runnerq-go/otel provides one for OpenTelemetry.
func (*WorkerEngineBuilder) MaxWorkers ¶
func (b *WorkerEngineBuilder) MaxWorkers(max int) *WorkerEngineBuilder
MaxWorkers sets how many activities run at once (default 10).
func (*WorkerEngineBuilder) Metrics ¶
func (b *WorkerEngineBuilder) Metrics(sink MetricsSink) *WorkerEngineBuilder
Metrics sets an unlabeled metrics sink (see UnlabeledMetrics), replacing one set by LabeledMetrics.
func (*WorkerEngineBuilder) QueueName ¶
func (b *WorkerEngineBuilder) QueueName(name string) *WorkerEngineBuilder
QueueName sets the queue to serve (default "default").
func (*WorkerEngineBuilder) Retention ¶
func (b *WorkerEngineBuilder) Retention(cfg RetentionConfig) *WorkerEngineBuilder
Retention opts the engine into deleting old terminal workflow trees (see RetentionConfig). Safe on every engine: the backend elects one sweeper.
func (*WorkerEngineBuilder) SchedulePollInterval ¶
func (b *WorkerEngineBuilder) SchedulePollInterval(interval time.Duration) *WorkerEngineBuilder
SchedulePollInterval sets how often due scheduled activities are released, for backends that don't schedule in Dequeue (default 5s).
func (*WorkerEngineBuilder) ShutdownGrace ¶
func (b *WorkerEngineBuilder) ShutdownGrace(d time.Duration) *WorkerEngineBuilder
ShutdownGrace bounds the shutdown drain (default 30s, at least 1s).
func (*WorkerEngineBuilder) Tracer ¶
func (b *WorkerEngineBuilder) Tracer(t Tracer) *WorkerEngineBuilder
Tracer sets the tracer for attempts and for the activities the engine's executors enqueue (see Tracer).
type WorkerError ¶
type WorkerError struct {
Kind WorkerErrorKind
Message string
Cause error
}
WorkerError is an error from the engine.
func IsWorkerError ¶
func IsWorkerError(err error) (*WorkerError, bool)
IsWorkerError returns the *WorkerError in err's chain, if any.
func WorkerErrorFromStorage ¶
func WorkerErrorFromStorage(err error) *WorkerError
WorkerErrorFromStorage maps a storage error onto a WorkerError kind; an error that isn't a storage error becomes ErrUnknown.
func (*WorkerError) Error ¶
func (e *WorkerError) Error() string
func (*WorkerError) IsRetryable ¶
func (e *WorkerError) IsRetryable() bool
IsRetryable reports whether retrying may resolve the error.
func (*WorkerError) Unwrap ¶
func (e *WorkerError) Unwrap() error
type WorkerErrorKind ¶
type WorkerErrorKind int
const ( ErrCustom WorkerErrorKind = iota ErrQueue ErrSerializationW ErrTimeoutW ErrExecution ErrHandlerNotFound ErrBackend ErrDatabase ErrConfiguration ErrShutdown ErrAlreadyRunning ErrScheduling ErrDuplicateActivityW ErrIdempotencyConflictW ErrDepthExceeded ErrUnknown // ErrSignalTimeoutW: WaitForSignal timed out. Not retryable: a retry // replays the stored deadline and times out again. ErrSignalTimeoutW // ErrActivityNotFoundW: the activity doesn't exist (never enqueued, or // swept by retention). ErrActivityNotFoundW // ErrActivityCancelled: the awaited activity was cancelled. Its Message // is the stored cancellation, as for any other failed result. ErrActivityCancelled // ErrCommandConflict: a command id was reused with different input. ErrCommandConflict )
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
conductor
module
|
|
|
examples
|
|
|
01-hello-workflow
command
01 — Hello, Workflow
|
01 — Hello, Workflow |
|
02-crash-and-resume
command
02 — Crash & Resume (the flagship demo)
|
02 — Crash & Resume (the flagship demo) |
|
03-steps-and-retries
command
03 — Steps & Retries
|
03 — Steps & Retries |
|
04-checkpoint-side-effects
command
04 — Checkpoint Side Effects with ctx.Run
|
04 — Checkpoint Side Effects with ctx.Run |
|
05-durable-sleep
command
05 — Durable Sleep
|
05 — Durable Sleep |
|
06-human-approval
command
06 — Human-in-the-Loop with Signals
|
06 — Human-in-the-Loop with Signals |
|
07-fan-out
command
07 — Fan-Out and WaitAll
|
07 — Fan-Out and WaitAll |
|
08-exactly-once-webhook
command
08 — Exactly-Once Webhook Ingestion
|
08 — Exactly-Once Webhook Ingestion |
|
09-cross-process-futures
command
09 — Cross-Process Futures
|
09 — Cross-Process Futures |
|
10-retries-and-dead-letter
command
10 — Retries and the Dead-Letter Queue
|
10 — Retries and the Dead-Letter Queue |
|
11-retention
command
11 — Retention
|
11 — Retention |
|
12-workload-isolation
command
12 — Workload Isolation
|
12 — Workload Isolation |
|
13-cron-schedules
command
13 — Cron schedules
|
13 — Cron schedules |
|
Package executor describes a running engine (an executor): who it is, what it is doing and what it has done.
|
Package executor describes a running engine (an executor): who it is, what it is doing and what it has done. |
|
internal
|
|
|
chaosworker
command
Command chaosworker is the Go SDK's worker for runnerq-spec's chaos harness (tools/chaos/README.md in runnerq-spec).
|
Command chaosworker is the Go SDK's worker for runnerq-spec's chaos harness (tools/chaos/README.md in runnerq-spec). |
|
conformancedriver
command
Command conformancedriver runs runnerq-spec's conformance scenarios' storage operations on the Postgres backend, speaking the spec's driver protocol (conformance/README.md) on stdin and stdout.
|
Command conformancedriver runs runnerq-spec's conformance scenarios' storage operations on the Postgres backend, speaking the spec's driver protocol (conformance/README.md) on stdin and stdout. |
|
cron
Package cron parses runnerq-spec's cron dialect and computes fire times (runnerq-spec schedules.md, vectors/cron_next_fire.json).
|
Package cron parses runnerq-spec's cron dialect and computes fire times (runnerq-spec schedules.md, vectors/cron_next_fire.json). |
|
spec
Package spec holds the constants every RunnerQ implementation shares (github.com/runnerq/runnerq-spec).
|
Package spec holds the constants every RunnerQ implementation shares (github.com/runnerq/runnerq-spec). |
|
spectest
Package spectest reads runnerq-spec vector files (the spec/ submodule) for tests.
|
Package spectest reads runnerq-spec vector files (the spec/ submodule) for tests. |
|
upgradetest/workload
command
Command workload is the upgrade test's workload (see the package test).
|
Command workload is the upgrade test's workload (see the package test). |
|
storagetest
Package storagetest is the conformance suite for storage.Storage backends.
|
Package storagetest is the conformance suite for storage.Storage backends. |