runnerq

package module
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: 20 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.

README

RunnerQ for Go

Durable Golang functions, with pluggable storage.

Go Reference CI Release

Getting started · Docs · Examples

Add crash-proof background jobs and multi-step workflows to your Go app in a few lines — no separate orchestrator to run, no new infrastructure. RunnerQ is a library: import it, point it at your storage (PostgreSQL is built in), and write workflows as ordinary Go functions. When a process crashes mid-workflow, it resumes from where it left off without redoing completed work.

func (h *Checkout) Handle(ctx runnerq.ActivityContext, payload json.RawMessage) (json.RawMessage, error) {
    // Each step is checkpointed. Crash after the charge is recorded and
    // restart — it isn't repeated; the workflow resumes at shipping.
    receipt, err := runnerq.RunStep(ctx, "charge-card", func(c context.Context) (Receipt, error) {
        return chargeCard(c, payload)   // at most once per recorded success
    })
    if err != nil {
        return nil, err
    }

    ship, err := runnerq.Activity[Ship](ctx.ActivityExecutor).Step("ship").Payload(payload).Execute(ctx.Ctx)
    if err != nil {
        return nil, err
    }
    return ship.GetResult(ctx.Ctx)   // parent parks here — frees the worker, survives deploys
}

The guarantee: steps run at least once, and a step whose result is recorded never runs again. A crash after chargeCard returns but before its checkpoint commits runs it again, so pass an idempotency key to your payment provider. See the contract.

See it for real: examples/02-crash-and-resume charges an order, lets you Ctrl-C it, and resumes on restart without double-charging. That demo is the whole pitch in 30 seconds.

Install

go get github.com/runnerq/runnerq-go@main

Requires Go 1.25 or later. The generic helpers are package functions, runnerq.RunStep(ctx, name, fn) and runnerq.Activity[T](exec); on Go 1.27 and later they are also methods (ctx.RunStep(name, fn), exec.Activity[T]()), the same calls in another spelling.

The API in this README is on main and not in a tagged release yet; see CHANGELOG.md. The latest release, v0.5.1, has the older named-activity API and the old module path, github.com/alob-mtc/runnerq-go. To move to this one, rewrite your imports:

grep -rl alob-mtc/runnerq-go --include='*.go' . | xargs sed -i 's#github.com/alob-mtc/runnerq-go#github.com/runnerq/runnerq-go#g'

Quick start

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "log"

    "github.com/runnerq/runnerq-go"
    "github.com/runnerq/runnerq-go/storage/postgres"
)

type Greeting struct{ runnerq.DefaultDeadLetterHandler }

func (h *Greeting) Handle(ctx runnerq.ActivityContext, payload json.RawMessage) (json.RawMessage, error) {
    greeting, err := runnerq.RunStep(ctx, "compose", func(context.Context) (string, error) {
        var name string
        if err := json.Unmarshal(payload, &name); err != nil {
            return "", runnerq.NewNonRetryError(err.Error())
        }
        return "hello, " + name, nil
    })
    if err != nil {
        return nil, err
    }
    return json.Marshal(greeting)
}

func main() {
    ctx := context.Background()

    backend, err := postgres.New(ctx, "postgres://postgres:runnerq@localhost:5432/runnerq", "my_app")
    if err != nil {
        log.Fatal(err)
    }
    defer backend.Close()

    engine, err := runnerq.Builder().Backend(backend).MaxWorkers(8).Build()
    if err != nil {
        log.Fatal(err)
    }
    engine.RegisterActivity(&Greeting{}) // serves activity type "Greeting"
    go engine.Start(ctx)

    future, _ := runnerq.Activity[Greeting](engine.GetActivityExecutor()).
        Payload(json.RawMessage(`"world"`)).
        Execute(ctx)

    result, _ := future.GetResult(ctx)
    fmt.Println(string(result))   // "hello, world"
}

The typed form above derives the activity name from the handler type, so nothing can drift. When a name must outlive a refactor, use the named form (RegisterActivityWithName, ActivityNamed); see Naming activities.

Why RunnerQ

Background work that touches the real world — charging cards, sending email, calling APIs, orchestrating multi-step jobs — has to survive crashes, deploys, and retries without doing things twice. The usual options are a heavy workflow server (a cluster to operate) or a plain task queue (no durability — you hand-roll idempotency and recovery yourself).

RunnerQ gives you durable execution as a library:

  • A workflow is just a Go function. Orchestration is normal control flow — loops, conditionals, error handling — not a DSL or a DAG.
  • Steps are checkpointed. Completed work is skipped on replay, so retries and restarts are cheap and recorded steps don't run again.
  • Workflows pause for free. Sleep for days or wait for a webhook while holding zero workers — paused workflows are just stored state.
  • Pluggable storage. PostgreSQL is built in; implement the storage interface to use anything else. No orchestrator cluster, no broker, no control-plane bill. Scale by adding stateless worker processes.

