memory

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package memory is the in-process driver of workflow.Client: runs, waits, sleeps, schedules and queues live in maps and goroutines inside the client value, with no database and no server.

It is for tests, local runs and apps that can afford to lose queued work. Everything is lost when the process exits, so it declares every capability except workflow.CapDurable (including the retry jitter and delay, misfire and cron-zone capabilities), and Start refuses nothing on that ground: durability is never inferred from a workflow (see workflow.Requires), the app picks a durable driver when it needs one.

Time

Every timer (delayed starts, sleep steps, wait deadlines, retry backoff, step timeouts, rate-limit windows, cron fires) comes from the injected clock.Clock, so a test that passes clock.NewFake makes "sleep three days" run in microseconds. Handlers still run on real goroutines.

Execution model

  • A run is admitted when its concurrency bucket has room and its rate limits allow a start; until then it is StatusQueued.
  • An admitted run drives its steps as a DAG: a step starts once every After parent has succeeded, with its input built by workflow.StepInput. A wait step outputs the signal's payload; a sleep step passes its input through.
  • Run steps execute on a fixed pool of workers (WithWorkers). Waits and sleeps do not hold a worker. Among step attempts waiting for a worker, the higher QueueConfig.Priority of their queue goes first, then the higher Job.Priority, then first come first served. An attempt held by a pause (Pause) or by its queue's Workers cap waits without blocking the others.
  • A failed attempt is retried per workflow.EffectiveRetriesFor (Job.Retry, else the step's, else the workflow's) as decided by RetryPolicy.Next on the injected clock: Max, MaxErrors (releases marked by RetryAfter do not count), the delay (DelayFor, else the backoff with its Jitter drawn from WithJitterSource) and Until from the step's first attempt. Permanent errors, NoRetryOn and cancellation are never retried. When a step fails for good the run's other steps are cancelled, OnFailure runs once with the failing step's input, and the run becomes StatusFailed (also when MaxErrors or Until stops it) unless the policy sets RetryPolicy.DiscardOnExhaust, which ends it StatusDiscarded with no OnFailure (CapDiscardExhausted, CapRunStates). While a step waits on its retry backoff and no attempt executes, the run reads StatusRetrying and RunInfo carries NextAttempt and NextAttemptAt. A step returning workflow.Discard ends the run StatusDiscarded at once, with no retry and no OnFailure (workflow.EndStatus; CapRunStates).
  • A wait that reaches its Deadline or Timeout fails the run (waits are not retried). A Signal is kept: a run that reaches a matching wait step after the Signal takes the first one sent after the run was enqueued, and never takes the same signal twice. Signals older than the oldest unfinished run are dropped.

Policies

  • Idempotency: a key is held from Enqueue until the run is terminal; a colliding Enqueue starts nothing and returns the holder's RunRef with a nil error, as workflow.Client documents.
  • Concurrency: only Go-function keys (workflow.KeyFunc); an expression key (concurrency, rate limit or WaitSpec.KeyFrom) is refused at Start with an UnsupportedError. QueueNewest and RoundRobin hold the new run until its bucket has room (each bucket is capped at MaxRuns, so no key can starve another); DropNewest and CancelNewest record the new run as StatusCancelled; CancelInProgress cancels the bucket's oldest running run to make room. A cancelled run releases its slot at once, even if a handler that ignores its context is still returning.
  • Rate limits: a sliding window of start times per key on the injected clock; a limited run waits queued until the window frees.
  • Cron: Workflow.Cron fires in its CronLocation (UTC when nil) and Client.Schedule in its Location, both from Start (or the Schedule call) onwards. Expressions are parsed by cron.Parse unless WithCronParser supplies another dialect, which gives up "the same spec on every driver" for what only that parser understands; a parser that returns neither a schedule nor an error is refused.
  • Misfires: the default is fire-once with no age limit: after a long pause (a fake clock jumping several ticks) the newest tick fires once and the older ones are reported as one TickMisfired. Every explicit workflow.Misfire policy is honoured (CapMisfireSkip, CapMisfireFireOnce, CapMisfireFireAll) through workflow.Misfire.Plan over the ticks since the last catch-up.

