storage

package
v0.5.2-0...-c11405c Latest Latest
Warning

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

Go to latest
Published: Nov 12, 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

Index

Constants

View Source
const (
	CommandApplied    = "applied"
	CommandSkipped    = "skipped"
	CommandWouldApply = "would_apply"
)

CommandItem.Outcome values.

View Source
const (
	RecordStatusPending    = "pending"
	RecordStatusScheduled  = "scheduled"
	RecordStatusRunning    = "running"
	RecordStatusWaiting    = "waiting"
	RecordStatusCompleted  = "completed"
	RecordStatusFailed     = "failed"
	RecordStatusDeadLetter = "dead_letter"
	RecordStatusCancelled  = "cancelled"
)

Canonical activity statuses.

View Source
const (
	RecordEventCreated         = "activity.created"
	RecordEventScheduled       = "activity.scheduled"
	RecordEventCancelled       = "activity.cancelled"
	RecordEventAttemptStarted  = "attempt.started"
	RecordEventAttemptOK       = "attempt.succeeded"
	RecordEventAttemptFailed   = "attempt.failed"
	RecordEventAttemptTimedOut = "attempt.timed_out"
	RecordEventLeaseExpired    = "attempt.lease_expired"
	RecordEventWaitParked      = "wait.parked"
	RecordEventSignalReceived  = "signal.received"
	RecordEventChildLinked     = "child.linked"
	RecordEventDeadLetter      = "dead_letter.entered"
	RecordEventRedriven        = "dead_letter.redriven"
	RecordEventRetried         = "activity.retried"
	RecordEventRunNow          = "activity.run_now"
	RecordEventRescheduled     = "activity.rescheduled"
	RecordEventPriorityChanged = "activity.priority_changed"
)

Canonical event types. Backend events with no equivalent keep a namespaced name of their own.

Created, Scheduled, AttemptStarted and AttemptOK are never stored: an activity's created_at, scheduled_at, started_at and completed_at say them.

View Source
const (
	OpEq       = "eq"
	OpNe       = "ne"
	OpIn       = "in"
	OpNin      = "nin"
	OpLt       = "lt"
	OpLte      = "lte"
	OpGt       = "gt"
	OpGte      = "gte"
	OpExists   = "exists"
	OpPrefix   = "prefix"
	OpContains = "contains"
)
View Source
const DefaultCatchUpLimit = spec.ScheduleCatchUpLimitDefault

DefaultCatchUpLimit is how many due ticks CatchUpAll fires at once when a schedule sets no limit.

View Source
const DefaultMaxRetryDelaySeconds = spec.DefaultMaxRetryDelaySeconds

DefaultMaxRetryDelaySeconds caps retry backoff for activities that set no MaxRetryDelay.

View Source
const MaxCatchUpLimit = 1000

MaxCatchUpLimit bounds CatchUpLimit.

View Source
const SerializationJSON = spec.SerializationJSON

SerializationJSON is plain JSON, the encoding an empty Serialization means.

View Source
const StepKeyPrefix = spec.StepKeyPrefix

StepKeyPrefix starts the keys the engine derives for activities spawned by a step; they are not application keys.

Variables

This section is empty.

Functions

func ApplicationIdempotencyKey

func ApplicationIdempotencyKey(stored, activityType string) string

ApplicationIdempotencyKey recovers the application's key from a stored key and activity type, as QueryStorage reports it. Handles v2 and legacy "<key>-<type>" keys; raw storage-API keys are returned as is, and step-derived keys yield "".

func AttemptsRemain

func AttemptsRemain(retryCount, maxRetries int) bool

AttemptsRemain reports whether a failed attempt may be followed by another. retryCount counts the attempts that failed before it; maxRetries is the attempt limit, 0 meaning unlimited. A retryable failure with attempts remaining is retried, one without dead-letters, and a lease expiry counts as a retryable failure.

func BusinessIdempotencyKey

func BusinessIdempotencyKey(key, activityType string) string

BusinessIdempotencyKey encodes (key, activityType) unambiguously. Base64 has no '-', so a v2 key never equals a legacy "<key>-<type>" key or an rq:step key (which contains UUIDs).

func CheckpointID

func CheckpointID(activityID uuid.UUID, kind, name string) uuid.UUID

CheckpointID derives the id of an activity's named checkpoint (kind "run", "sleep", "signal", ...). Backends must use it so a signal they store is the one the handler's WaitForSignal reads.

func CommandFingerprint

func CommandFingerprint(cmd Command) string

CommandFingerprint is a command's canonical fingerprint (runnerq-spec vectors/command_fingerprint.json): the SHA-256 of a canonical JSON form of its input, without its ID. SDK clients set Command.Fingerprint to it, so a command id repeated with the same input replays from the shared ledger whichever SDK sent it.

func LegacyBusinessIdempotencyKey

func LegacyBusinessIdempotencyKey(encoded string) (legacy, activityType string, ok bool)

LegacyBusinessIdempotencyKey maps a v2 key to its legacy "<key>-<type>" form for reading pre-v2 claims. Accept a legacy row only after verifying its activity type.

func NextFireTime

func NextFireTime(cronExpr, timezone string, after time.Time) (time.Time, error)