Good fits: payment flows that must not redo completed steps, processing each webhook once, approval flows that wait days for a human, and fanning a batch out across workers. The examples cover each of these.

Features

Durable workflows that survive crashes

A handler that calls runnerq.RunStep is a durable workflow. Each step's result is checkpointed; if the process dies, the handler replays and completed steps return their stored results instead of re-executing.

receipt, err := runnerq.RunStep(ctx, "charge-card", func(c context.Context) (Receipt, error) {
    return chargeCard(c, payload)   // at most once per recorded success
})
Orchestration that fast-forwards on retry

Spawn child activities with .Step(name). A retried parent reattaches to the children it already launched instead of duplicating them, and parents that await children park in storage — no goroutine, no lease, no retry burned while they wait.

fut, _ := runnerq.Activity[Reserve](ctx.ActivityExecutor).Step("reserve").Payload(p).Execute(ctx.Ctx)
reserved, _ := fut.GetResult(ctx.Ctx)   // memoized on replay
Durable timers and signals

Sleep inside a workflow for seconds or weeks. The deadline is persisted — a restart resumes the remainder — and long sleeps hold no worker.

ctx.Sleep("cooling-off", 24 * time.Hour)   // survives restarts; frees the worker

Wait for an approval, a webhook, or a payment confirmation. The workflow parks until a signal arrives, delivered from anywhere — even another process.

decision, err := ctx.WaitForSignal("approval", 48*time.Hour)   // parks, holds no worker
// from an HTTP handler, a Slack action, a Kafka consumer:
engine.Signal(ctx, activityID, "approval", payload)
Exactly-once enqueue

Idempotency keys make enqueuing exactly-once — dedupe webhooks and event handlers with one option.

executor.ActivityNamed("process_event").
    Payload(p).
    IdempotencyKeyOption(eventID, runnerq.ReturnExisting).   // duplicate deliveries collapse to one
    Execute(ctx)
A real queue underneath

Priorities, exponential-backoff retries, a dead-letter queue, scheduling, and worker-level type filtering so slow jobs can't starve latency-sensitive ones.

executor.ActivityNamed("send_email").
    Payload(p).
    Priority(runnerq.PriorityHigh).
    MaxRetries(5).
    Timeout(2 * time.Minute).
    Delay(30 * time.Second).
    Execute(ctx)
Cron schedules

Declare a schedule on the engine and every engine of the queue fires it, once per tick, in any IANA time zone and across daylight-saving changes. Pause, resume, trigger and list schedules from any process.

engine.RegisterSchedule(runnerq.Schedule{
    Name: "nightly-report", Cron: "30 2 * * *", Timezone: "Europe/London",
    Activity: runnerq.NameOf[NightlyReport](),
})

See Schedules.

Pluggable storage

PostgreSQL is built in. To use something else, implement storage.Storage and run the conformance suite in storage/storagetest against it: a backend that passes can replace Postgres without the engine noticing. See Storage backends.

A console for your workers

The conductor agent connects your workers to a console that shows every activity, its steps, events and results, read live from your own database through the workers. Your data stays where it is. See Conductor agent.

Manage work from code

runnerq.NewClient(backend) needs no engine. It submits, signals and awaits activities, lists them, and cancels, retries, reschedules, runs now, reprioritises or deletes them. A cancel stops a running handler on whichever worker holds it. Every command is idempotent by command id.

client := runnerq.NewClient(backend)
res, err := client.Cancel(ctx, runnerq.IDs(id), runnerq.WithReason("customer asked"))
res, err = client.Retry(ctx, runnerq.IDs(failedID), runnerq.ResetAttempts())

Examples

Runnable, realistic, copy-pasteable — each in examples/ with its own README. docker compose up -d once, then go run . in any of them.

# Example Shows
01 hello-workflow a durable two-step workflow
02 crash-and-resume kill it mid-flight; it resumes without redoing work
03 steps-and-retries child activities memoized across a retry
04 checkpoint-side-effects a recorded charge isn't repeated when the handler retries
05 durable-sleep timers that survive restarts
06 human-approval pause for an approval, delivered over HTTP
07 fan-out spawn many children, run them in parallel
08 exactly-once-webhook idempotency keys collapse duplicate deliveries
09 cross-process-futures enqueue in a web tier, await by ID anywhere
10 retries-and-dead-letter backoff, the dead-letter queue, OnDeadLetter
11 retention TTL cleanup of completed workflows
12 workload-isolation many worker fleets sharing one queue
13 cron-schedules a cron schedule fired once per tick across engines

How it compares

RunnerQ Temporal / Cadence Plain task queue (River, Asynq, …)
Durable workflows ✅ ✅ ❌
Deploy model a Go library a server cluster to operate a library
Infrastructure Postgres you already run, or your own storage backend server + its own datastore Postgres or Redis
Workflow code plain Go, step-memoized plain code, full replay-determinism n/a
Durable timers / signals ✅ ✅ ❌
Scale add stateless worker processes scale the cluster add workers
  • Use RunnerQ when you want durable, crash-safe workflows or queues with minimal new infrastructure, and you're already running Postgres.
  • Reach for a dedicated workflow server (Temporal, Cadence) if you need many SDK languages or want workflow orchestration decoupled from your app and your database.
  • A plain queue (River, Asynq, SQS) is enough if you only need fire-and-forget tasks and don't need workflows, steps, signals, or durable timers.