Queues

Without WithQueues the workers serve every queue. With it they serve only the listed queues, each with its own Workers cap and Priority; a workflow or a Job.Queue on a queue not listed is refused (ErrInvalid), since nothing in this process would ever run it. QueueConfig.Limit caps the step attempts of a queue running at once; this driver is one process, so the process is the whole cluster and the cap holds across it (CapQueueLimitGlobal), where Workers is the same kind of per-client cap.

Operating on runs

The client keeps finished runs within RunRetention (by default a day and at most 10,000, DefaultRunRetention; WithRunRetention changes it) and unfinished runs always, so it implements the run query family: Runs (newest enqueue first, a position cursor), Retry (the failed run keeps its RunRef and resumes after the steps that succeeded; its concurrency and rate limits apply again), Delete and CancelAll. Pause and Resume hold runs by workflow, queue or all.

Schedules

Declared crons get the stable ID "cron:<workflow>:<index>", are listed by Schedules and can be paused but not unscheduled. A named Client.Schedule is upserted by (Workflow, Name). Each tick passes the misfire policy, then the schedule's Windows, then the workflow's ScheduleWhen; fired runs carry workflow.FiredLabels, and every outcome goes to OnTick observers on the notifier goroutine. A paused schedule reports its ticks as skipped and never fires them, not even on resume; it resumes at its next tick.

Chains, scaling and closures

Job.Chain is kept with the run: each step attempt gets a workflow.ChainEdits on its ctx, whose PrependToChain and AppendToChain edits apply only if the attempt succeeds, and once the run succeeds the next job (workflow.NextInChain) is enqueued under the same lock that recorded the success. A chained job that cannot be enqueued (its workflow not registered, the client stopping) ends the chain and is logged. A run that Retry re-opens keeps its edited chain. Like every run here, a chain lives only in this process.

The client implements workflow.WorkerScaler over the queues given to WithQueues: SetWorkers changes a queue's Workers cap while it runs and QueueLoads reports each queue's backlog, oldest wait, cap and running attempts. The caps share the WithWorkers pool, so give the pool at least a balancer's Total. Nothing balances unless the app runs a workflow.BalanceLoop.

EnqueueClosure (workflow.ClosureEnqueuer, CapClosure) runs a Go function as a run of workflow.ClosureWorkflow through the same queues, retries, middleware and observers as any run. It is lost with the process, as every run of this driver is; a durable driver refuses closures.

Run ends

The client implements workflow.RunNotifier and declares workflow.CapRunFinished: every run that reaches a terminal status is delivered once to each observer, including runs cancelled before they started (a cancelled RunAt run, whose Ref carries only the ScheduledID), DropNewest and CancelNewest runs, and runs cancelled by shutdown. A cancelled run's Err matches workflow.ErrCancelled; a failed run's Err wraps the step's original error. FinishedAt comes from the injected clock. Observers run on one notifier goroutine, in registration order and in the order runs ended, outside the client's lock, so they may call back into the client; a panicking observer is logged and skipped. An idempotency collision starts no run and produces no event.

Shutdown

Cancelling the context passed to Start, or calling Stop, shuts the client down: every unfinished run becomes StatusCancelled (and is delivered to run-finished observers, whose ctx is by then cancelled), every goroutine the client started exits, and later calls fail with ErrNotStarted. Stop also waits for that to finish, so prefer it in tests. Drain stops claiming attempts, waits for the running ones until its ctx ends, then stops the same way; WithStopWhenIdle drains by itself once the last unfinished run has ended and nothing new came for the grace; WithRecycle drains by itself once a workflow.Recycle limit (finished attempts, time since Start, memory) is reached, and StopCause then returns the *workflow.RecycleError, which workflow.Serve returns. Done closes once everything has stopped. Because a stop cancels every unfinished run, the client does not declare workflow.CapShutdownRequeue: there is no store for a stopped attempt to go back to. DrainWithReport (workflow.ReportingDrainer, CapDrainReport) is Drain that also returns a workflow.DrainReport: the steps and runs that finished during the drain and every attempt still running at the deadline, listed with the disposition DrainCancelled, because the run became StatusCancelled.