NextFireTime is the first fire time of cronExpr in timezone strictly after after.

func RetryDelaySeconds

func RetryDelaySeconds(retryCount int, retryDelaySeconds, maxRetryDelaySeconds int64) int64

RetryDelaySeconds is the backoff before the retry that follows attempt retryCount+1: retryDelaySeconds × 2^(retryCount+1), capped at maxRetryDelaySeconds (0 means DefaultMaxRetryDelaySeconds). The result always fits a time.Duration.

func ScheduleFireTimes

func ScheduleFireTimes(s *Schedule, now time.Time) (fire []time.Time, next time.Time, err error)

ScheduleFireTimes is what firing a due schedule at now enqueues, oldest first, and its next NextFireAt (runnerq-spec vectors/schedule_fire.json). A schedule not yet due fires nothing and keeps its NextFireAt.

func ScheduleIdempotencyKey

func ScheduleIdempotencyKey(name string, at time.Time) string

ScheduleIdempotencyKey is the application key of the activity a schedule fires at a time: schedule:<name>:<time in RFC 3339 UTC, to the second>. Store it encoded, as BusinessIdempotencyKey(key, activity type).

func StepIdempotencyKey

func StepIdempotencyKey(root, parent uuid.UUID, step string) string

StepIdempotencyKey is the key of the activity a step spawns under parent in root's tree. A retried parent re-issuing the spawn derives the same key and gets the existing child.

func ValidateSchedule

func ValidateSchedule(s *Schedule) error

ValidateSchedule checks what UpsertSchedule stores, filling in the zero Timezone (UTC), CatchUp (one) and CatchUpLimit (DefaultCatchUpLimit).

Types

type ActivityEvent

type ActivityEvent struct {
	ActivityID uuid.UUID         `json:"activity_id"`
	Timestamp  time.Time         `json:"timestamp"`
	EventType  ActivityEventType `json:"event_type"`
	WorkerID   *string           `json:"worker_id,omitempty"`
	Detail     json.RawMessage   `json:"detail,omitempty"`
}

ActivityEvent records a lifecycle event.

type ActivityEventType

type ActivityEventType = string

ActivityEventType classifies stored events: only what the activity row can't say (runnerq-spec schema/postgres/events.schema.json).

const (
	EventFailed     ActivityEventType = "Failed"
	EventRetrying   ActivityEventType = "Retrying"
	EventDeadLetter ActivityEventType = "DeadLetter"
	// EventRequeued: the reaper returned an expired-lease activity to pending.
	EventRequeued ActivityEventType = "Requeued"
	// EventYielded: a durable wait parked the activity without consuming a retry.
	EventYielded  ActivityEventType = "Yielded"
	EventSignaled ActivityEventType = "Signaled"
	// EventSpawnLinked: idempotency reuse linked another parent to an existing
	// activity.
	EventSpawnLinked ActivityEventType = "SpawnLinked"
	// Operator actions applied through CommandStorage.
	EventCancelled       ActivityEventType = "Cancelled"
	EventRetried         ActivityEventType = "Retried"
	EventRedriven        ActivityEventType = "Redriven"
	EventRunNow          ActivityEventType = "RunNow"
	EventRescheduled     ActivityEventType = "Rescheduled"
	EventPriorityChanged ActivityEventType = "PriorityChanged"
)

type ActivityPriority

type ActivityPriority = int

ActivityPriority determines execution ordering.

const (
	PriorityLow      ActivityPriority = 1
	PriorityNormal   ActivityPriority = 2
	PriorityHigh     ActivityPriority = 3
	PriorityCritical ActivityPriority = 4
)

type ActivityQuery

type ActivityQuery struct {
	Filter  *QueryFilter
	Sort    *QuerySort // nil: created_at descending
	Include RecordInclude
	Limit   int    // 0: 50; capped at 1000
	Cursor  string // opaque, from a previous page
}

ActivityQuery is a filtered, sorted, paginated activity query.

type ActivityRecord

type ActivityRecord struct {
	ID       uuid.UUID
	Type     string
	Queue    string
	Status   string // canonical
	Priority int
	RootID   uuid.UUID
	ParentID *uuid.UUID
	Depth    int
	// IdempotencyKey is the key the application set (see
	// ApplicationIdempotencyKey), never the stored encoding; empty when the
	// application set none. Filters on "idempotency_key" match this form.
	IdempotencyKey string
	// Attempt is the attempt running or next to run, from 1; for a terminal
	// activity, the number of attempts made.
	Attempt int
	// MaxAttempts is the total number of attempts allowed; 0 is unlimited.
	MaxAttempts    int
	CreatedAt      time.Time
	ScheduledFor   *time.Time
	StartedAt      *time.Time
	CompletedAt    *time.Time
	UpdatedAt      time.Time
	Timeout        time.Duration
	LeaseExpiresAt *time.Time
	// ExecutorID is the engine instance running it (running activities only).
	ExecutorID string
	Wait       *RecordWait
	Metadata   map[string]string
	LastError  *RecordError // only with Include.LastError
	// Payload and Result's data (only with Include.Payload and
	// Include.Result) are plain JSON, as is StepEntry.Data: backends unwrap
	// other encodings, such as the "json" part of the TypeScript SDK's
	// superjson-v1.
	Payload json.RawMessage
	Result  *ActivityResult
}

