Documentation
¶
Overview ¶
Package workflow runs durable, multi-step processes that span hours or days and survive sleeps, webhooks, deploys, and worker restarts.
Define a workflow as a struct whose fields hold its input, with a Handle method that receives a *Run. Perform durable work through methods on Run such as Run.Step, Run.Do, Run.Sleep, and Run.WaitFor:
func (o OnboardUser) Handle(run *workflow.Run) error {
if err := run.Do("send welcome email", o.sendWelcomeEmail); err != nil {
return err
}
if err := run.Sleep(3 * 24 * time.Hour); err != nil {
return err
}
projects, err := run.Step("count projects", o.countProjects)
if err != nil || projects > 0 {
return err
}
return run.Do("send tips", o.sendTips)
}
Register workflow types in laravel.Options.Workflows and start runs with Start or StartOnce. Each advance runs as a queued job: the worker calls Handle from the top, returns previously recorded results from the journal without re-running completed operations, and executes the first unrecorded operation. When a run must wait for a sleep, a Token, or a step retry, that operation suspends the run and ends the advance so a later job resumes from the same point.
Index ¶
- Constants
- Variables
- func Cancel(ctx context.Context, id RunID, reason string) (bool, error)
- func CreateTables(ctx context.Context) error
- func Fatal(err error) error
- func Jobs() []any
- func ResumeURL[T any](ctx context.Context, token Token[T], value T, options ...URLOption) (string, error)
- func RetryAfter(wait time.Duration, err error) error
- func RetryAt(at time.Time, err error) error
- func Routes(route *routing.Router)
- func WebhookURL[T any](ctx context.Context, token Token[T], options ...URLOption) (string, error)
- type Accepted
- type Attempt
- type Claim
- type ClaimState
- type Config
- type DatabaseStore
- func (s *DatabaseStore) Cancel(ctx context.Context, id RunID, reason string, now time.Time) (bool, error)
- func (s *DatabaseStore) Claim(ctx context.Context, id RunID, lease time.Duration) (Claim, error)
- func (s *DatabaseStore) Create(ctx context.Context, run NewRun) (RunID, error)
- func (s *DatabaseStore) Entries(ctx context.Context, id RunID) ([]Entry, error)
- func (s *DatabaseStore) Find(ctx context.Context, id RunID) (RunRecord, bool, error)
- func (s *DatabaseStore) List(ctx context.Context, filter Filter) ([]RunRecord, error)
- func (s *DatabaseStore) Overdue(ctx context.Context, now time.Time) ([]RunRecord, error)
- func (s *DatabaseStore) Prune(ctx context.Context, before time.Time) (int64, error)
- func (s *DatabaseStore) Record(ctx context.Context, id RunID, lease Lease, entry Entry) error
- func (s *DatabaseStore) Release(ctx context.Context, id RunID, lease Lease, outcome Outcome, now time.Time) error
- func (s *DatabaseStore) Renew(ctx context.Context, id RunID, lease Lease, duration time.Duration) error
- func (s *DatabaseStore) Resume(ctx context.Context, token, value string) (RunID, bool, error)
- func (s *DatabaseStore) Retry(ctx context.Context, id RunID, now time.Time) (bool, error)
- func (s *DatabaseStore) SetAttributes(ctx context.Context, id RunID, lease Lease, attributes map[string]string) error
- func (s *DatabaseStore) StopWaiting(ctx context.Context, id RunID, lease Lease, token string) error
- func (s *DatabaseStore) Wait(ctx context.Context, id RunID, lease Lease, token string, number int) (string, bool, error)
- func (s *DatabaseStore) Waiting(ctx context.Context, token string) (RunID, bool, error)
- func (s *DatabaseStore) WithPrefix(prefix string) *DatabaseStore
- type Entry
- type Filter
- type Inbox
- type Kind
- type Lease
- type MemoryStore
- func (s *MemoryStore) Cancel(_ context.Context, id RunID, reason string, now time.Time) (bool, error)
- func (s *MemoryStore) Claim(_ context.Context, id RunID, lease time.Duration) (Claim, error)
- func (s *MemoryStore) Create(_ context.Context, run NewRun) (RunID, error)
- func (s *MemoryStore) Entries(_ context.Context, id RunID) ([]Entry, error)
- func (s *MemoryStore) Find(_ context.Context, id RunID) (RunRecord, bool, error)
- func (s *MemoryStore) List(_ context.Context, filter Filter) ([]RunRecord, error)
- func (s *MemoryStore) Overdue(_ context.Context, now time.Time) ([]RunRecord, error)
- func (s *MemoryStore) Prune(_ context.Context, before time.Time) (int64, error)
- func (s *MemoryStore) Record(_ context.Context, id RunID, lease Lease, entry Entry) error
- func (s *MemoryStore) Release(_ context.Context, id RunID, lease Lease, outcome Outcome, now time.Time) error
- func (s *MemoryStore) Renew(_ context.Context, id RunID, lease Lease, duration time.Duration) error
- func (s *MemoryStore) Resume(_ context.Context, token, value string) (RunID, bool, error)
- func (s *MemoryStore) Retry(_ context.Context, id RunID, now time.Time) (bool, error)
- func (s *MemoryStore) SetAttributes(_ context.Context, id RunID, lease Lease, attributes map[string]string) error
- func (s *MemoryStore) StopWaiting(_ context.Context, id RunID, lease Lease, token string) error
- func (s *MemoryStore) Wait(_ context.Context, id RunID, lease Lease, token string, number int) (string, bool, error)
- func (s *MemoryStore) Waiting(_ context.Context, token string) (RunID, bool, error)
- type NewRun
- type Options
- type Outcome
- type PendingStart
- func Attribute(name, value string) *PendingStart
- func ClaimToken[S ~string](token S) *PendingStart
- func Delay(d time.Duration) *PendingStart
- func DelayUntil(t time.Time) *PendingStart
- func OnConnection(name string) *PendingStart
- func OnQueue(name string) *PendingStart
- func PurgeWhenFinished() *PendingStart
- func (p *PendingStart) Attribute(name, value string) *PendingStart
- func (p *PendingStart) ClaimToken[S ~string](token S) *PendingStart
- func (p *PendingStart) Delay(d time.Duration) *PendingStart
- func (p *PendingStart) DelayUntil(t time.Time) *PendingStart
- func (p *PendingStart) OnConnection(name string) *PendingStart
- func (p *PendingStart) OnQueue(name string) *PendingStart
- func (p *PendingStart) PurgeWhenFinished() *PendingStart
- func (p *PendingStart) Start(ctx context.Context, workflow any) (RunID, error)
- func (p *PendingStart) StartOnce(ctx context.Context, key string, workflow any) (Started, error)
- type Recorded
- type Recorder
- type Resumed
- type Run
- func (r *Run) Attributes() map[string]string
- func (r *Run) Do(name string, work func(ctx context.Context) error, options ...StepOption) error
- func (r *Run) Go[T any](name string, work func(ctx context.Context) (T, error), options ...StepOption) *Task[T]
- func (r *Run) ID() RunID
- func (r *Run) Inbox[T any](token Token[T]) *Inbox[T]
- func (r *Run) NewToken[T any]() Token[T]
- func (r *Run) SetAttribute(name, value string)
- func (r *Run) Sleep(d time.Duration, options ...SleepOption) error
- func (r *Run) SleepUntil(t time.Time, options ...SleepOption) error
- func (r *Run) StartedAt() time.Time
- func (r *Run) Step[T any](name string, work func(ctx context.Context) (T, error), options ...StepOption) (T, error)
- func (r *Run) WaitFor[T any](token Token[T]) (T, error)
- func (r *Run) WaitWithin[T any](token Token[T], timeout time.Duration) (T, bool, error)
- type RunCancelled
- type RunCompleted
- type RunFailed
- type RunID
- type RunInfo
- type RunRecord
- type SleepOption
- type StartOutcome
- type Started
- type Status
- type StepFailedError
- type StepInfo
- type StepOption
- type Store
- type Task
- type Token
- type TokenOwnedError
- type URLOption
- type Workflows
- func (w *Workflows) Advance(ctx context.Context, id RunID, replacements map[string]string) error
- func (w *Workflows) Fake(r Recorder) bool
- func (w *Workflows) Recover(ctx context.Context) (int, error)
- func (w *Workflows) Retry(ctx context.Context, id RunID) (bool, error)
- func (w *Workflows) Save(ctx context.Context, workflow any, tokens ...string) (RunID, error)
- func (w *Workflows) Store() Store
Constants ¶
const PurgedInput = "null"
PurgedInput is the placeholder JSON stored in RunRecord.Input after a run's data has been purged.
const ( // RouteName is the name of the built-in resume route mounted at // /_workflow/resume by [Routes]. RouteName = "workflow.resume" )
Variables ¶
var ErrLeaseLost = errors.New("workflow: advance lost its lease")
ErrLeaseLost is returned by fenced Store write methods (Store.Record, Store.Wait, Store.StopWaiting, Store.SetAttributes, Store.Renew, and Store.Release) when the run is no longer Running or the caller's Lease token no longer matches the active lease.
Functions ¶
func Cancel ¶
Cancel marks run id as Cancelled so it will not advance again, and dispatches RunCancelled. Any step currently running finishes, but no later step starts. The optional reason is stored on RunInfo.Error and included in RunCancelled:
cancelled, err := workflow.Cancel(ctx, id, "the customer closed their account")
Cancel returns false if the run does not exist or has already ended. It panics if ctx does not carry an application scope.
func CreateTables ¶
CreateTables creates the five tables used by the database workflow store: workflow_runs, workflow_steps, workflow_waits, workflow_resumes, and workflow_attributes. Register it directly in database/migrations/migrations.go:
{Name: "2026_01_01_000000_create_workflow_tables", Run: workflow.CreateTables}
func Fatal ¶
Fatal wraps err to mark a step failure as permanent so the step fails immediately without retrying, such as for a declined card:
receipt, err := gateway.Charge(ctx, o.OrderID)
if errors.Is(err, gateway.ErrDeclined) {
return Receipt{}, workflow.Fatal(err)
}
func Jobs ¶
func Jobs() []any
Jobs returns the internal queue job types required to advance workflow runs.
func ResumeURL ¶
func ResumeURL[T any](ctx context.Context, token Token[T], value T, options ...URLOption) (string, error)
ResumeURL creates a signed URL that resumes the run that owns token with value when requested via GET or POST, such as an approval link in an email:
link, err := workflow.ResumeURL(ctx, Decision(o.ExpenseID), Approved, workflow.Expires(3*24*time.Hour))
ResumeURL is pure and records nothing in the journal, so re-running a step that builds a URL is safe. The built-in route responds with 202 Accepted, or with 404 Not Found when no unfinished run owns the token, so a webhook sender retries. Because the signature proves only that your application issued the URL and not who opened it, anyone with the link (including email link scanners) can trigger it. For sensitive actions, pass Through pointing at an authenticated route, or link to a page whose form submits to Resume.
func RetryAfter ¶
RetryAfter wraps err to schedule the step's next attempt after wait instead of the configured Backoff, such as when honoring an API rate-limit header. The failed attempt still counts toward Tries:
if response.Status() == http.StatusTooManyRequests {
return workflow.RetryAfter(time.Minute, errors.New("the CRM is busy"))
}
func RetryAt ¶
RetryAt wraps err to schedule the step's next attempt at time at instead of the configured Backoff. The failed attempt still counts toward Tries.
func Routes ¶
Routes registers the built-in GET and POST /_workflow/resume endpoint under RouteName. The laravel package mounts it outside web middleware when workflows are configured so external webhooks can POST without CSRF tokens.
func WebhookURL ¶
WebhookURL creates a signed URL that resumes the run that owns token using the JSON body that an external service POSTs to it:
callback, err := workflow.WebhookURL(ctx, Scan(o.ExpenseID))
An empty body resumes the run with JSON null, while invalid JSON returns 400 without resuming anything. The run decodes the body as T, failing if decoding fails. Because anyone with the URL can post any JSON body, use a type that matches the sender's payload or pass Through with a handler that calls Accept to validate the payload before resuming.
Types ¶
type Accepted ¶
type Accepted[T any] struct { // Value is the decoded resume value from the signed URL or webhook body. Value T `json:"value"` // Outcome reports whether the run that owns the token took the value // ([ResumeDelivered]), no unfinished run owns it, such as when someone // clicks a link after the run finished ([ResumeNotFound]), or the resume // awaits a transaction commit ([ResumeOnCommit]). Outcome Resumed `json:"outcome"` }
Accepted holds the decoded value and resume outcome returned by Accept.
func Accept ¶
Accept verifies a signed resume or webhook request on a route targeted by Through, resumes the run that owns the token, and returns the decoded value:
func Decided(r *web.Request) *web.Response {
resume, err := workflow.Accept[workflows.Decision](r)
if err != nil {
return web.Fail(err)
}
if resume.Outcome == workflow.ResumeNotFound {
return web.View("expenses.already-decided", nil)
}
return web.View("expenses.decided", map[string]any{"approved": resume.Value == workflows.Approved})
}
Accept returns a *web.Error without resuming any run when the signature is invalid or expired (403), when the request method is HEAD (405), or when the URL is not a resume URL or its JSON body cannot decode as T (400).
type Attempt ¶
type Attempt struct {
// Key uniquely identifies this step within this run ("<runID>:<stepName>")
// and stays identical across retries. Pass it as an API idempotency key so
// retries after a crash do not duplicate side effects.
Key string
// Step is the step's name.
Step string
// Number is the 1-based attempt number.
Number int
}
Attempt describes the currently executing attempt of a workflow step, as returned by CurrentStep.
func CurrentStep ¶
CurrentStep returns the Attempt metadata for the running step, including a stable idempotency key:
func (o Checkout) chargeCard(ctx context.Context) (Receipt, error) {
return payments.Charge(ctx, o.OrderID, workflow.CurrentStep(ctx).Key)
}
CurrentStep panics if ctx is not the context passed to a step function (for example, if called directly with *Run inside Handle).
type Claim ¶
type Claim struct {
// State reports whether the run was claimed, held, or already ended.
State ClaimState
// Run is the claimed run record when State is [Claimed].
Run RunRecord
// Entries holds the run's journal entries when State is [Claimed].
Entries []Entry
// Lease is the fencing token for this claim when State is [Claimed].
Lease Lease
}
Claim is the result of Store.Claim, containing the run record, journal entries, and fencing Lease when State is Claimed.
type ClaimState ¶
type ClaimState int
ClaimState reports the outcome of a Store.Claim attempt.
const ( // Claimed indicates that the caller acquired the lease and the run is now // [Running]. Claimed ClaimState = iota + 1 // Held indicates that another worker currently holds the run's lease. Held // Ended indicates that the run does not exist or has already ended. Ended )
type Config ¶
type Config struct {
// Workflows lists one value of each workflow type the application starts,
// such as workflows.OnboardUser{}.
Workflows []any
// Store persists workflow runs and journals. Nil uses [NewMemoryStore].
Store Store
// Logger receives warning logs when a step fails and is scheduled for
// retry. Nil uses [slog.Default].
Logger *slog.Logger
}
type DatabaseStore ¶
type DatabaseStore struct {
// contains filtered or unexported fields
}
DatabaseStore implements Store using five database tables: workflow_runs, workflow_steps, workflow_waits, workflow_resumes, and workflow_attributes. Each statement commits independently so concurrent DatabaseStore.Wait and DatabaseStore.Resume calls observe each other's writes.
workflow_runs.lease_token holds the active Lease token while a worker holds a run, so stalled advances whose lease expired cannot write to the run, its steps, its waits, or its attributes.
A row of workflow_waits means the run owns the token, and the primary key on the token keeps two runs from owning it. Its number is the value the run waits for now, or NULL when it doesn't wait. workflow_resumes numbers the values each run keeps for each token, and its primary key on the run, token, and number keeps two resumes from taking one number. A run gives up its tokens in the statement after the one that finishes it. If the process stops in between, the next run that claims one of those tokens finds its owner finished and takes the token over.
func NewDatabaseStore ¶
func NewDatabaseStore(conn *db.DB) *DatabaseStore
NewDatabaseStore constructs a DatabaseStore backed by conn.
func (*DatabaseStore) Cancel ¶
func (s *DatabaseStore) Cancel(ctx context.Context, id RunID, reason string, now time.Time) (bool, error)
Cancel implements Store.Cancel.
func (*DatabaseStore) Claim ¶
Claim implements Store.Claim.
func (*DatabaseStore) Create ¶
Create implements Store.Create.
func (*DatabaseStore) Entries ¶
Entries implements Store.Entries.
func (*DatabaseStore) Find ¶
Find implements Store.Find.
func (*DatabaseStore) List ¶
List implements Store.List.
func (*DatabaseStore) Overdue ¶
Overdue implements Store.Overdue.
func (*DatabaseStore) Prune ¶
Prune implements Store.Prune.
func (*DatabaseStore) Record ¶
Record implements Store.Record.
func (*DatabaseStore) Release ¶
func (s *DatabaseStore) Release(ctx context.Context, id RunID, lease Lease, outcome Outcome, now time.Time) error
Release implements Store.Release.
func (*DatabaseStore) Renew ¶
func (s *DatabaseStore) Renew(ctx context.Context, id RunID, lease Lease, duration time.Duration) error
Renew implements Store.Renew.
func (*DatabaseStore) Resume ¶
Resume implements Store.Resume.
func (*DatabaseStore) Retry ¶
Retry implements Store.Retry.
func (*DatabaseStore) SetAttributes ¶
func (s *DatabaseStore) SetAttributes(ctx context.Context, id RunID, lease Lease, attributes map[string]string) error
SetAttributes implements Store.SetAttributes.
func (*DatabaseStore) StopWaiting ¶
StopWaiting implements Store.StopWaiting.
func (*DatabaseStore) Wait ¶
func (s *DatabaseStore) Wait(ctx context.Context, id RunID, lease Lease, token string, number int) (string, bool, error)
Wait implements Store.Wait.
func (*DatabaseStore) Waiting ¶
Waiting implements Store.Waiting.
func (*DatabaseStore) WithPrefix ¶
func (s *DatabaseStore) WithPrefix(prefix string) *DatabaseStore
WithPrefix returns a copy of s whose table names are prefixed with prefix, such as "app_" for "app_workflow_runs".
type Entry ¶
type Entry struct {
// Kind identifies the entry type.
Kind Kind
// Name is the step or sleep name, the wait token, or the inbox token and
// read number.
Name string
// Status is [Pending], [Completed], or [Failed].
Status Status
// Tries is the number of attempts made for a step entry.
Tries int
// Output holds the JSON-encoded step return value or resume payload, or
// empty for a timed-out wait or incomplete entry.
Output string
// Error holds the error message from the step's last failed attempt.
Error string
// WakeAt is when the sleep ends, the wait times out, or the next retry is
// scheduled, or the zero time.
WakeAt time.Time
// StartedAt is when the run first reached this entry.
StartedAt time.Time
// FinishedAt is when the entry completed or failed, or the zero time.
FinishedAt time.Time
}
Entry represents a single line in a run's journal: a step, sleep, wait, or inbox read, uniquely identified within the run by Kind and Name.
type Filter ¶
type Filter struct {
// Status matches runs with this status, or all statuses when empty.
Status Status
// Workflow matches runs with this registered workflow name, or all
// workflows when empty.
Workflow string
// Attributes matches runs that contain every key-value pair in this map.
Attributes map[string]string
// Limit caps the number of returned runs. Zero means no limit.
Limit int
}
Filter selects which runs Store.List returns.
type Inbox ¶
type Inbox[T any] struct { // contains filtered or unexported fields }
Inbox receives an ordered stream of values delivered to a Token by Resume. Open one with Run.Inbox and read values with Inbox.Next or Inbox.NextWithin.
type Kind ¶
type Kind string
Kind identifies the type of operation recorded in a journal Entry.
const ( // KindStep records a step from [Run.Step], [Run.Do], or [Run.Go]. KindStep Kind = "step" // KindSleep records a sleep from [Run.Sleep] or [Run.SleepUntil]. KindSleep Kind = "sleep" // KindWait records a token wait from [Run.WaitFor] or [Run.WaitWithin]. KindWait Kind = "wait" // KindInbox records a single read of an [Inbox], named "<token> #<read>" // such as "expenses.7.votes #2". KindInbox Kind = "inbox" )
type Lease ¶
type Lease string
Lease identifies one advance's lease on a workflow run.
Store.Claim returns a distinct non-empty Lease per claim, and every in-advance Store write carries it back so a stalled advance whose lease expired cannot overwrite a newer advance's work.
type MemoryStore ¶
type MemoryStore struct {
// contains filtered or unexported fields
}
MemoryStore is an in-memory Store intended for tests and local development. All runs are lost when the process exits, so use DatabaseStore in production. Its methods are safe for concurrent use.
func NewMemoryStore ¶
func NewMemoryStore() *MemoryStore
NewMemoryStore constructs an empty MemoryStore.
func (*MemoryStore) Cancel ¶
func (s *MemoryStore) Cancel(_ context.Context, id RunID, reason string, now time.Time) (bool, error)
Cancel implements Store.Cancel.
func (*MemoryStore) Claim ¶
Claim implements Store.Claim.
func (*MemoryStore) Create ¶
Create implements Store.Create.
func (*MemoryStore) Entries ¶
Entries implements Store.Entries.
func (*MemoryStore) Find ¶
Find implements Store.Find.
func (*MemoryStore) List ¶
List implements Store.List.
func (*MemoryStore) Overdue ¶
Overdue implements Store.Overdue.
func (*MemoryStore) Prune ¶
Prune implements Store.Prune.
func (*MemoryStore) Record ¶
Record implements Store.Record.
func (*MemoryStore) Release ¶
func (s *MemoryStore) Release(_ context.Context, id RunID, lease Lease, outcome Outcome, now time.Time) error
Release implements Store.Release.
func (*MemoryStore) Renew ¶
Renew implements Store.Renew.
func (*MemoryStore) Resume ¶
Resume implements Store.Resume.
func (*MemoryStore) Retry ¶
Retry implements Store.Retry.
func (*MemoryStore) SetAttributes ¶
func (s *MemoryStore) SetAttributes(_ context.Context, id RunID, lease Lease, attributes map[string]string) error
SetAttributes implements Store.SetAttributes.
func (*MemoryStore) StopWaiting ¶
StopWaiting implements Store.StopWaiting.
func (*MemoryStore) Wait ¶
func (s *MemoryStore) Wait(_ context.Context, id RunID, lease Lease, token string, number int) (string, bool, error)
Wait implements Store.Wait.
func (*MemoryStore) Waiting ¶
Waiting implements Store.Waiting.
type NewRun ¶
type NewRun struct {
// ID is the run's unique identifier.
ID RunID
// Workflow is the workflow's registered name.
Workflow string
// Input holds the JSON-encoded workflow struct.
Input string
// Context holds the JSON-encoded context values captured at start and
// restored on every advance.
Context string
// Connection is the queue connection for the run's advance jobs.
Connection string
// Queue is the queue name for the run's advance jobs.
Queue string
// CreatedAt is when the run started.
CreatedAt time.Time
// WakeAt is when the run is eligible for its first advance.
WakeAt time.Time
// Attributes holds the initial labels set on the run.
Attributes map[string]string
// Unique is an optional deduplication key held until the run ends.
Unique string
// Purge deletes payload data when the run finishes.
Purge bool
// Tokens are the tokens the run owns from its start, set with
// [ClaimToken],
// so the values resumed before the run waits for them are kept for it.
Tokens []string
}
NewRun holds the initial fields of a workflow run passed to Store.Create.
type Options ¶
type Options struct {
// Queue names the default queue for the workflow's advance jobs unless
// overridden by [OnQueue]. An empty string uses the connection's default
// queue.
Queue string
}
Options configures a workflow's default behavior. Implement a WorkflowOptions() workflow.Options method on a workflow struct to set them:
func (Checkout) WorkflowOptions() workflow.Options {
return workflow.Options{Queue: "workflows"}
}
type Outcome ¶
type Outcome struct {
// Status is [Waiting] when suspended, [Completed] when Handle returned
// nil, or [Failed] when the run failed permanently.
Status Status
// WakeAt is the next scheduled wake-up time for a [Waiting] run, or the
// zero time when waiting only on a resume.
WakeAt time.Time
// Output holds the JSON-encoded return value of a [Completed] workflow.
Output string
// Error holds the error message of a [Failed] workflow.
Error string
}
Outcome describes how a single advance ended, passed to Store.Release.
type PendingStart ¶
type PendingStart struct {
// contains filtered or unexported fields
}
PendingStart configures queue placement, initial delay, attributes, claimed tokens, and purge behavior before starting a workflow run with PendingStart.Start or PendingStart.StartOnce. Each builder method returns a modified copy so a PendingStart can be shared safely:
id, err := workflow.OnConnection("redis").OnQueue("workflows").Delay(time.Hour).Start(ctx, workflows.OnboardUser{UserID: user.ID})
The chosen connection and queue apply to every advance of the run.
func Attribute ¶
func Attribute(name, value string) *PendingStart
Attribute returns a PendingStart with the given initial label, as PendingStart.Attribute does.
func ClaimToken ¶
func ClaimToken[S ~string](token S) *PendingStart
ClaimToken returns a PendingStart whose run owns token from its start, as PendingStart.ClaimToken does.
func Delay ¶
func Delay(d time.Duration) *PendingStart
Delay returns a PendingStart that delays the run's first advance by d.
func DelayUntil ¶
func DelayUntil(t time.Time) *PendingStart
DelayUntil returns a PendingStart that schedules the run's first advance at time t.
func OnConnection ¶
func OnConnection(name string) *PendingStart
OnConnection returns a PendingStart whose advance jobs use the queue connection named name instead of the default connection.
func OnQueue ¶
func OnQueue(name string) *PendingStart
OnQueue returns a PendingStart whose advance jobs use the queue named name.
func PurgeWhenFinished ¶
func PurgeWhenFinished() *PendingStart
PurgeWhenFinished returns a PendingStart that deletes the run's payload data upon completion, as PendingStart.PurgeWhenFinished does.
func (*PendingStart) Attribute ¶
func (p *PendingStart) Attribute(name, value string) *PendingStart
Attribute returns a copy of p with the label name set to value so workflow:list --attribute can find the run. Workflows can update labels later with Run.SetAttribute. Keep attribute values short and free of secrets because they persist for the lifetime of the run.
func (*PendingStart) ClaimToken ¶
func (p *PendingStart) ClaimToken[S ~string](token S) *PendingStart
ClaimToken returns a copy of p whose run owns token from its start, so the values that Resume gives the token before the run reaches its wait are kept for the run. For example, a step might ask a payment gateway to charge a card, and the gateway's webhook might arrive before the step returns. Without the claim, no run owns the token until the run reaches Run.WaitFor, so the webhook's resume finds no run:
id, err := workflow.ClaimToken(workflows.Charged(order.ID)).Start(r, workflows.ChargeOrder{OrderID: order.ID})
Starting fails with a wrapped *TokenOwnedError if an unfinished run already owns the token. Call ClaimToken once for each token.
func (*PendingStart) Delay ¶
func (p *PendingStart) Delay(d time.Duration) *PendingStart
Delay returns a copy of p that delays the run's first advance by d.
func (*PendingStart) DelayUntil ¶
func (p *PendingStart) DelayUntil(t time.Time) *PendingStart
DelayUntil returns a copy of p that schedules the run's first advance at t.
func (*PendingStart) OnConnection ¶
func (p *PendingStart) OnConnection(name string) *PendingStart
OnConnection returns a copy of p whose advance jobs use the queue connection named name instead of the default connection.
func (*PendingStart) OnQueue ¶
func (p *PendingStart) OnQueue(name string) *PendingStart
OnQueue returns a copy of p whose advance jobs use the queue named name instead of the workflow's or connection's default queue.
func (*PendingStart) PurgeWhenFinished ¶
func (p *PendingStart) PurgeWhenFinished() *PendingStart
PurgeWhenFinished returns a copy of p that deletes the run's input, context, output, and step outputs and errors once the run completes, fails, or is cancelled. The run keeps its ID, status, attributes, and step names and timestamps for auditing, but a purged failed run cannot be retried. Use it for workflows handling sensitive data that must not remain in storage.
func (*PendingStart) Start ¶
Start saves a new run of workflow, enqueues its first advance, and returns its RunID, as Start does. It panics if ctx does not carry an application scope.
type Recorded ¶
type Recorded struct {
// Workflow is the workflow struct value passed to [Start] or [StartOnce].
Workflow any
// Name is the workflow's registered name.
Name string
// Connection is the queue connection chosen for the run.
Connection string
// Queue is the queue name chosen for the run.
Queue string
// Attributes holds the initial labels set on the run.
Attributes map[string]string
// Unique is the [StartOnce] deduplication key, or empty for [Start].
Unique string
// WakeAt is the scheduled time of the run's first advance.
WakeAt time.Time
}
Recorded holds the metadata of a workflow start captured by a Recorder.
type Recorder ¶
type Recorder interface {
// Records reports whether this recorder should intercept starts of
// workflow.
Records(workflow any) bool
// Record stores a captured start.
Record(start Recorded)
}
Recorder captures workflow starts in tests instead of persisting and executing them, such as workflowtest.Fake.
type Resumed ¶
type Resumed string
Resumed reports the outcome of a Resume call. Its string values serialize directly to logs and JSON.
const ( // ResumeDelivered indicates that the run owning the token keeps the // value, and its next advance was enqueued if it was waiting for it. ResumeDelivered Resumed = "delivered" // ResumeNotFound indicates that no unfinished run owns the token, so the // value went nowhere. ResumeNotFound Resumed = "not_found" // ResumeOnCommit indicates that delivery waits for the active database // transaction on ctx to commit. ResumeOnCommit Resumed = "on_commit" )
func Resume ¶
Resume gives value to the run that owns token and enqueues its next advance if it waits for the value:
resumed, err := workflow.Resume(r, workflows.Decision(expenseID), workflows.Approved)
A run owns a token from when it first waits for the token with Run.WaitFor, Run.WaitWithin, or Run.Inbox, or from its start when the start claims the token with PendingStart.ClaimToken, until it completes, fails, or is cancelled. The run keeps the values it's given in the order they arrived: a wait takes the first, and an inbox reads them all. When no unfinished run owns the token, such as after the run moved on and finished, Resume keeps nothing and returns ResumeNotFound, so a value never reaches a run it wasn't sent to. Inside a database transaction, Resume defers delivery until commit and returns ResumeOnCommit.
A token is an identifier, not a secret. Authorize the caller or use a signed URL before calling Resume. Resume panics if ctx does not carry an application scope.
type Run ¶
Run represents a single advance of a workflow run passed to the workflow's Handle method. Perform all durable operations through its methods: Run.Step, Run.Do, Run.Go, Run.Sleep, Run.SleepUntil, Run.WaitFor, Run.WaitWithin, and Run.Inbox.
Each advance calls Handle from the top. Operations already recorded in the run's journal return their saved results immediately without re-executing, while the first unrecorded operation performs its work. When an operation must wait for a sleep, a token, or a retry backoff, it suspends the run without returning, runs deferred functions, and ends the advance so a later worker job resumes from that point.
Run embeds context.Context with the application scope and context values captured when the run started, so Handle can pass run to helpers such as services.From(run). Perform I/O inside step functions using the context passed to each step.
func (*Run) Attributes ¶
Attributes returns a copy of the run's labels from start and Run.SetAttribute.
func (*Run) Do ¶
Do runs work once like Run.Step for a step that returns only an error:
if err := run.Do("send welcome email", o.sendWelcomeEmail); err != nil {
return err
}
func (*Run) Go ¶
func (r *Run) Go[T any](name string, work func(ctx context.Context) (T, error), options ...StepOption) *Task[T]
Go starts a durable step in its own goroutine so multiple steps can execute concurrently. Call Task.Wait to collect each result:
projects := run.Go("count projects", o.countProjects)
teammates := run.Go("count teammates", o.countTeammates)
p, err := projects.Wait()
if err != nil {
return err
}
t, err := teammates.Wait()
If one concurrent step suspends for a retry, sibling tasks finish their current attempts first and keep their recorded results for the next advance. Wait for all tasks before calling an unnamed Run.Sleep or Run.NewToken, because doing so while a task is outstanding fails the run.
func (*Run) ID ¶
ID returns the run's stable RunID, which stays the same across every advance and can be combined with a step name as an idempotency key.
func (*Run) Inbox ¶
Inbox opens a multi-value Inbox for token to receive repeated signals such as votes, replies, or webhook events sent via Resume:
votes := run.Inbox(Votes(o.ExpenseID))
for {
vote, ok, err := votes.NextWithin(5 * 24 * time.Hour)
if err != nil || !ok {
return Expired, err
}
// ...
}
The first read claims the token for the run, as Run.WaitFor does, and the inbox then returns every value sent to the token in order, including values that arrive while the run is busy with a step. To keep values sent before the first read, claim the token at the start with PendingStart.ClaimToken. A run may read an inbox at most 1,000 times.
func (*Run) NewToken ¶
NewToken generates a deterministic Token scoped to run r, useful when only ResumeURL or WebhookURL needs the token:
decision := run.NewToken[Decision]()
Generated tokens combine the run ID with a sequence number, so every replay produces the same tokens in the same order. Inserting a new wait ahead of an existing one shifts later numbers and invalidates URLs already sent out; use an explicit domain token when workflow code may change mid-flight. Calling NewToken while a Run.Go task is outstanding fails the run.
func (*Run) SetAttribute ¶
SetAttribute sets a label on the run, such as its current phase, for filtering with workflow:list --attribute and viewing in workflow:show. Setting the same name again replaces the previous value:
run.SetAttribute("phase", "shipping")
Changed attributes are persisted when the advance ends (whether it suspends, completes, or fails). Replaying the same assignments produces no extra write.
func (*Run) Sleep ¶
func (r *Run) Sleep(d time.Duration, options ...SleepOption) error
Sleep suspends the run for duration d without holding a worker. Unnamed sleeps are numbered in the order reached; pass Named to assign a stable name.
func (*Run) SleepUntil ¶
func (r *Run) SleepUntil(t time.Time, options ...SleepOption) error
SleepUntil suspends the run until time t without holding a worker.
func (*Run) StartedAt ¶
StartedAt returns the timestamp when the run started, which stays the same across every advance.
func (*Run) Step ¶
func (r *Run) Step[T any](name string, work func(ctx context.Context) (T, error), options ...StepOption) (T, error)
Step executes work once and records its return value under name, which must be unique within the run. On subsequent advances, Step returns the recorded value without running work again:
receipt, err := run.Step("charge card", o.chargeCard, workflow.Tries(5), workflow.Timeout(30*time.Second))
Values round-trip through JSON on every advance, including the first, so T must encode and decode cleanly with encoding/json/v2.
Failed attempts retry up to three times by default (10 seconds, then 1 minute apart, unless overridden by RetryAfter, RetryAt, Tries, or Backoff). The run suspends between retries without holding a worker. A panic in work counts as a failed attempt. Returning a Fatal error or exhausting tries records a *StepFailedError that is replayed on later advances so error-handling branches stay deterministic.
func (*Run) WaitFor ¶
WaitFor suspends the run until Resume delivers a value for token, then returns that value:
decision, err := run.WaitFor(Decision(o.ExpenseID))
Each run can wait on a given token once. Reaching the wait claims the token, so the run owns it until it completes, fails, or is cancelled, and Resume gives its values only to this run. If another unfinished run owns the token, the run fails with an error naming the owner. To keep the values resumed before the run reaches the wait, claim the token at the start with PendingStart.ClaimToken.
func (*Run) WaitWithin ¶
WaitWithin waits for token like Run.WaitFor, timing out after timeout and returning false if no resume arrives in time:
decision, decided, err := run.WaitWithin(Decision(o.ExpenseID), 3*24*time.Hour)
type RunCancelled ¶
type RunCancelled struct {
// RunID is the ID of the cancelled run.
RunID RunID
// Workflow is the workflow's registered name.
Workflow string
// Reason is the optional explanation passed to [Cancel].
Reason string
}
RunCancelled is dispatched when Cancel or workflow:cancel stops a run.
type RunCompleted ¶
type RunCompleted struct {
// RunID is the ID of the completed run.
RunID RunID
// Workflow is the workflow's registered name.
Workflow string
}
RunCompleted is dispatched when a workflow's Handle method returns nil. Event listeners receive the context values captured when the run started.
type RunFailed ¶
type RunFailed struct {
// RunID is the ID of the failed run.
RunID RunID
// Workflow is the workflow's registered name.
Workflow string
// Err is the error that ended the run.
Err error
}
RunFailed is dispatched after a run fails permanently and any Failed hook on the workflow has run. Laravel also reports the error through the application's error reporter.
type RunID ¶
type RunID string
RunID uniquely identifies a workflow run as a UUIDv7 string, so IDs sort in creation order and can be stored in UUID or text database columns.
func Start ¶
Start saves a new run of workflow, enqueues its first advance job, and returns its RunID:
id, err := workflow.Start(r, workflows.OnboardUser{UserID: user.ID})
The run captures context values from ctx (such as the active tenant) and restores them on every advance. Inside a database transaction, the run starts after the transaction commits and is discarded if it rolls back. Start panics if ctx does not carry an application scope.
type RunInfo ¶
type RunInfo struct {
// ID is the run's unique identifier.
ID RunID `json:"id"`
// Workflow is the workflow's registered name.
Workflow string `json:"workflow"`
// Status is the run's current lifecycle [Status].
Status Status `json:"status"`
// Output holds the workflow's JSON-encoded return value, or nil if the run
// has not completed or its data was purged.
Output jsontext.Value `json:"output"`
// Error holds the failure message for a [Failed] run or the cancellation
// reason for a [Cancelled] run.
Error string `json:"error,omitempty"`
// WakeAt is the next scheduled wake-up time, or the zero time if the run
// has ended or is waiting only for a resume.
WakeAt time.Time `json:"wake_at,omitzero"`
// CreatedAt is when the run started.
CreatedAt time.Time `json:"created_at"`
// FinishedAt is when the run completed, failed, or was cancelled, or the
// zero time if it is still active.
FinishedAt time.Time `json:"finished_at,omitzero"`
// Attributes holds the labels set at start or via [Run.SetAttribute].
Attributes map[string]string `json:"attributes"`
// Purged reports whether the run's payload data was deleted on completion
// because it started with [PendingStart.PurgeWhenFinished].
Purged bool `json:"purged"`
// Steps lists the run's steps, sleeps, waits, and inbox reads in the order
// the run first reached them.
Steps []StepInfo `json:"steps"`
}
RunInfo summarizes a workflow run's status, steps, attributes, and output or error as returned by Find and WaitingFor. It encodes directly to JSON so HTTP handlers can return it for status or progress views.
func Find ¶
Find loads the RunInfo for run id along with its recorded steps, returning false if no run matches id. RunInfo encodes directly to JSON for progress endpoints:
run, found, err := workflow.Find(r, id)
if err != nil {
return web.Fail(err)
}
if !found {
return web.Abort(http.StatusNotFound)
}
return web.JSON(run)
Find panics if ctx does not carry an application scope.
func NewRunInfo ¶
NewRunInfo builds a RunInfo snapshot from a stored RunRecord and its journal entries.
func WaitingFor ¶
WaitingFor returns the run that's waiting for a value of token now via a wait or inbox, and false when none is. A run that owns the token but hasn't reached its wait yet isn't returned. A route may check the run before it resumes the token, such as to confirm that the signed-in user may decide on the expense the run is for:
run, found, err := workflow.WaitingFor(r, workflows.Decision(expenseID))
if err != nil {
return web.Fail(err)
}
if !found {
return web.Abort(http.StatusNotFound)
}
WaitingFor panics if ctx does not carry an application scope.
func (RunInfo) Step ¶
Step looks up a recorded step, sleep, wait, or inbox read by kind and name, returning false if the run has not reached it.
func (RunInfo) WaitingFor ¶
WaitingFor returns the token names that the run is currently waiting on via Run.WaitFor, Run.WaitWithin, or an Inbox.
type RunRecord ¶
type RunRecord struct {
// ID is the run's unique identifier.
ID RunID
// Workflow is the workflow's registered name.
Workflow string
// Input holds the JSON-encoded workflow struct, or [PurgedInput] once
// purged.
Input string
// Context holds the JSON-encoded context values restored on each advance.
Context string
// Connection is the queue connection for the run's advance jobs.
Connection string
// Queue is the queue name for the run's advance jobs.
Queue string
// Status is the run's current [Status].
Status Status
// Output holds the workflow's JSON-encoded return value once [Completed],
// or empty.
Output string
// Error holds the failure message once [Failed] or the cancellation reason
// once [Cancelled], or empty.
Error string
// WakeAt is the next scheduled wake-up time, or the zero time if the run
// waits only for a resume or has ended.
WakeAt time.Time
// CreatedAt is when the run started.
CreatedAt time.Time
// FinishedAt is when the run reached a terminal status, or the zero time.
FinishedAt time.Time
// Attributes holds the run's labels.
Attributes map[string]string
// Purge deletes the run's input, context, output, error, and entry
// payloads once the run finishes.
Purge bool
}
RunRecord holds a persisted workflow run without its journal entries.
func NewRecord ¶
NewRecord initializes a Pending RunRecord from run for Store.Create.
func (*RunRecord) Cancel ¶
Cancel marks r as Cancelled at time now with reason for Store.Cancel. If r.Purge is true, Cancel clears payload data while keeping reason in Error.
type SleepOption ¶
type SleepOption func(name *string)
SleepOption configures Run.Sleep and Run.SleepUntil.
func Named ¶
func Named(name string) SleepOption
Named assigns a custom journal name to a sleep so workflow:show displays that name instead of an automatic number such as "sleep 2":
err := run.Sleep(time.Hour, workflow.Named("trial grace period"))
type StartOutcome ¶
type StartOutcome string
StartOutcome describes what StartOnce did with a start request. Its string values serialize directly to logs and JSON.
const ( // StartedNew indicates that a new run was saved and its first advance was // enqueued. StartedNew StartOutcome = "new" // StartedExisting indicates that an unfinished run already held the unique // key, so no new run was created. StartedExisting StartOutcome = "existing" // StartedOnCommit indicates that creation waits for the active database // transaction on ctx to commit. StartedOnCommit StartOutcome = "on_commit" )
type Started ¶
type Started struct {
// ID is the new run's ID, the existing run's ID holding the key, or the
// pending run's ID when deferred until transaction commit.
ID RunID `json:"id"`
// Outcome indicates whether the run was created, deduplicated, or deferred.
Outcome StartOutcome `json:"outcome"`
}
Started reports the RunID and StartOutcome of a StartOnce call.
func StartOnce ¶
StartOnce starts a run of workflow unless an unfinished run already holds key, preventing duplicate runs from double submissions. A run holds key until it completes, fails, or is cancelled:
started, err := workflow.StartOnce(r, fmt.Sprintf("expenses.%d", id), workflows.ApproveExpense{ExpenseID: id})
if started.Outcome == workflow.StartedExisting {
// The expense is already waiting for approval...
}
Inside a database transaction, StartOnce defers creation until commit and returns StartedOnCommit. StartOnce panics if ctx does not carry an application scope.
type Status ¶
type Status string
Status represents the lifecycle state of a workflow run or a journal entry.
const ( // Pending indicates a run waiting for its first advance or a journal entry // that has not finished yet. Pending Status = "pending" // Running indicates a run currently held and advanced by a worker. Running Status = "running" // Waiting indicates a run suspended on a sleep, a token wait, or a step // retry backoff. Waiting Status = "waiting" // Completed indicates a run whose Handle returned nil or an entry that // finished. Completed Status = "completed" // Failed indicates a run that returned an error or violated a replay rule, // or a step that exhausted its tries. Failed Status = "failed" // Cancelled indicates a run stopped by [Cancel] or workflow:cancel. Cancelled Status = "cancelled" )
func ParseStatus ¶
ParseStatus parses a status name such as "pending" or "failed" into a Status. It returns an error if name is not a recognized status.
type StepFailedError ¶
type StepFailedError struct {
// Step is the name of the failed step.
Step string
// Err is the error message from the step's final attempt.
Err string
}
StepFailedError reports that a step failed permanently after exhausting its Tries or returning a Fatal error. The step returns the same error on subsequent replays so compensation logic runs deterministically:
flight, err := run.Step("book flight", o.bookFlight)
if err != nil {
return err
}
if err := run.Do("book hotel", o.bookHotel); err != nil {
if err := run.Do("cancel flight", o.cancelFlight(flight)); err != nil {
return err
}
return err
}
func (*StepFailedError) Error ¶
func (e *StepFailedError) Error() string
Error returns a formatted message naming the failed step and its error.
type StepInfo ¶
type StepInfo struct {
// Kind identifies whether this entry is a step, sleep, wait, or inbox read.
Kind Kind `json:"kind"`
// Name is the step or sleep name, the wait token, or the inbox token and
// read number (such as "expenses.7.votes #2").
Name string `json:"name"`
// Status is the entry's current [Status].
Status Status `json:"status"`
// Tries is how many attempts the step has made. Replaced steps in tests
// report 0.
Tries int `json:"tries"`
// Error holds the error message from the step's most recent failed try.
Error string `json:"error,omitempty"`
// WakeAt is when the sleep ends, the wait times out, or the next retry is
// scheduled, or the zero time.
WakeAt time.Time `json:"wake_at,omitzero"`
// StartedAt is when the run first reached this entry.
StartedAt time.Time `json:"started_at"`
// FinishedAt is when the entry completed or failed, or the zero time.
FinishedAt time.Time `json:"finished_at,omitzero"`
// TimedOut reports whether a wait or inbox read timed out without
// receiving a value.
TimedOut bool `json:"timed_out"`
}
StepInfo describes a single step, sleep, wait, or inbox read recorded in a RunInfo.
type StepOption ¶
type StepOption func(o *stepOptions)
StepOption configures retry and timeout behavior for Run.Step, Run.Do, and Run.Go.
func Backoff ¶
func Backoff(waits ...time.Duration) StepOption
Backoff sets the delay before each retry attempt in order, repeating the final duration once the slice is exhausted. The default is 10 seconds, then 1 minute.
func Timeout ¶
func Timeout(timeout time.Duration) StepOption
Timeout caps how long a single attempt of a step may run before its context is canceled and the attempt fails.
func Tries ¶
func Tries(tries int) StepOption
Tries sets the maximum number of attempts for a step (at least 1, defaulting to 3).
type Store ¶
type Store interface {
// Create saves a new run as [Pending], as [NewRecord] builds it, owning
// run.Tokens. When run.Unique is set and an unfinished run already holds
// that key, it saves nothing and returns that run's ID. Of two calls with
// one key, only one may save its run. A run holds its key until it
// completes, fails, or is cancelled. When an unfinished run owns one of
// run.Tokens, Create saves nothing and returns a [*TokenOwnedError].
Create(ctx context.Context, run NewRun) (existing RunID, err error)
// Claim takes the run's lease for lease, marks the run [Running], mints a
// distinct [Lease] fencing token, and returns it with the run and its
// entries. A lease that has run out counts as given up. Of two calls for
// one run, only one may claim it.
Claim(ctx context.Context, id RunID, lease time.Duration) (Claim, error)
// Record saves an entry, in place of the run's entry of the same kind
// and name. It returns [ErrLeaseLost], and saves nothing, when the run
// isn't [Running] or lease is no longer the run's active lease, such as
// after a cancel or another worker claiming an expired lease.
Record(ctx context.Context, id RunID, lease Lease, entry Entry) error
// Wait claims the token for the run, notes that the run waits for the
// value numbered number that it keeps for the token, and returns that
// value when it has arrived. It returns [ErrLeaseLost], and changes
// nothing, when the run isn't [Running] or lease is no longer active. When
// another unfinished run owns the token, Wait changes nothing and returns
// a [*TokenOwnedError]. A run that gets its value no longer waits for the
// token, but still owns it. A run waits for one value of a token at a
// time, so a later Wait for the same token replaces the number it waits
// for.
Wait(ctx context.Context, id RunID, lease Lease, token string, number int) (value string, ok bool, err error)
// StopWaiting notes that the run no longer waits for token, because its
// wait timed out. The run still owns the token. It returns [ErrLeaseLost],
// and changes nothing, when the run isn't [Running] or lease is no longer
// active.
StopWaiting(ctx context.Context, id RunID, lease Lease, token string) error
// Resume adds value to the end of the list that the token's owner keeps
// for the token, numbered one past the last, and returns the owner. It
// reports due when the owner waits for a number up to the value's, so
// the owner should advance. When no unfinished run owns the token,
// Resume keeps nothing and returns an empty owner.
Resume(ctx context.Context, token, value string) (owner RunID, due bool, err error)
// Waiting returns the run that owns token and waits for a value of it
// now, and false when no run does.
Waiting(ctx context.Context, token string) (RunID, bool, error)
// SetAttributes replaces the run's attributes. It returns [ErrLeaseLost],
// and saves nothing, when the run isn't [Running] or lease is no longer
// active.
SetAttributes(ctx context.Context, id RunID, lease Lease, attributes map[string]string) error
// Renew extends the run's lease to duration from now, while an advance is
// still running. It returns [ErrLeaseLost], and changes nothing, when the
// run isn't [Running] or lease is no longer active.
Renew(ctx context.Context, id RunID, lease Lease, duration time.Duration) error
// Release saves how an advance ended at now, as [RunRecord.End] applies
// it, and gives up the lease. A run that ends no longer waits, and gives
// up its unique key and its tokens. A completed run loses its values. A
// failed run keeps them, so a retry continues reading where it stopped
// once it claims each token again. A run with Purge set loses its data
// when it completes or fails, its entries lose their outputs and errors,
// and it loses its values even when it failed, since it can't be
// retried.
// Release returns [ErrLeaseLost], and saves nothing, when the run isn't
// [Running] or lease is no longer active.
Release(ctx context.Context, id RunID, lease Lease, outcome Outcome, now time.Time) error
// Find returns the run with the ID, and false when no run has it.
Find(ctx context.Context, id RunID) (RunRecord, bool, error)
// Entries returns the run's entries, in the order the run first reached
// them.
Entries(ctx context.Context, id RunID) ([]Entry, error)
// List returns the runs that filter selects, newest first.
List(ctx context.Context, filter Filter) ([]RunRecord, error)
// Cancel marks an unfinished run [Cancelled] with the reason, finished
// at now, as [RunRecord.Cancel] applies it, and gives up its unique key.
// The run gives up its tokens and loses its values, and loses its data
// when Purge is set. It
// reports false when the run doesn't exist or has ended.
Cancel(ctx context.Context, id RunID, reason string, now time.Time) (bool, error)
// Retry marks a failed run [Pending] again, due at now, without its
// error and without its failed entries. It reports false when the run
// hasn't failed or has lost its data.
Retry(ctx context.Context, id RunID, now time.Time) (bool, error)
// Overdue returns the runs that should have advanced by now and
// haven't: pending and waiting runs whose WakeAt has passed, waiting
// runs whose wait a resume has answered, and running runs whose lease
// has run out.
Overdue(ctx context.Context, now time.Time) ([]RunRecord, error)
// Prune deletes the runs that finished before before, with their
// entries and values, and returns how many runs it deleted.
Prune(ctx context.Context, before time.Time) (int64, error)
}
Store persists workflow runs, their journal entries, and the resume values they wait on. Laravel handles replay, retries, JSON encoding, and job scheduling, so a Store only stores opaque JSON strings and enforces lease, token, and resume atomicity.
A token belongs to one unfinished run at a time. A run claims a token when it starts with the token in NewRun.Tokens, or when it first waits for the token with Store.Wait, and gives up its tokens when it completes, fails, or is cancelled. Store.Resume adds its value to the list the token's owner keeps for that token, numbered from 1 in the order the values arrived. When no unfinished run owns the token, the store keeps nothing. A single wait reads value 1, while an inbox reads values 1, 2, 3, and so on. Reading does not remove values, so crashed advances can replay safely.
Implementations must guarantee four atomic invariants, and fence every in-advance write with the Lease returned by Store.Claim:
- Of two concurrent Store.Claim calls for one run, only one obtains the lease, with a distinct Lease token.
- Of two unfinished runs that claim one token, with Store.Create or Store.Wait, only one owns it. The other gets a *TokenOwnedError naming the owner.
- Concurrent Store.Resume calls for one token assign distinct sequence numbers to their values.
- A concurrent Store.Wait and Store.Resume for one token cannot miss each other: either Resume reports the owner due or Wait returns the value.
Leases use the system clock rather than the application's testable clock so time travel in tests does not prematurely expire an active lease. Verify custom implementations with workflowtest.StoreContract.
type Task ¶
type Task[T any] struct { // contains filtered or unexported fields }
Task represents a concurrent step started with Run.Go. Call Task.Wait to retrieve its result.
type Token ¶
Token identifies an external signal that a run waits for and specifies the Go type T of the value delivered by Resume. Define a helper function so the workflow and the resuming caller share the same token format and type:
func Decision(expenseID int64) workflow.Token[Decision] {
return workflow.Token[Decision](fmt.Sprintf("expenses.%d.decision", expenseID))
}
A token is an identifier, not a secret. Because its underlying type is string, models and workflow structs can store it directly.
type TokenOwnedError ¶
type TokenOwnedError struct {
// Token is the token the run tried to claim.
Token string
// Owner is the unfinished run that owns the token.
Owner RunID
}
TokenOwnedError reports that a run can't claim a token, because another unfinished run owns it. Store.Create and Store.Wait return it, and Start returns it wrapped when a token passed to ClaimToken is taken.
func (*TokenOwnedError) Error ¶
func (e *TokenOwnedError) Error() string
type URLOption ¶
type URLOption func(o *urlOptions)
URLOption configures a signed URL created by ResumeURL or WebhookURL.
func Through ¶
Through targets a named application route instead of the default /_workflow/resume endpoint, passing any route parameters in the same format as urls.Route. The target handler calls Accept to verify the signature and resume the run after the route's middleware (such as authentication) runs.
type Workflows ¶
type Workflows struct {
// contains filtered or unexported fields
}
Workflows holds an application's registered workflow definitions and their backing Store. Retrieve the application's instance with From.
func From ¶
From returns the Workflows registry from the application scope in ctx. Use it for operations not covered by package-level helpers, such as querying the backing Store directly:
runs, err := workflow.From(ctx).Store().List(ctx, workflow.Filter{Status: workflow.Failed})
From panics if ctx does not carry an application scope or if the application has no workflows service registered.
func New ¶
New constructs a Workflows registry from cfg. It returns an error if any workflow value is nil, lacks a valid Handle or Failed signature, has an empty name, or collides with another workflow's name.
func (*Workflows) Advance ¶
Advance executes a single advance of run id in the current process without enqueueing its next wake-up. Any step name present in replacements records the given JSON string directly instead of calling the step function.
Advance is used by workflowtest to drive runs synchronously in tests. It returns an error only if the backing Store fails.
func (*Workflows) Fake ¶
Fake installs r to capture workflow starts instead of persisting and running them. It returns false without making changes if a fake is already installed.
func (*Workflows) Recover ¶
Recover enqueues an advance job for every overdue run whose sleep, timeout, retry, resume, or expired lease was missed, such as after a worker crash or cleared queue. It returns the number of runs scheduled.
func (*Workflows) Retry ¶
Retry resets a failed run to Pending so it resumes from the failed step while keeping all previously completed steps, then enqueues its next advance. Retry returns false if the run does not exist, is not in Failed status, or had its data purged.
func (*Workflows) Save ¶
Save stores a new run of workflow without enqueueing its first advance and returns its RunID. The run owns tokens from its start, as PendingStart.ClaimToken makes it. Tests such as workflowtest use Save together with Workflows.Advance to step through a run manually.