Operator calls and history

Schedules honour workflow.OverlapSkip (Schedule.Overlap, Workflow.CronOverlap) from the status of their last run, which the client keeps per schedule with its fire time (ScheduleInfo.Last, workflow.CapScheduleHistory; a named upsert keeps it). TriggerSchedule runs a schedule now (workflow.ScheduleTriggerer). ForceComplete and ForceFail end a run from outside (workflow.RunForcer). RunInfo.Errors keeps each run's failed attempts, the newest workflow.DefaultErrorHistory unless WithErrorHistory says otherwise; Retry keeps them.

The client has no enqueue-only mode (workflow.CapEnqueueOnly): its runs live in this process, so a client that never started would hold work nobody runs. Enqueue keeps needing Start. For the same reason it has no scheduler-only or worker-only mode (workflow.NodeScheduler, workflow.NodeWorker): nothing else would run what it fires. To fire crons here and run jobs on a durable driver, use package hybrid.

Run data, steps and nodes

A step may Snooze (put back without spending an attempt; the run reads StatusWaiting), Heartbeat (with Step.HeartbeatTimeout, an attempt that stops beating fails with workflow.ErrHeartbeatTimeout) and ReportProgress (kept as RunInfo.Progress). Workflow.RunTimeout ends a run that runs too long and Workflow.OnTimeout replaces OnFailure for any timeout. Job.Tenant is kept and filtered by RunQuery.Tenant. A succeeded run keeps its result (workflow.RunOutput; Result, RunInfo.Output). Reschedule moves a delayed run, CancelStep withdraws one running or parked step, OnLifecycle streams inserted, started, retrying, snoozed, progress and finished events. The failed run's error is a workflow.RunError. Concurrency.FIFO holds: queued runs of one key are admitted in enqueue order. QueueConfig.Weight shares workers between queues of equal priority by a weighted draw from the jitter source. Every attempt names this node (WithNodeID, else workflow.DefaultNodeID); Nodes lists the one node and Health reports it live until stopped and ready while started and not draining. WithPayloadLimit refuses oversized payloads at Enqueue. Schedules honour Seconds (cron.ParseSeconds), Active, KeepRuns and stamp workflow.LabelTickAt on every fired run.

RunAll, for tests, runs everything now: delayed starts, retry backoffs, snoozes and sleeps end at once, and it returns once no run can move (finished or waiting for an event), with a RunAllReport, or with ErrRunAllStalled when runs are left that only the clock, a resume or a free slot can move. Timeouts keep following the clock.

Index

Constants

This section is empty.

Variables

View Source
var DefaultRunRetention = RunRetention{MaxAge: 24 * time.Hour, MaxRuns: 10_000}

DefaultRunRetention is what a client keeps without WithRunRetention: finished runs for a day, at most 10,000 of them. A long-lived process on this driver would otherwise grow without bound, since Runs and Retry need finished runs kept; a day covers "the job failed overnight, retry it in the morning", and 10,000 bounds memory however busy the client.

View Source
var ErrRunAllStalled = errors.New("memory: RunAll stalled")

ErrRunAllStalled is returned by RunAll when runs are left that nothing it can hurry will move: a paused workflow or queue, a rate limit or timeout waiting on a fake clock, a concurrency slot held by a run that waits for an event.

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the in-memory workflow.Client. Build it with New. All state hangs off the value; two clients share nothing.

func New

func New(opts ...Option) *Client

New returns a client that has started nothing: no goroutine runs until Start.

func (*Client) Cancel