ActivityRecord is an activity in the canonical model.

type ActivityRecordPage

type ActivityRecordPage struct {
	Items      []ActivityRecord
	NextCursor string
}

ActivityRecordPage is one page of activities.

type ActivityResult

type ActivityResult struct {
	Data  json.RawMessage
	State ResultState
	// Serialization is Data's encoding, as for QueuedActivity.Serialization.
	Serialization string `json:",omitempty"`
}

ActivityResult holds result data from a completed activity.

type ActivitySnapshot

type ActivitySnapshot struct {
	ID                uuid.UUID         `json:"id"`
	ActivityType      string            `json:"activity_type"`
	Payload           json.RawMessage   `json:"payload"`
	Priority          ActivityPriority  `json:"priority"`
	Status            string            `json:"status"`
	CreatedAt         time.Time         `json:"created_at"`
	ScheduledAt       *time.Time        `json:"scheduled_at,omitempty"`
	StartedAt         *time.Time        `json:"started_at,omitempty"`
	CompletedAt       *time.Time        `json:"completed_at,omitempty"`
	CurrentWorkerID   *string           `json:"current_worker_id,omitempty"`
	LastWorkerID      *string           `json:"last_worker_id,omitempty"`
	RetryCount        uint32            `json:"retry_count"`
	MaxRetries        uint32            `json:"max_retries"`
	TimeoutSeconds    uint64            `json:"timeout_seconds"`
	RetryDelaySeconds uint64            `json:"retry_delay_seconds"`
	Metadata          map[string]string `json:"metadata"`
	LastError         *string           `json:"last_error,omitempty"`
	LastErrorAt       *time.Time        `json:"last_error_at,omitempty"`
	StatusUpdatedAt   time.Time         `json:"status_updated_at"`
	Score             *float64          `json:"score,omitempty"`
	LeaseDeadlineMS   *int64            `json:"lease_deadline_ms,omitempty"`
	ProcessingMember  *string           `json:"processing_member,omitempty"`
	IdempotencyKey    *string           `json:"idempotency_key,omitempty"`
	ParentActivityID  *uuid.UUID        `json:"parent_activity_id,omitempty"`
	RootActivityID    *uuid.UUID        `json:"root_activity_id,omitempty"`
	Depth             uint16            `json:"depth"`
}

ActivitySnapshot is an activity's stored state as storagetest.Reader returns it.

type ActivityTree

type ActivityTree struct {
	RootID    uuid.UUID
	Items     []ActivityRecord
	Truncated bool
}

ActivityTree is the tree an activity belongs to.

type AggregateBucket

type AggregateBucket struct {
	Field    string // created_at | completed_at
	Interval time.Duration
	From     *time.Time
	To       *time.Time
}

AggregateBucket splits an aggregate into fixed time buckets.

type AggregateQuery

type AggregateQuery struct {
	Filter    *QueryFilter
	GroupBy   []string
	Bucket    *AggregateBucket
	Count     bool
	Durations []DurationMetric
	Limit     int // groups; 0: 200, capped at 1000
}

AggregateQuery groups and measures activities.

type AggregateRow

type AggregateRow struct {
	Key    map[string]string
	Bucket *time.Time
	Count  int64
	// Durations maps a duration field to percentile label ("p95") to
	// milliseconds.
	Durations map[string]map[string]float64
}

AggregateRow is one group.

type AggregateRows

type AggregateRows struct {
	Rows      []AggregateRow
	Truncated bool
}

AggregateRows is an aggregate's result.

type AttemptLeaseStorage

type AttemptLeaseStorage interface {
	ExtendLeaseForWorker(ctx context.Context, activityID uuid.UUID, workerID string, extendBy time.Duration) (bool, error)
}

AttemptLeaseStorage renews only the claim held by workerID, which is a fresh token per dequeue attempt, not a reusable slot label.

type BatchQueueStorage

type BatchQueueStorage interface {
	DequeueBatch(ctx context.Context, workerIDPrefix string, limit int, timeout time.Duration, activityTypes []string) ([]DequeuedActivity, error)
}

BatchQueueStorage is an optional capability for claiming several activities in one round trip; when present the engine claims exactly as many as it has idle slots instead of looping Dequeue per slot.

DequeueBatch claims at most limit activities under Dequeue's eligibility and ordering rules. workerIDPrefix is fresh per call; each LeaseID must be unique and derived from it (e.g. "<prefix>:<activity id>") so tokens never collide across calls. timeout means what it does for Dequeue; an empty result with a nil error means nothing became claimable in time.

type CatchUp

type CatchUp string

CatchUp says what firing does with ticks that came due while no worker fired them (runnerq-spec schedules.md).

const (
	// CatchUpSkip fires the latest due tick only when it is less than a
	// minute old.
	CatchUpSkip CatchUp = "skip"
	// CatchUpOne fires the latest due tick, however late. The default.
	CatchUpOne CatchUp = "one"
	// CatchUpAll fires every due tick, oldest first, up to CatchUpLimit.
	CatchUpAll CatchUp = "all"
)

type CheckpointStorage