Documentation

Full reference in docs/:

Status

RunnerQ is pre-1.0. The durable-execution core (steps, checkpoints, signals, durable sleep, crash recovery) is built and integration-tested against Postgres, but APIs may still change before 1.0. See RELEASING.md for the stability policy.

Development

Values and rules shared with the TypeScript SDK (key formats, notification channels, error kinds) come from runnerq-spec, checked out as the spec submodule:

git submodule update --init
go generate ./internal/spec   # after bumping spec: regenerate the constants
RUNNERQ_TEST_DSN=postgres://... go test ./... -race
# runnerq-spec's cross-language scenarios, through this SDK's conformance driver:
go build -o /tmp/conformancedriver ./internal/conformancedriver
go run -C spec/tools/conformance . -driver go=/tmp/conformancedriver

The vector tests (TestSpec*) need the submodule; the Postgres tests need RUNNERQ_TEST_DSN.

License

MIT — see LICENSE.

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

View Source
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).

View Source
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.

View Source
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).

View Source
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.

View Source
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.

View Source
const DefaultMaxActivityDepth uint16 = 32

DefaultMaxActivityDepth is MaxActivityDepth's default.

View Source
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

View Source
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

func IsActivityNotFound(err error) bool

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

func IsCancelled(err error) bool

IsCancelled reports whether err is an awaited activity's cancellation (Client.Cancel), as GetResult and Client.Result return it.

func IsCommandConflict

func IsCommandConflict(err error) bool

IsCommandConflict reports whether err is a management command rejected because its command id (WithCommandID) was already used with other input.

func IsSignalTimeout

func IsSignalTimeout(err error) bool

IsSignalTimeout reports whether err is a WaitForSignal timeout.

func IsYield

func IsYield(err error) bool

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

func NameOf[T any]() string

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

func ValidTraceparent(s string) bool

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

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

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

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

type ActivityError struct {
	Retryable bool
	Message   string
}

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.

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 NewClient

func NewClient(backend storage.Storage) *Client

NewClient returns a Client on backend.

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) Backend

func (c *Client) Backend() storage.Storage

Backend is the client's backend.

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

func (c *Client) Get(ctx context.Context, activityID uuid.UUID) (*storage.ActivityRecord, error)

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

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

func (c *Client) Result(ctx context.Context, activityID uuid.UUID) (json.RawMessage, error)

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

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

type InFlightActivity struct {
	ID        uuid.UUID
	Type      string
	Attempt   int
	StartedAt time.Time
}

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

func NewSchedules(backend storage.Storage) (*Schedules, error)

NewSchedules manages the schedules of backend's queue. It fails when the backend does not implement storage.ScheduleStorage.

func (*Schedules) Delete

func (m *Schedules) Delete(ctx context.Context, name string) error

Delete removes a schedule. Activities it already enqueued are unaffected.

func (*Schedules) Get

func (m *Schedules) Get(ctx context.Context, name string) (*storage.Schedule, error)

Get returns a schedule as stored; a not-found error for an unknown name.

func (*Schedules) List

func (m *Schedules) List(ctx context.Context) ([]storage.Schedule, error)

List returns the queue's schedules by name.

func (*Schedules) Pause

func (m *Schedules) Pause(ctx context.Context, name string) error

Pause stops a schedule firing until Resume.

func (*Schedules) Resume

func (m *Schedules) Resume(ctx context.Context, name string) error

Resume restarts a paused schedule from its next fire time after now; ticks missed while paused are not caught up.

func (*Schedules) Trigger

func (m *Schedules) Trigger(ctx context.Context, name string) (*ActivityFuture, error)

Trigger enqueues the schedule's activity now, even while paused, without changing its fire times. Triggers within the same second share one activity.

func (*Schedules) Upsert

func (m *Schedules) Upsert(ctx context.Context, s Schedule) error

Upsert creates the schedule or replaces its definition. A paused schedule stays paused, and its next fire time is kept unless Cron or Timezone changed.

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

type Step[R any] func(ctx context.Context) (R, error)

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.

func IDs

func IDs(ids ...uuid.UUID) Target

IDs targets the activities with these ids.

func Matching

func Matching(filter storage.QueryFilter, max int) Target

Matching targets up to max activities matching filter that the command can act on.

type TraceAttribute

type TraceAttribute struct {
	Key   string
	Value any
}

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

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

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

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

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

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

ShutdownGrace bounds the shutdown drain (default 30s, at least 1s).

func (*WorkerEngineBuilder) Tracer

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
)

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.

Jump to

Keyboard shortcuts

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