func (c *Client) Cancel(_ context.Context, ref workflow.RunRef) error

Cancel stops a run or a delayed start; finished runs are left alone.

func (*Client) CancelAll

func (c *Client) CancelAll(ctx context.Context, q workflow.RunQuery) (int, error)

CancelAll cancels every run matching q; see workflow.BulkCanceller.

func (*Client) CancelStep

func (c *Client) CancelStep(ctx context.Context, ref workflow.RunRef, step string) error

CancelStep withdraws one step of a run (see workflow.StepCanceller).

func (*Client) Capabilities

func (c *Client) Capabilities() workflow.Caps

Capabilities returns everything except CapDurable.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, ref workflow.RunRef) error

Delete forgets a terminal run; see workflow.RunDeleter.

func (*Client) Done

func (c *Client) Done() <-chan struct{}

Done is closed once the client has fully stopped: after Drain, after the Start ctx was cancelled, or after WithStopWhenIdle fired.

func (*Client) Drain

func (c *Client) Drain(ctx context.Context) error

Drain stops claiming step attempts, waits for the running ones until ctx ends, then shuts the client down; see workflow.Drainer. Unfinished runs become StatusCancelled, since nothing in memory outlives the client. It is DrainWithReport without the report.

func (*Client) DrainWithReport

func (c *Client) DrainWithReport(ctx context.Context) (workflow.DrainReport, error)

DrainWithReport is Drain that also returns what the drain finished and what it cut off (workflow.ReportingDrainer). Every cut-off attempt has the disposition DrainCancelled: nothing in memory outlives the client, so its run becomes StatusCancelled. The report is fixed when the deadline ends, before the client's context is cancelled, so attempts the shutdown itself interrupts are listed as cut and never as finished. A second call, or one after the client stopped, returns the first call's report.

func (*Client) Enqueue

func (c *Client) Enqueue(ctx context.Context, job workflow.Job) (workflow.RunRef, error)

Enqueue starts a run now, or at job.RunAt. See the package doc for how idempotency keys, concurrency and rate limits apply.

func (*Client) EnqueueClosure

func (c *Client) EnqueueClosure(ctx context.Context, cl workflow.ClosureJob) (workflow.RunRef, error)

EnqueueClosure runs c.Fn as a run of workflow.ClosureWorkflow in this process; see workflow.ClosureEnqueuer. The run goes through the same queues, priorities, pauses, retries, middleware and run-finished observers as any other, and Status, Cancel, Runs, Retry and Delete work on its RunRef. It lives only in this process's memory, like every run of this driver.

func (*Client) ForceComplete

func (c *Client) ForceComplete(ctx context.Context, ref workflow.RunRef) error

ForceComplete ends a run as succeeded without running its remaining steps; see workflow.RunForcer. Attempts in progress see their context cancelled with cause workflow.ErrForced and their results are dropped. A failed run is turned into a success: its run-finished event is delivered again and its chain continues.

func (*Client) ForceFail

func (c *Client) ForceFail(ctx context.Context, ref workflow.RunRef, reason string) error

ForceFail ends an unfinished run as failed with workflow.ForcedFailure(reason); see workflow.RunForcer. No retry is made and OnFailure does not run.

func (*Client) Health

Health reports the client live unless it was stopped, and ready while it is started and neither draining nor stopped (see workflow.HealthChecker). There is no backend to reach.

func (*Client) Nodes

func (c *Client) Nodes(ctx context.Context) ([]workflow.NodeInfo, error)

Nodes reports this client as the one node there is (see workflow.NodeLister).

func (*Client) OnLifecycle

func (c *Client) OnLifecycle(fn workflow.LifecycleFunc) error

OnLifecycle registers fn to observe every run's lifecycle (see workflow.LifecycleNotifier). Lifecycle observers share the run-finished observers' goroutine: in registration order, in the order things happened, never while the client's lock is held.

func (*Client) OnRunFinished