type CheckpointStorage interface {
	StoreCheckpoint(ctx context.Context, resultID, ownerID uuid.UUID, workerID string, result ActivityResult, step string) error
}

CheckpointStorage stores immutable checkpoints fenced on the owning execution. Retrying identical data succeeds; a different outcome is ErrCheckpointConflict. Signals, which are mutable, must not use it.

type Command

type Command struct {
	// ID makes the command idempotent; empty disables the ledger.
	ID string
	// Fingerprint identifies the input, to detect a reused ID.
	Fingerprint string
	Kind        CommandKind
	Target      CommandTarget
	DryRun      bool
	Reason      string

	// CascadeChildren also cancels non-terminal descendants (cancel).
	CascadeChildren bool
	// ResetAttempts restores the full retry budget (retry).
	ResetAttempts bool
	// At is the new time (reschedule).
	At time.Time
	// Priority is the new priority (set_priority).
	Priority      ActivityPriority
	SignalName    string
	SignalPayload json.RawMessage
}

Command is one command against the backend's queue.

type CommandItem

type CommandItem struct {
	ID      uuid.UUID
	Outcome string
	// Status is the canonical status after the command (current if skipped).
	Status string
	// ErrKind and ErrMessage explain a skip: ErrNotFound, or ErrConflict for
	// a target in the wrong state.
	ErrKind    StorageErrorKind
	ErrMessage string
}

CommandItem is the outcome for one target.

type CommandKind

type CommandKind string
const (
	CommandCancel      CommandKind = "cancel"
	CommandRetry       CommandKind = "retry"
	CommandRunNow      CommandKind = "run_now"
	CommandReschedule  CommandKind = "reschedule"
	CommandSetPriority CommandKind = "set_priority"
	CommandDelete      CommandKind = "delete"
	CommandSignal      CommandKind = "signal"
)

type CommandResult

type CommandResult struct {
	Matched int
	Applied int
	// Cascaded counts descendants a cascading cancel also cancelled.
	Cascaded int
	// More is true when a filter target matched more than Max.
	More  bool
	Items []CommandItem
	// Replayed is true when the result came from the ledger.
	Replayed bool
}

CommandResult is a command's outcome.

type CommandStorage

type CommandStorage interface {
	ApplyCommand(ctx context.Context, cmd Command) (*CommandResult, error)
}

CommandStorage applies operator commands to the backend's own queue. Commands are idempotent by Command.ID: the backend keeps each applied command's result for at least 24 hours and replays it for the same ID; the same ID with a different Fingerprint is ErrConflict.

Per-target problems (not found, wrong state) are reported per item and do not fail the command. A returned error means nothing was applied.

type CommandTarget

type CommandTarget struct {
	IDs            []uuid.UUID
	Filter         *QueryFilter
	Max            int
	IdempotencyKey string
}

CommandTarget selects what a command acts on: exactly one of IDs, a Filter bounded by Max, or an IdempotencyKey (the stored form, see BusinessIdempotencyKey).

type DeadLetterRecord

type DeadLetterRecord struct {
	Activity ActivitySnapshot `json:"activity"`
	Error    string           `json:"error"`
	FailedAt time.Time        `json:"failed_at"`
}

DeadLetterRecord is a dead-lettered activity.

type DependencyStorage

type DependencyStorage interface {
	RegisterDependency(ctx context.Context, waiterID, resultID uuid.UUID, workerID string) error
	YieldForResult(ctx context.Context, waiterID, resultID uuid.UUID, producerID *uuid.UUID, wakeAt time.Time, workerID, kind, step string) error
}

DependencyStorage records which activity waits on which result, independent of parent lineage. Dependencies survive replay and are deleted with the waiter's tree. RegisterDependency rejects a missing producer (rehydrated futures). YieldForResult atomically records the wait, checks readiness, and parks or wakes the claim; a nil producerID means an external signal.

type DequeuedActivity

type DequeuedActivity struct {
	Activity QueuedActivity
	// LeaseID is the execution token recorded as the claim's worker ID and
	// presented by every fenced acknowledgement. Unique per claimed activity.
	LeaseID       string
	Attempt       uint32
	LeaseDeadline time.Time
}

DequeuedActivity is an activity claimed by a worker.

type DurationMetric

type DurationMetric struct {
	Field       string    // queue | run | total
	Percentiles []float64 // 0 < p < 100
}

DurationMetric asks for percentiles of a duration.

type EventQuery

type EventQuery struct {
	Filter        *QueryFilter
	Desc          bool // newest first
	Limit         int
	Cursor        string
	IncludeDetail bool
}

EventQuery lists lifecycle events in log order. "seq" (EventRecord.ID) increases in insertion order, so seq > cursor tails the log; a late commit can surface below an already-seen seq, so tailers rescan a window below their cursor.

type EventRecord

type EventRecord struct {
	ID         int64
	Cursor     string
	ActivityID uuid.UUID
	Type       string // canonical
	At         time.Time
	ExecutorID string
	Detail     json.RawMessage // only with IncludeDetail
}

EventRecord is one lifecycle event.

type EventRecordPage

type EventRecordPage struct {
	Items      []EventRecord
	NextCursor string
}

EventRecordPage is one page of events.

type FailureKind