func (c *Client) OnRunFinished(fn workflow.RunFinishedFunc) error

OnRunFinished registers fn to observe every run end (see workflow.RunNotifier). Observers run on one notifier goroutine, in registration order and in the order runs ended, never on the goroutine that enqueued or cancelled the run, and never while the client's lock is held, so an observer may call back into the client.

func (*Client) OnTick

func (c *Client) OnTick(fn workflow.TickObserver) error

OnTick registers fn to observe every schedule tick (see workflow.TickNotifier). Tick observers share the run-finished observers' goroutine and guarantees: in registration order, in the order ticks happened, never while the client's lock is held.

func (*Client) Pause

func (c *Client) Pause(ctx context.Context, t workflow.PauseTarget) error

Pause holds the runs t targets; see workflow.Pauser.

func (*Client) PauseSchedule

func (c *Client) PauseSchedule(_ context.Context, t workflow.ScheduleTarget) error

PauseSchedule stops a schedule, or every schedule, from firing. See workflow.SchedulePauser: a tick that falls due during the pause never fires, not even on resume.

func (*Client) Paused

func (c *Client) Paused(ctx context.Context) ([]workflow.PauseTarget, error)

Paused lists the pauses in force: All first, then workflows, then queues, each by name.

func (*Client) PayloadLimit

func (c *Client) PayloadLimit() int

PayloadLimit reports the WithPayloadLimit cap (workflow.PayloadLimiter); zero means none.

func (*Client) QueueLoads

func (c *Client) QueueLoads(ctx context.Context) ([]workflow.QueueLoad, error)

QueueLoads reports the load of every queue given to WithQueues, sorted by name; see workflow.WorkerScaler. Depth counts the attempts ready for a worker (a pause holding them still counts them: they are waiting). A queue whose Workers is zero (no per-queue cap) reports the pool size (WithWorkers), the most it can run at once. Without WithQueues there are no queues to balance and the list is empty.

func (*Client) Register

func (c *Client) Register(wf workflow.Workflow) error

Register validates wf and stores it. Cron expressions are parsed here so a typo fails now, not at the first fire.

func (*Client) Reschedule

func (c *Client) Reschedule(ctx context.Context, ref workflow.RunRef, at time.Time) (workflow.RunRef, error)

Reschedule moves a delayed run that has not started to at (see workflow.RunRescheduler).

func (*Client) Result

func (c *Client) Result(ctx context.Context, ref workflow.RunRef) ([]byte, error)

Result returns a succeeded run's result (see workflow.ResultReader).

func (*Client) Resume

func (c *Client) Resume(ctx context.Context, t workflow.PauseTarget) error

Resume lifts a pause; Resume(PauseAll()) lifts every pause.

func (*Client) ResumeSchedule

func (c *Client) ResumeSchedule(_ context.Context, t workflow.ScheduleTarget) error

ResumeSchedule lets a paused schedule, or every schedule, fire again from its next tick.

func (*Client) Retry

func (c *Client) Retry(ctx context.Context, ref workflow.RunRef) (workflow.RunRef, error)

Retry re-runs a failed run from the step that failed; see workflow.RunRetrier. The run keeps its RunRef. Its concurrency and rate limits apply again, as for a new run.

func (*Client) RunAll

func (c *Client) RunAll(ctx context.Context) (RunAllReport, error)

RunAll runs everything now, for a test: delayed starts begin at once, retry backoffs, snoozes and sleep steps end at once, and it returns when no run it covers can move further (finished, or waiting for an event). Timeouts are not hurried: a step timeout, wait deadline, heartbeat or RunTimeout still follows the client's clock. It needs Start. When runs are left that it cannot move (paused, rate-limited on a fake clock), it returns the report with an error wrapping ErrRunAllStalled; ctx ending returns ctx's error.

func (*Client) Runs

Runs lists runs matching q, newest enqueue first. The cursor is a position, not an offset, so runs enqueued between pages do not shift the next page.

func (*Client) Schedule

Schedule registers a recurring trigger evaluated in s.Location on the injected clock. It needs Start first and a registered workflow.

A schedule with a Name is upserted by (Workflow, Name), as on the SQL driver: calling Schedule again with the same name returns the same ScheduleID and replaces the schedule (re-activating it after an Unschedule) instead of adding a second. A replaced schedule computes its next tick from the moment of the call, so an unchanged schedule keeps its next fire time. Without a Name every call adds a schedule.

func (*Client) Schedules

func (c *Client) Schedules(ctx context.Context) ([]workflow.ScheduleInfo, error)

Schedules lists the live schedules, declared and run-time, sorted by workflow, name and ID, each with its next fire time in its zone (zero while paused).

func (*Client) SetWorkers

func (c *Client) SetWorkers(ctx context.Context, queue string, n int) error

SetWorkers sets the worker cap of a queue given to WithQueues; see workflow.WorkerScaler. The cap is within the pool (WithWorkers): a cap above the pool size cannot run more than the pool at once, so give the pool at least the balancer's budget. Lowering it lets running attempts finish; raising it wakes idle workers at once.

func (*Client) Signal

func (c *Client) Signal(ctx context.Context, ev workflow.Event) error

Signal resumes every run currently waiting on ev's name and key, and keeps ev so a run enqueued before this call that reaches a matching wait step later takes it then (once per run). Kept signals older than the oldest unfinished run are dropped, which bounds the buffer.

func (*Client) Start

func (c *Client) Start(ctx context.Context) error

Start checks every workflow against Capabilities and refuses expression keys (KeyExpr) with an UnsupportedError, then starts the workers and the declared cron schedules. It does not block. Cancelling ctx shuts the client down (see Stop).

func (*Client) Status

func (c *Client) Status(_ context.Context, ref workflow.RunRef) (workflow.Status, error)

Status reports where a run is.

func (*Client) Stop

func (c *Client) Stop()

Stop shuts the client down and waits until every goroutine it started has exited. Unfinished runs become StatusCancelled. It is safe to call more than once, and before Start (a no-op).

func (*Client) StopCause

func (c *Client) StopCause() error

StopCause returns the *workflow.RecycleError when a WithRecycle limit stopped the client, and nil otherwise; see workflow.StopCauser.

func (*Client) TriggerSchedule

func (c *Client) TriggerSchedule(ctx context.Context, id workflow.ScheduleID) (workflow.RunRef, error)

TriggerSchedule runs schedule id now with its input and labels (see workflow.ScheduleTriggerer): it obeys the overlap policy, ignores windows, ScheduleWhen and a pause, and becomes the schedule's last fire.

func (*Client) Unschedule

func (c *Client) Unschedule(_ context.Context, id workflow.ScheduleID) error

Unschedule stops a schedule. An empty id, or one already removed, is a no-op; an id this client never issued returns ErrNotFound. A declared cron is part of its workflow and is refused (ErrInvalid): remove it from Workflow.Cron instead, or pause it.

type Option

type Option func(*Client)

Option configures a Client.

func WithClock

func WithClock(c clock.Clock) Option

WithClock sets the time source of every timer and schedule. The default is clock.Real; tests pass clock.NewFake.

func WithCronParser

func WithCronParser(p cron.Parser) Option

WithCronParser replaces the cron parser behind Workflow.Cron and Schedule.Cron (cron.Parse by default), for a dialect the standard one lacks: the extended "L", "W" and "#" fields, a seconds field, hashed minutes. It is opt-in and gives up "the same spec on every driver" for the expressions only this parser understands; see cron.Parser. Nil is ignored.

func WithErrorHistory

func WithErrorHistory(n int) Option

WithErrorHistory keeps the newest n failed attempts of each run in RunInfo.Errors (workflow.CapErrorHistory). Without the option a run keeps workflow.DefaultErrorHistory; n <= 0 keeps none.

func WithJitterSource