type FailureKind struct {
	Retryable bool
	Reason    string
	IsTimeout bool
	// Details is the structured failure (the TypeScript SDK's name, message,
	// stack, code and cause), stored in the error result as "failure". Empty
	// for the Go SDK.
	Details json.RawMessage `json:",omitempty"`
}

FailureKind describes how an activity failed.

func NewNonRetryableFailure

func NewNonRetryableFailure(reason string) FailureKind

func NewRetryableFailure

func NewRetryableFailure(reason string) FailureKind

func NewTimeoutFailure

func NewTimeoutFailure() FailureKind

NewTimeoutFailure returns a retryable timeout failure.

type IdempotencyBehavior

type IdempotencyBehavior int

IdempotencyBehavior defines how duplicates are handled.

const (
	BehaviorAllowReuse IdempotencyBehavior = iota
	BehaviorReturnExisting
	BehaviorAllowReuseOnFailure
	BehaviorNoReuse
)

type IdempotencyKeyConfig

type IdempotencyKeyConfig struct {
	Key      string
	Behavior IdempotencyBehavior
}

IdempotencyKeyConfig holds a key and its behavior.

type IdempotencyResult

type IdempotencyResult struct {
	ExistingID       uuid.UUID
	ExistingParentID *uuid.UUID
}

IdempotencyResult describes the existing activity that already owns an idempotency key. ExistingParentID is nil for root or legacy activities.

type LeaseConfigurer

type LeaseConfigurer interface {
	SetLeaseMS(leaseMS int64)
}

LeaseConfigurer is an optional capability that receives the engine's lease duration at startup.

type QueryCapabilities

type QueryCapabilities struct {
	ActivityFilters []string // field names; "metadata" covers metadata.<key>
	ActivitySorts   []string
	EventFilters    []string
	GroupBy         []string
	Buckets         []string
	Durations       []string
}

QueryCapabilities lists what a backend can evaluate.

type QueryFilter

type QueryFilter struct {
	And   []QueryFilter
	Or    []QueryFilter
	Not   *QueryFilter
	Field string
	Op    string
	Value any
}

QueryFilter is a boolean expression. Exactly one of And, Or, Not or the Field/Op predicate is set. Value holds decoded JSON: string, float64, bool, []any or nil. Timestamps are RFC 3339 strings. Field "metadata.<key>" addresses a metadata tag.

type QuerySort

type QuerySort struct {
	Field string
	Desc  bool
}

QuerySort orders by one field; the backend adds a unique tiebreaker.

type QueryStorage

type QueryStorage interface {
	QueryCapabilities() QueryCapabilities
	QueryActivities(ctx context.Context, q ActivityQuery) (*ActivityRecordPage, error)
	// CountActivities counts matches up to limit; exact is false when the
	// count stopped at limit.
	CountActivities(ctx context.Context, filter *QueryFilter, limit int64) (count int64, exact bool, err error)
	AggregateActivities(ctx context.Context, q AggregateQuery) (*AggregateRows, error)
	QueryEvents(ctx context.Context, q EventQuery) (*EventRecordPage, error)
	// ListStepEntries lists an activity's durable steps, oldest first.
	ListStepEntries(ctx context.Context, activityID uuid.UUID, includeData bool, limit int, cursor string) (*StepEntryPage, error)
	// GetActivityTree returns the tree the activity belongs to (any member
	// may be named), root first, up to maxNodes.
	GetActivityTree(ctx context.Context, activityID uuid.UUID, include RecordInclude, maxNodes int) (*ActivityTree, error)
}

QueryStorage is a backend's read surface for dashboards and tooling (the conductor agent serves it too): filter, sort, project, paginate and aggregate activities, events and steps in the canonical backend-neutral model.

Queries span every queue in the database (filter on "queue" to narrow), so every executor of an app answers the same way.

Backends advertise what they evaluate in QueryCapabilities and must reject anything else with ErrUnsupported, never silently ignore a filter.

type QueueStorage