func WithJitterSource(rnd func() float64) Option

WithJitterSource sets where Backoff.Jitter draws its uniform values in [0, 1), so a test can pin them. The default is math/rand/v2. It must be safe for concurrent use. Nil is ignored.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets where the driver reports what it cannot return to a caller (a cron fire that failed to enqueue, an OnFailure handler error). The default discards.

func WithMiddleware

func WithMiddleware(mw ...workflow.Middleware) Option

WithMiddleware wraps every step handler and OnFailure handler. The first middleware is the outermost.

func WithNodeID

func WithNodeID(id string) Option

WithNodeID names this client's node in StepInfo.Node, AttemptError.Node, RunInfo.AttemptedBy and Nodes (workflow.CapNodeIdentity). The default is workflow.DefaultNodeID. An empty id is ignored.

func WithPayloadLimit

func WithPayloadLimit(n int) Option

WithPayloadLimit refuses at Enqueue a job whose payload (or a chained job's) is over n bytes, with a *workflow.PayloadTooLargeError, so a test on this driver catches a payload a production engine would reject. Zero or less means no limit, the default.

func WithQueues

func WithQueues(qs ...workflow.QueueConfig) Option

WithQueues makes the client serve only these queues, each with its own worker cap and priority (see workflow.QueueConfig). Without it the client serves every queue from one pool. Because this driver is one process, a run on a queue it does not serve could never run, so Start refuses a workflow whose queue is not listed and Enqueue refuses a Job.Queue that is not (both ErrInvalid). An invalid list is reported by Start. Calling it again replaces the list.

func WithRecycle

func WithRecycle(r workflow.Recycle) Option

WithRecycle makes the client stop itself once a limit in r is reached (finished attempts, time since Start, memory), so a supervisor can replace the process; see workflow.Recycle. The client then drains as Drain does, its Done channel closes and StopCause returns the *workflow.RecycleError; workflow.Serve returns it. Since nothing in memory outlives the client, runs left unfinished become StatusCancelled. Start refuses an invalid r (workflow.ValidateRecycle).

func WithRunRetention

func WithRunRetention(r RunRetention) Option

WithRunRetention replaces DefaultRunRetention. RunRetention{} keeps every finished run until Delete, for a test or a short-lived tool that wants to inspect everything; negative fields are treated as zero. Finished runs past the limits are forgotten when a run ends, when one is enqueued and when Runs lists them; afterwards Status returns ErrNotFound for them, as after Delete.

func WithStopWhenIdle

func WithStopWhenIdle(grace time.Duration) Option

WithStopWhenIdle makes the client stop by itself, as Drain would, once its last unfinished run (delayed, queued, running or waiting) has ended and no run was enqueued for grace on the injected clock: a worker that stops when its queue is empty. It is for batch-style processes: Start, enqueue the work, wait on Done. A client that never ran anything never stops this way, so Start followed by Enqueue is safe. Schedules do not keep it alive. A grace below zero is ignored.

func WithWorkers

func WithWorkers(n int) Option

WithWorkers sets how many step attempts may execute at once. Values below 1 are ignored.

type RunAllReport

type RunAllReport struct {
	Succeeded, Failed, Cancelled, Discarded int

	// Waiting counts runs left suspended on a wait step: an event they
	// need has not been signalled, which RunAll cannot do for them.
	Waiting int
}

RunAllReport counts what became of the runs RunAll covered: the runs unfinished when it was called and the runs enqueued while it ran (chained jobs, children, cron fires).

type RunRetention

type RunRetention struct {
	// MaxAge forgets a finished run once it finished more than MaxAge ago
	// on the injected clock.
	MaxAge time.Duration

	// MaxRuns forgets the oldest finished runs beyond this many.
	MaxRuns int
}

RunRetention bounds how many finished runs the client remembers for Status, Runs, Retry and Delete. A run that is not finished is never forgotten. Zero fields mean no limit on that axis.

Jump to

Keyboard shortcuts

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