type QueueStorage interface {
	ResultStorage

	Enqueue(ctx context.Context, activity QueuedActivity) error
	// Dequeue claims the next runnable activity, blocking up to timeout for
	// work (0: one non-blocking attempt); (nil, nil) means nothing was claimable.
	Dequeue(ctx context.Context, workerID string, timeout time.Duration, activityTypes []string) (*QueuedActivity, error)
	// AckSuccess completes an activity. The result MUST be stored atomically
	// with the status change, and a result record MUST be written even when
	// result is nil so waiters always resolve. workerID is the unique execution
	// token: retrying an identical committed ack with it must succeed; a stale
	// or conflicting ack must not change the row.
	AckSuccess(ctx context.Context, activityID uuid.UUID, result json.RawMessage, workerID string) error
	// AckFailure records a failure once per execution token and reports whether
	// the activity was dead-lettered. Retrying the same committed failure
	// returns the original decision without consuming another attempt.
	AckFailure(ctx context.Context, activityID uuid.UUID, failure FailureKind, workerID string) (bool, error)
	ProcessScheduled(ctx context.Context) (uint64, error)
	RequeueExpired(ctx context.Context, batchSize int) (uint64, error)
	// Yield parks a processing activity until wakeAt WITHOUT counting a retry
	// (for durable waits longer than the attempt's timeout). Fenced on workerID
	// like the acks: returns ErrClaimLost when that worker no longer holds the
	// claim. kind ("sleep"/"signal"/"await") and step are recorded on the
	// Yielded event only; either may be empty.
	Yield(ctx context.Context, activityID uuid.UUID, wakeAt time.Time, workerID, kind, step string) error
	// StoreResult persists a result row. ownerActivityID governs its lifetime
	// (retention deletes it with the owner's tree): the activity itself for its
	// own result, or the handler's activity for a checkpoint with a synthetic
	// activityID. step is the checkpoint's "kind:name" (e.g.
	// "run:create-transfer"), or "" for an activity's own result.
	StoreResult(ctx context.Context, activityID uuid.UUID, ownerActivityID uuid.UUID, result ActivityResult, step string) error
	// WakeWaiting makes a parked ('waiting') activity runnable now; false in
	// any other state. It closes the race where a result commits between a
	// handler's last check and its park, which produces no wake of its own.
	WakeWaiting(ctx context.Context, activityID uuid.UUID) (bool, error)
	// SignalActivity stores payload as a result row under signalID, owned by
	// activityID, and wakes the activity if parked; store and wake commit
	// atomically. The same signalID again overwrites (last write wins). name
	// (may be "") is recorded as "signal:<name>" on the row and on the Signaled
	// event. Must return a not-found error for an unknown activityID, or the
	// row would never be collected.
	SignalActivity(ctx context.Context, activityID uuid.UUID, signalID uuid.UUID, name string, payload json.RawMessage) error
	// LookupIdempotencyActivityID returns the one activity that owns
	// idempotencyKey in this queue (see runnerq.SignalActivityByKey), or a
	// not-found error when none does (never claimed, or retention-swept).
	LookupIdempotencyActivityID(ctx context.Context, idempotencyKey string) (uuid.UUID, error)
	// CleanupExpired deletes up to batchSize terminal trees older than the
	// policy allows and returns how many. It must (a) delete only trees whose
	// root is terminal with no non-terminal descendants, (b) delete the tree's
	// activities, events, results (by activity AND by owner) and idempotency
	// keys together, and (c) keep concurrent sweepers from duplicating work
	// (returning 0 while another holds the lease is correct).
	CleanupExpired(ctx context.Context, policy RetentionPolicy, batchSize int) (uint64, error)
	// EnqueueIdempotent claims the idempotency key and enqueues the activity
	// atomically, so a crash never leaves a key claimed by an activity that
	// was never enqueued (bricking the key). (nil, nil) means it was enqueued;
	// callers MUST NOT also call Enqueue. When an existing owner is kept under
	// the key's behavior, the result describes it and nothing is enqueued.
	EnqueueIdempotent(ctx context.Context, activity *QueuedActivity) (*IdempotencyResult, error)
	// RecordSpawnLinked records that parentID spawned the existing childID
	// (idempotency reuse). Best-effort: callers log errors and continue.
	RecordSpawnLinked(ctx context.Context, childID, parentID uuid.UUID) error
	// SchedulesNatively reports whether due scheduled activities become
	// claimable without the engine calling ProcessScheduled.
	SchedulesNatively() bool
}

QueueStorage defines core queue operations.

type QueuedActivity

type QueuedActivity struct {
	ID                   uuid.UUID
	ActivityType         string
	Payload              json.RawMessage
	Priority             ActivityPriority
	MaxRetries           uint32
	RetryCount           uint32
	TimeoutSeconds       uint64
	RetryDelaySeconds    uint64
	MaxRetryDelaySeconds uint64
	ScheduledAt          *time.Time
	Metadata             map[string]string
	IdempotencyKey       *IdempotencyKeyConfig
	CreatedAt            time.Time
	ParentActivityID     *uuid.UUID
	RootActivityID       uuid.UUID
	Depth                uint16
	// Serialization is the payload's encoding: empty means plain JSON
	// (json-v1), all the Go SDK writes. The TypeScript SDK sets superjson-v1;
	// backends store it with the payload and return it with claims.
	Serialization string `json:",omitempty"`
}

QueuedActivity represents an activity ready to be enqueued.

func ScheduledActivity

func ScheduledActivity(s *Schedule, at, now time.Time) QueuedActivity

ScheduledActivity is the activity a schedule fires at a time, keyed by ScheduleIdempotencyKey with BehaviorReturnExisting.

type RecordError

type RecordError struct {
	Message string
	Kind    string
	At      *time.Time
}

RecordError describes a failure.

type RecordInclude

type RecordInclude struct {
	Payload   bool
	Result    bool
	LastError bool
}

RecordInclude selects heavy fields, which are omitted unless requested.

type RecordWait

type RecordWait struct {
	Kind  string // sleep | signal | children | other
	Name  string
	Until *time.Time
}

RecordWait describes why a waiting activity is parked.

type ResultNotifier

type ResultNotifier interface {
	NotifyResult(id uuid.UUID) (hint <-chan struct{}, stop func())
}

ResultNotifier is an optional capability: hints that a result for an id may have been stored, in this process or another sharing the database. The engine uses it to stop a handler promptly when its activity is cancelled (a cancel stores the activity's error result): on a hint it renews the claim at once instead of at the next heartbeat. Hints may be lost or spurious, so consumers recheck stored state. stop ends the subscription.

type ResultState

type ResultState int

ResultState indicates success or failure of an activity result.

const (
	ResultOk ResultState = iota
	ResultErr
)

type ResultStorage

type ResultStorage interface {
	GetResult(ctx context.Context, activityID uuid.UUID) (*ActivityResult, error)
}

ResultStorage retrieves activity results.

type ResultWaiter

type ResultWaiter interface {
	WaitForResult(ctx context.Context, activityID uuid.UUID) (*ActivityResult, error)
}

ResultWaiter is an optional capability for blocking until a result exists (e.g. via LISTEN/NOTIFY) instead of polling GetResult. The wait must work across processes: the waiter and the producing worker usually share only the database. It returns once the result exists, or with ctx's error.

type RetentionPolicy

type RetentionPolicy struct {
	// Completed applies to trees whose root completed.
	Completed time.Duration
	// Failed applies to failed, dead_letter or cancelled roots, on a separate
	// clock so failures can be held longer for inspection.
	Failed time.Duration
	// Events trims the events of finished activities older than this, before
	// their tree goes. Events of unfinished activities are kept. 0 keeps events
	// as long as their tree.
	Events time.Duration
}

RetentionPolicy sets how long terminal workflow trees are kept before the sweeper deletes their activities, events, results (checkpoints included) and idempotency keys. Zero keeps that class forever. The unit is the whole tree under a terminal root with no non-terminal descendants, never single rows, so a retried parent never finds its children's results missing.

type Schedule

type Schedule struct {
	Name     string
	Cron     string
	Timezone string
	// ActivityType, Payload and Serialization are the fired activity's;
	// Serialization is as for QueuedActivity.
	ActivityType  string
	Payload       json.RawMessage
	Serialization string `json:",omitempty"`
	Options       ScheduleOptions
	CatchUp       CatchUp
	CatchUpLimit  int

	// Set by the backend; UpsertSchedule ignores them.
	Paused     bool
	NextFireAt time.Time
	LastFireAt *time.Time
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

Schedule is a stored cron schedule: it enqueues an activity of ActivityType at each fire time of Cron in Timezone.

type ScheduleOptions

type ScheduleOptions struct {
	Priority             ActivityPriority  `json:"priority"`
	MaxRetries           uint32            `json:"max_retries"`
	TimeoutSeconds       uint64            `json:"timeout_seconds"`
	RetryDelaySeconds    uint64            `json:"retry_delay_seconds"`
	MaxRetryDelaySeconds uint64            `json:"max_retry_delay_seconds"`
	Metadata             map[string]string `json:"metadata"`
}

ScheduleOptions are the execution options of the activities a schedule fires. JSON keys are runnerq_schedules.options'.

func DecodeScheduleOptions

func DecodeScheduleOptions(raw []byte) (ScheduleOptions, error)

DecodeScheduleOptions reads stored options, absent keys taking their defaults.

func DefaultScheduleOptions

func DefaultScheduleOptions() ScheduleOptions

DefaultScheduleOptions are what absent keys of a stored schedule's options mean.

type ScheduleStorage

type ScheduleStorage interface {
	// UpsertSchedule creates or replaces a schedule by name. It keeps Paused
	// and LastFireAt, and NextFireAt unless Cron or Timezone changed; an
	// unchanged definition changes nothing. The schedule must pass
	// ValidateSchedule.
	UpsertSchedule(ctx context.Context, schedule Schedule) error
	// GetSchedule returns a not-found error for an unknown name.
	GetSchedule(ctx context.Context, name string) (*Schedule, error)
	// ListSchedules returns the queue's schedules by name.
	ListSchedules(ctx context.Context) ([]Schedule, error)
	PauseSchedule(ctx context.Context, name string) error
	// ResumeSchedule unpauses a paused schedule and moves NextFireAt to the
	// first fire time after now: ticks missed while paused are not caught up.
	ResumeSchedule(ctx context.Context, name string) error
	DeleteSchedule(ctx context.Context, name string) error
	// TriggerSchedule enqueues the schedule's activity now, paused or not,
	// keyed as a fire at now truncated to the second, and returns its ID (the
	// existing one when that key was fired already).
	TriggerSchedule(ctx context.Context, name string) (uuid.UUID, error)
	// FireDueSchedules fires up to limit due schedules, each in one
	// transaction that enqueues its fire times (ScheduleFireTimes) under
	// ScheduleIdempotencyKey and advances NextFireAt, so concurrent callers
	// fire each tick once. It returns how many activities it enqueued, and
	// the errors of schedules it could not fire, having fired the rest.
	FireDueSchedules(ctx context.Context, limit int) (int, error)
}

ScheduleStorage is an optional capability: cron schedules stored with the queue, which every engine of the queue fires (runnerq-spec schedules.md).

type SelfMaintainingStorage

type SelfMaintainingStorage interface {
	MaintainsItself() bool
}

SelfMaintainingStorage is storage that recovers expired leases and applies retention itself, such as a storage service that runs them for every queue. When MaintainsItself reports true the engine runs neither, and rejects its own retention settings rather than silently ignoring them: configure retention on the storage.

type SpawnStorage

type SpawnStorage interface {
	EnqueueForWorker(ctx context.Context, a QueuedActivity, ownerID uuid.UUID, workerID string) error
	EnqueueIdempotentForWorker(ctx context.Context, a *QueuedActivity, ownerID uuid.UUID, workerID string) (*IdempotencyResult, error)
}

SpawnStorage fences handler spawns on the spawning execution's claim: the claim check and insert commit together, so an execution that lost its lease (whose replacement may be issuing the same spawns) cannot add children. ownerID is the executing activity, the fence even for AsRoot spawns. Both methods return ErrClaimLost when workerID no longer holds ownerID.

type StepEntry

type StepEntry struct {
	ID         uuid.UUID
	ActivityID uuid.UUID
	Kind       string // run | sleep | signal | other
	Name       string
	State      ResultState
	Data       json.RawMessage // only when requested
	CreatedAt  time.Time
}

StepEntry is one durable step of an activity.

type StepEntryPage

type StepEntryPage struct {
	Items      []StepEntry
	NextCursor string
}

StepEntryPage is one page of steps.

type StepRecord

type StepRecord struct {
	Kind      string
	Name      string
	State     ResultState
	Data      json.RawMessage
	CreatedAt time.Time
}

StepRecord is one durable Run or Sleep checkpoint, decoded for inspection. Kind is "run" or "sleep"; Data is the Run result or the Sleep wake deadline.

type Storage

type Storage interface {
	QueueStorage
	ResultStorage
}

Storage is the surface a backend must provide. A new backend must pass the storage/storagetest conformance suite before it is trusted with durable execution. QueryStorage and CommandStorage are optional.

type StorageError

type StorageError struct {
	Kind    StorageErrorKind
	Message string
	Cause   error
	// Field names the offending input for ErrInvalidArgument/ErrUnsupported.
	Field string
}

StorageError is a backend-agnostic storage error.

func IsStorageError

func IsStorageError(err error) (*StorageError, bool)

IsStorageError extracts a *StorageError from err's chain.

func NewConfigurationError

func NewConfigurationError(msg string) *StorageError

func NewConflictError

func NewConflictError(msg string) *StorageError

func NewDuplicateActivityError

func NewDuplicateActivityError(msg string) *StorageError

func NewIdempotencyConflictError

func NewIdempotencyConflictError(msg string) *StorageError

func NewInternalError

func NewInternalError(msg string) *StorageError

func NewInvalidQueryError

func NewInvalidQueryError(field, msg string) *StorageError

NewInvalidQueryError reports malformed or out-of-range query input.

func NewNotFoundError

func NewNotFoundError(msg string) *StorageError

func NewSerializationError

func NewSerializationError(msg string) *StorageError

func NewTimeoutError

func NewTimeoutError(msg string) *StorageError

func NewUnavailableError

func NewUnavailableError(msg string) *StorageError

func NewUnsupportedQueryError

func NewUnsupportedQueryError(field, msg string) *StorageError

NewUnsupportedQueryError reports a query feature the backend cannot evaluate.

func (*StorageError) Error

func (e *StorageError) Error() string

func (*StorageError) IsRetryable

func (e *StorageError) IsRetryable() bool

IsRetryable reports whether a retry may succeed.

func (*StorageError) Unwrap

func (e *StorageError) Unwrap() error

type StorageErrorKind

type StorageErrorKind int

StorageErrorKind numbers are stored and sent on the wire; runnerq-spec fixes them.

const (
	ErrUnavailable         StorageErrorKind = spec.StorageErrorKindUnavailable
	ErrConflict            StorageErrorKind = spec.StorageErrorKindConflict
	ErrNotFound            StorageErrorKind = spec.StorageErrorKindNotFound
	ErrInternal            StorageErrorKind = spec.StorageErrorKindInternal
	ErrSerialization       StorageErrorKind = spec.StorageErrorKindSerialization
	ErrConfiguration       StorageErrorKind = spec.StorageErrorKindConfiguration
	ErrTimeout             StorageErrorKind = spec.StorageErrorKindTimeout
	ErrDuplicateActivity   StorageErrorKind = spec.StorageErrorKindDuplicateActivity
	ErrIdempotencyConflict StorageErrorKind = spec.StorageErrorKindIdempotencyConflict
	// ErrClaimLost: the execution no longer owns the activity.
	ErrClaimLost StorageErrorKind = spec.StorageErrorKindClaimLost
	// ErrCheckpointConflict: an immutable checkpoint has a different outcome.
	ErrCheckpointConflict StorageErrorKind = spec.StorageErrorKindCheckpointConflict
	// ErrInvalidArgument: malformed or out-of-range input named by Field.
	ErrInvalidArgument StorageErrorKind = spec.StorageErrorKindInvalidArgument
	// ErrUnsupported: a query feature the backend cannot evaluate, named by
	// Field.
	ErrUnsupported StorageErrorKind = spec.StorageErrorKindUnsupported
)

Directories

Path Synopsis
Package storagetest is the conformance suite for storage.Storage backends.
Package storagetest is the conformance suite for storage.Storage backends.

Jump to

Keyboard shortcuts

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