@cslug/workflow 0.0.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,9 @@
1
+ # @cslug/workflow
2
+
3
+ Durable workflows for cslug apps: an `@inject()` class whose `run(ctx, input)` is journaled step by step in
4
+ PostgreSQL and woken up by queue jobs. Steps run once (retried with backoff, without holding a worker), sleeps last
5
+ days, runs wait for events and signals, and a run picks up where it stopped after a deploy or a crash. No server
6
+ besides the app's Postgres and Redis. `cslug add workflow` installs it and lists `WorkflowProvider`.
7
+
8
+ Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md),
9
+ [guide 25](../../guides/25-workflows.md).
package/docs/README.md ADDED
@@ -0,0 +1,71 @@
1
+ # @cslug/workflow
2
+
3
+ `WorkflowProvider` (after `DatabaseProvider` and `QueueProvider`) registers the migration, the
4
+ `cslug.workflow.resume` job and `Workflows`, and imports `app/workflows/` so every process (web, worker) knows every
5
+ workflow and watches the events they wait for.
6
+
7
+ ## Tables (migration `00000000_000800`)
8
+
9
+ | Table | |
10
+ |---|---|
11
+ | `cslug_workflow_runs` | `id` (text: yours or a UUIDv7), `workflow`, `status`, `input`, `output`, `error`, `waiting_for`, `waiting_match`, `wake_at`, timestamps, `finished_at` |
12
+ | `cslug_workflow_steps` | The journal: `(run_id, seq)`, `name`, `kind` (`step`, `sleep`, `wait`, `now`, `uuid`), `status` (`completed`, `pending`, `retrying`, `failed`), `result`, `error`, `attempts`, `wake_at` |
13
+ | `cslug_workflow_signals` | Signals and matched events not yet taken by their run |
14
+
15
+ ## Running a run
16
+
17
+ `start()` inserts the run (`on conflict do nothing`: an existing id returns `{ created: false }`) and dispatches a
18
+ resume, through the outbox when inside a transaction. A resume (`Workflows.resume(runId)`):
19
+
20
+ 1. takes the advisory lock `cslug:workflow:<id>` (one process at a time per run);
21
+ 2. stops if the run is finished or cancelled; fails it with `workflow.unknown` if no workflow has its name;
22
+ 3. replays `run(ctx, input)` with the journal: each `ctx` call takes the next position, checks its name and kind
23
+ (`workflow.nondeterministic` otherwise) and returns the stored result when it is completed;
24
+ 4. ends `completed` (output stored), `failed` (error stored), or suspended: `sleeping` / `waiting` with `wake_at`,
25
+ and a delayed resume job for `wake_at` when the suspension point is new (or the job ran early).
26
+
27
+ A `ctx.step` runs `fn` and writes its journal entry in one database transaction. On failure, the entry becomes
28
+ `retrying` with `wake_at` after the backoff, and the run sleeps; after `tries` it is `failed` and the run fails
29
+ with `workflow.step_failed`.
30
+
31
+ ## Waiting
32
+
33
+ `waitForSignal(name)` waits on the channel `signal:<name>`; `workflows.signal(runId, name, data)` stores the signal
34
+ and wakes the run, so a signal sent early is kept. `waitFor(Event, match)` waits on `event:<event name>` with
35
+ `match` stored as JSON; an `EventBus` listener for each event in a workflow's `static waitsFor` finds the waiting
36
+ runs whose match the payload contains (`waiting_match <@ payload`), stores the payload for them and wakes them, in
37
+ the emitter's transaction. Timeouts are `wake_at`: the wait then returns `undefined`.
38
+
39
+ Values cross the journal as JSON: bigint and `Date` become strings (`Json<T>` types it).
40
+
41
+ ## Sagas and cancelling
42
+
43
+ `step(name, fn, { compensate })`: compensations are functions, so they are not stored; the replay registers each
44
+ finished step's `compensate` as it passes it. When the replay ends with an error other than
45
+ `workflow.nondeterministic`, the same resume runs the registered compensations last first. Each is journaled at
46
+ seq `-(step seq + 1)` (kind `compensate`), runs in a transaction with its entry, and is retried with the step's
47
+ `tries` and `backoff`: the run is `compensating` and sleeps until then. It ends `compensated` (the original error
48
+ kept) or, on a compensation's last try, `compensation_failed` (that error). Without compensations it ends `failed`.
49
+
50
+ `cancel(id)` sets `cancelling` and queues a resume. That replay runs in cancel mode: the first `ctx` call whose
51
+ entry is not completed throws `Cancellation`; the finished steps are compensated the same way, and the run ends
52
+ `cancelled` (or `compensation_failed`).
53
+
54
+ ## Operations
55
+
56
+ `Workflows.list({ status, workflow, limit })`, `retry(id)` (a `failed` run back to `pending`, a
57
+ `compensation_failed` one to `compensating`; its failed journal entries become `retrying` with no wake-up time and
58
+ zero attempts, so they run at once), `prune(olderThan)` (finished runs, with their journals and signals, by
59
+ `finished_at`). Commands: `workflow:list [--status] [--workflow] [--limit] [--json]`, `workflow:show <id> [--json]`,
60
+ `workflow:retry <id>`, `workflow:cancel <id>`, `workflow:prune [--older-than=90d]`. `cslug describe workflows`: name,
61
+ class and events waited for.
62
+
63
+ Traces: a span `workflow.step <name>` (attributes `cslug.workflow.run_id`, `.step`, `.attempt`) around each step or
64
+ compensation that runs, failed ones recorded. Audit (with `@cslug/security`, loaded at runtime): `workflow.started`
65
+ in `start()`, and `workflow.<final status>` when a run ends, subject `{ type: 'workflow_run', id }`, data
66
+ `{ workflow }`; `Workflows.audit` can be set to any `{ record(action, options) }`.
67
+
68
+ ## Testing
69
+
70
+ `testApp({ fakes: ['workflows'] })` → `t.workflows`, a `WorkflowFake`: `runUntilIdle({ max?, fastForward? })`,
71
+ `assertStatus(id, status, output?)`, `find`, `journal`, `signal`. See guide 25 § Testing.
package/docs/api.md ADDED
@@ -0,0 +1,23 @@
1
+ # @cslug/workflow API
2
+
3
+ | Export | |
4
+ |---|---|
5
+ | `Workflow<I, O>` | Base class: `run(ctx, input)`; statics `workflowName?`, `waitsFor?`; `Workflow.start(input, { id? })` → `{ id, created }` |
6
+ | `WorkflowContext` | `runId`, `step(name, fn, { tries?, backoff?, timeout? })`, `sleep(duration)`, `sleepUntil(date)`, `waitFor(Event, match?, { timeout? })`, `waitForSignal(name, { timeout? })`, `now()`, `uuid()` |
7
+ | `StepOptions<T>` | `{ tries?: number (3), backoff?: Backoff (30 s doubled, ≤ 1 h), timeout?: Duration, compensate?: (result: Json<T>) => unknown }` |
8
+ | `Workflows` | `start(Workflow, input, options?)`, `signal(runId, name, data?)`, `find(runId)`, `list({ status?, workflow?, limit? })`, `retry(runId)`, `prune(olderThan)`, `audit?`, `cancel(runId)` (→ `cancelling`, compensates, → `cancelled`), `resume(runId, { wakeAt? })`, `register(Workflow)`, `store` |
9
+ | `WorkflowRun` | `{ id, workflow, status, input, output, error, waitingFor, waitingMatch, wakeAt, createdAt, updatedAt, finishedAt }` |
10
+ | `RunStatus`, `FINISHED` | `pending`, `running`, `sleeping`, `waiting`, `compensating`, `cancelling`, `completed`, `failed`, `cancelled`, `compensated`, `compensation_failed`; the last five |
11
+ | `JournalEntry`, `WorkflowStore` | A journal entry; the SQL (`store.journal(runId)`) |
12
+ | `WorkflowFake`, `installWorkflowFake` | `t.workflows`: `runUntilIdle({ max?, fastForward? })`, `assertStatus(id, status, output?)`, `find`, `journal`, `signal` |
13
+ | `workflowCommands` | `WorkflowListCommand`, `WorkflowShowCommand`, `WorkflowRetryCommand`, `WorkflowCancelCommand`, `WorkflowPruneCommand` |
14
+ | `WorkflowAudit` | `{ record(action, { subject, data }) }` (what `Workflows.audit` takes) |
15
+ | `WorkflowResumeJob` | The queue job `cslug.workflow.resume` (`{ runId, wakeAt? }`) |
16
+ | `WorkflowProvider`, `WORKFLOW_MIGRATIONS` | |
17
+ | `registerWorkflow`, `findWorkflow`, `workflowName`, `isWorkflowClass` | The registry |
18
+ | `StepFailedError`, `CompensationFailedError`, `NondeterminismError` | `workflow.step_failed`, `workflow.compensation_failed`, `workflow.nondeterministic` |
19
+ | `Suspension`, `Cancellation`, `isSuspension` | What `ctx` throws to stop a replay (suspend, or a run being cancelled): rethrow it from a `catch` |
20
+ | `Json<T>` | A value after a JSON round trip |
21
+
22
+ Error codes: `workflow.step_failed`, `workflow.compensation_failed`, `workflow.step_timeout`, `workflow.nondeterministic`, `workflow.unknown`,
23
+ `workflow.duplicate`, `workflow.no_provider`, `workflow_run.not_found` (signal to an unknown run).
@@ -0,0 +1,48 @@
1
+ -- up
2
+ create table cslug_workflow_runs (
3
+ id text primary key,
4
+ workflow text not null,
5
+ status text not null default 'pending',
6
+ input jsonb,
7
+ output jsonb,
8
+ error jsonb,
9
+ waiting_for text,
10
+ waiting_match jsonb,
11
+ wake_at timestamptz,
12
+ created_at timestamptz not null default now(),
13
+ updated_at timestamptz not null default now(),
14
+ finished_at timestamptz
15
+ );
16
+ create index cslug_workflow_runs_status_idx on cslug_workflow_runs (status, wake_at);
17
+ create index cslug_workflow_runs_waiting_idx on cslug_workflow_runs (waiting_for) where status = 'waiting';
18
+
19
+ create table cslug_workflow_steps (
20
+ run_id text not null references cslug_workflow_runs (id) on delete cascade,
21
+ seq integer not null,
22
+ name text not null,
23
+ kind text not null,
24
+ status text not null,
25
+ result jsonb,
26
+ error jsonb,
27
+ attempts integer not null default 0,
28
+ wake_at timestamptz,
29
+ created_at timestamptz not null default now(),
30
+ updated_at timestamptz not null default now(),
31
+ primary key (run_id, seq)
32
+ );
33
+
34
+ create table cslug_workflow_signals (
35
+ id uuid primary key,
36
+ run_id text not null references cslug_workflow_runs (id) on delete cascade,
37
+ name text not null,
38
+ data jsonb,
39
+ created_at timestamptz not null default now(),
40
+ consumed_at timestamptz
41
+ );
42
+ create index cslug_workflow_signals_waiting_idx on cslug_workflow_signals (run_id, name, created_at)
43
+ where consumed_at is null;
44
+
45
+ -- down
46
+ drop table cslug_workflow_signals;
47
+ drop table cslug_workflow_steps;
48
+ drop table cslug_workflow_runs;
package/package.json CHANGED
@@ -1 +1,50 @@
1
- {"name":"@cslug/workflow","version":"0.0.0","description":"Placeholder: the real package is published by the cslug release workflow.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/cslugts/cslug.git","directory":"packages/workflow"}}
1
+ {
2
+ "name": "@cslug/workflow",
3
+ "version": "0.11.0",
4
+ "description": "Durable workflows on PostgreSQL and the queue: journaled steps, durable sleeps, waits for events and signals.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/cslugts/cslug.git",
10
+ "directory": "packages/workflow"
11
+ },
12
+ "homepage": "https://github.com/cslugts/cslug/tree/main/packages/workflow",
13
+ "keywords": [
14
+ "cslug",
15
+ "bun",
16
+ "framework",
17
+ "workflow",
18
+ "durable-execution",
19
+ "saga",
20
+ "postgres"
21
+ ],
22
+ "exports": {
23
+ ".": "./src/index.ts"
24
+ },
25
+ "files": [
26
+ "src",
27
+ "migrations",
28
+ "docs",
29
+ "README.md"
30
+ ],
31
+ "engines": {
32
+ "bun": ">=1.3.14"
33
+ },
34
+ "peerDependencies": {
35
+ "@cslug/core": "0.11.0",
36
+ "@cslug/database": "0.11.0",
37
+ "@cslug/queue": "0.11.0",
38
+ "@cslug/security": "0.11.0"
39
+ },
40
+ "devDependencies": {
41
+ "@cslug/redis": "workspace:*",
42
+ "@cslug/testing": "workspace:*",
43
+ "@cslug/security": "workspace:*"
44
+ },
45
+ "peerDependenciesMeta": {
46
+ "@cslug/security": {
47
+ "optional": true
48
+ }
49
+ }
50
+ }
@@ -0,0 +1,125 @@
1
+ import { arg, Command, flag, resolve } from '@cslug/core'
2
+ import type { RunStatus } from './store'
3
+ import { Workflows } from './workflows'
4
+
5
+ const when = (d: Date | null) => (d ? new Date(d).toISOString().replace('T', ' ').slice(0, 19) : '')
6
+
7
+ /** `cslug workflow:list [--status=failed] [--workflow=booking.deposit] [--limit=50]`. */
8
+ export class WorkflowListCommand extends Command {
9
+ static signature = 'workflow:list'
10
+ static description = 'List workflow runs, newest first'
11
+ static args = {
12
+ status: flag.string().optional().describe('pending, sleeping, waiting, failed, completed, …'),
13
+ workflow: flag.string().optional().describe('A workflow name'),
14
+ limit: flag.number().default(50),
15
+ json: flag.boolean(),
16
+ }
17
+
18
+ async handle({ status, workflow, limit, json }: Command.Args<typeof WorkflowListCommand>) {
19
+ const runs = await resolve(Workflows).list({ status: status as RunStatus | undefined, workflow, limit })
20
+ if (json) return this.line(JSON.stringify(runs))
21
+ if (!runs.length) return this.info('No runs')
22
+ this.table(
23
+ runs.map((r) => ({
24
+ id: r.id,
25
+ workflow: r.workflow,
26
+ status: r.status,
27
+ wakeAt: when(r.wakeAt),
28
+ waitingFor: r.waitingFor ?? '',
29
+ updated: when(r.updatedAt),
30
+ })),
31
+ )
32
+ }
33
+ }
34
+
35
+ /** `cslug workflow:show <id>`: a run and its journal. */
36
+ export class WorkflowShowCommand extends Command {
37
+ static signature = 'workflow:show'
38
+ static description = 'Show a workflow run and its journal'
39
+ static args = { id: arg.string(), json: flag.boolean() }
40
+
41
+ async handle({ id, json }: Command.Args<typeof WorkflowShowCommand>) {
42
+ const workflows = resolve(Workflows)
43
+ const run = await workflows.find(id)
44
+ if (!run) {
45
+ this.error(`No workflow run ${id}`)
46
+ return 1
47
+ }
48
+ const journal = await workflows.store.journal(id)
49
+ if (json) {
50
+ this.line(JSON.stringify({ run, journal }))
51
+ return 0
52
+ }
53
+ this.line(`${run.id} ${run.workflow} ${run.status}`)
54
+ if (run.wakeAt) this.line(`wakes at ${when(run.wakeAt)}${run.waitingFor ? `, waiting for ${run.waitingFor}` : ''}`)
55
+ if (run.error) this.line(`error: ${run.error.code ?? run.error.name}: ${run.error.message}`)
56
+ this.line(`input: ${JSON.stringify(run.input)}`)
57
+ if (run.output !== null) this.line(`output: ${JSON.stringify(run.output)}`)
58
+ this.line()
59
+ this.table(
60
+ journal.map((e) => ({
61
+ seq: e.seq,
62
+ kind: e.kind,
63
+ name: e.name,
64
+ status: e.status,
65
+ attempts: e.attempts,
66
+ wakeAt: when(e.wakeAt),
67
+ error: (e.error as { message?: string } | null)?.message ?? '',
68
+ })),
69
+ )
70
+ return 0
71
+ }
72
+ }
73
+
74
+ /** `cslug workflow:retry <id>`: a failed run, again from the step (or compensation) that failed. */
75
+ export class WorkflowRetryCommand extends Command {
76
+ static signature = 'workflow:retry'
77
+ static description = 'Retry a failed workflow run from where it failed'
78
+ static args = { id: arg.string() }
79
+
80
+ async handle({ id }: Command.Args<typeof WorkflowRetryCommand>) {
81
+ if (!(await resolve(Workflows).retry(id))) {
82
+ this.error(`${id} is not a failed run (failed or compensation_failed)`)
83
+ return 1
84
+ }
85
+ this.success(`${id} queued again`)
86
+ return 0
87
+ }
88
+ }
89
+
90
+ /** `cslug workflow:cancel <id>`. */
91
+ export class WorkflowCancelCommand extends Command {
92
+ static signature = 'workflow:cancel'
93
+ static description = 'Cancel a workflow run (its finished steps are compensated)'
94
+ static args = { id: arg.string() }
95
+
96
+ async handle({ id }: Command.Args<typeof WorkflowCancelCommand>) {
97
+ if (!(await resolve(Workflows).cancel(id))) {
98
+ this.error(`${id} has finished, is being cancelled, or does not exist`)
99
+ return 1
100
+ }
101
+ this.success(`${id} is cancelling`)
102
+ return 0
103
+ }
104
+ }
105
+
106
+ /** `cslug workflow:prune --older-than=90d`: delete finished runs and their journals. */
107
+ export class WorkflowPruneCommand extends Command {
108
+ static signature = 'workflow:prune'
109
+ static description = 'Delete finished workflow runs older than a duration'
110
+ static args = { olderThan: flag.string().default('90d').describe('A duration: 30d, 12w') }
111
+
112
+ async handle({ olderThan }: Command.Args<typeof WorkflowPruneCommand>) {
113
+ const n = await resolve(Workflows).prune(olderThan)
114
+ this.success(`Deleted ${n} finished run(s) older than ${olderThan}`)
115
+ return 0
116
+ }
117
+ }
118
+
119
+ export const workflowCommands = [
120
+ WorkflowListCommand,
121
+ WorkflowShowCommand,
122
+ WorkflowRetryCommand,
123
+ WorkflowCancelCommand,
124
+ WorkflowPruneCommand,
125
+ ]
package/src/context.ts ADDED
@@ -0,0 +1,283 @@
1
+ import { type AnyEventClass, type Clock, CslugError, type Duration, parseDuration, type Tracer } from '@cslug/core'
2
+ import type { Database } from '@cslug/database'
3
+ import { type Backoff, backoffDelay, Job } from '@cslug/queue'
4
+ import { Cancellation, CompensationFailedError, NondeterminismError, StepFailedError, Suspension } from './errors'
5
+ import { errorJson, type Json, toJson } from './json'
6
+ import type { JournalEntry, WorkflowStore } from './store'
7
+
8
+ export type StepOptions<T = unknown> = {
9
+ /** Attempts in all, the first included (default 3). Also for its compensation. */
10
+ tries?: number
11
+ /** Wait before retry n: a duration, one per retry, or a function (default: 30 s, doubled each time, at most 1 h). */
12
+ backoff?: Backoff
13
+ /** An attempt longer than this fails (and is retried). */
14
+ timeout?: Duration
15
+ /**
16
+ * Undo this step (a saga): when the run later fails or is cancelled, the compensations of its finished steps run
17
+ * in reverse order, each once (journaled, retried like the step), with the step's result.
18
+ */
19
+ compensate?: (result: Json<T>) => unknown
20
+ }
21
+
22
+ type Compensation = { seq: number; name: string; result: unknown; options: StepOptions<never> }
23
+
24
+ const DEFAULT_BACKOFF = Job.exponential('30s', { max: '1h' })
25
+
26
+ /** The event's payload type. */
27
+ type PayloadOf<E> = E extends abstract new (payload: infer P) => unknown ? P : never
28
+
29
+ async function withTimeout<T>(work: Promise<T>, timeout: Duration | undefined, step: string): Promise<T> {
30
+ if (timeout === undefined) return work
31
+ let timer: ReturnType<typeof setTimeout> | undefined
32
+ try {
33
+ return await Promise.race([
34
+ work,
35
+ new Promise<never>((_, reject) => {
36
+ timer = setTimeout(
37
+ () => reject(new CslugError('workflow.step_timeout', `Step "${step}" took longer than ${timeout}`)),
38
+ parseDuration(timeout),
39
+ )
40
+ }),
41
+ ])
42
+ } finally {
43
+ clearTimeout(timer)
44
+ }
45
+ }
46
+
47
+ /**
48
+ * What `run(ctx, input)` gets. Each call has a place in the run's journal: a call already finished returns its
49
+ * stored result; the first unfinished one runs, or suspends the run (guide 25).
50
+ */
51
+ export class WorkflowContext {
52
+ private seq = 0
53
+ private readonly entries: Map<number, JournalEntry>
54
+ /** The finished steps with a `compensate`, in order, as the replay passes them. */
55
+ private readonly compensations: Compensation[] = []
56
+
57
+ constructor(
58
+ /** The run's id. */
59
+ readonly runId: string,
60
+ journal: JournalEntry[],
61
+ private readonly store: WorkflowStore,
62
+ private readonly db: Database,
63
+ private readonly clock: Clock,
64
+ /** Replaying a run being cancelled: the first call that has not run stops it. */
65
+ private readonly cancelling = false,
66
+ private readonly tracer?: Tracer,
67
+ ) {
68
+ this.entries = new Map(journal.map((e) => [e.seq, e]))
69
+ }
70
+
71
+ private next(name: string, kind: JournalEntry['kind']): { seq: number; entry?: JournalEntry } {
72
+ const seq = this.seq++
73
+ const entry = this.entries.get(seq)
74
+ if (entry && (entry.name !== name || entry.kind !== kind)) throw new NondeterminismError(seq, entry.name, name)
75
+ if (this.cancelling && entry?.status !== 'completed') throw new Cancellation()
76
+ return { seq, entry }
77
+ }
78
+
79
+ /** Whether a finished step of this replay has something to undo. */
80
+ get hasCompensations(): boolean {
81
+ return this.compensations.length > 0
82
+ }
83
+
84
+ private finished<T>(seq: number, name: string, result: T, options: StepOptions<never>): T {
85
+ if (options.compensate) this.compensations.push({ seq, name, result, options })
86
+ return result
87
+ }
88
+
89
+ /**
90
+ * Run the compensations of the finished steps, last first, each once: journaled at seq `-(step seq + 1)`, in a
91
+ * transaction with its entry, retried after the step's backoff (the run suspends). Throws
92
+ * `CompensationFailedError` after the last try.
93
+ */
94
+ async compensate(): Promise<void> {
95
+ for (const c of [...this.compensations].reverse()) {
96
+ const seq = -(c.seq + 1)
97
+ const name = `compensate:${c.name}`
98
+ const entry = this.entries.get(seq)
99
+ if (entry?.status === 'completed') continue
100
+ if (entry?.status === 'failed') throw new CompensationFailedError(c.name, entry.error)
101
+ if (this.waiting(entry)) throw new Suspension('sleeping', entry?.wakeAt ?? null)
102
+ const attempts = (entry?.attempts ?? 0) + 1
103
+ const base = { seq, name, kind: 'compensate' as const, attempts }
104
+ try {
105
+ await this.traced(name, attempts, () =>
106
+ this.db.transaction(async () => {
107
+ await withTimeout(Promise.resolve(c.options.compensate?.(c.result as never)), c.options.timeout, name)
108
+ await this.record({ ...base, status: 'completed', wakeAt: null })
109
+ }),
110
+ )
111
+ } catch (error) {
112
+ if (attempts < (c.options.tries ?? 3)) {
113
+ const wakeAt = new Date(
114
+ this.clock.now().getTime() + backoffDelay(c.options.backoff ?? DEFAULT_BACKOFF, attempts),
115
+ )
116
+ await this.record({ ...base, status: 'retrying', error: errorJson(error), wakeAt })
117
+ throw new Suspension('sleeping', wakeAt)
118
+ }
119
+ await this.record({ ...base, status: 'failed', error: errorJson(error), wakeAt: null })
120
+ throw new CompensationFailedError(c.name, error)
121
+ }
122
+ }
123
+ }
124
+
125
+ private due(at: Date | null): boolean {
126
+ return at !== null && this.clock.now().getTime() >= new Date(at).getTime()
127
+ }
128
+
129
+ /** A retry waits for its time (one without a time, after `workflow:retry`, runs now). */
130
+ private waiting(entry: JournalEntry | undefined): boolean {
131
+ return entry?.status === 'retrying' && entry.wakeAt !== null && !this.due(entry.wakeAt)
132
+ }
133
+
134
+ /** `fn` in a span `workflow.step <name>` (only when it runs, not when it is replayed; errors recorded). */
135
+ private traced<T>(name: string, attempt: number, fn: () => Promise<T>): Promise<T> {
136
+ if (!this.tracer?.enabled) return fn()
137
+ return this.tracer.span(
138
+ `workflow.step ${name}`,
139
+ {
140
+ attributes: {
141
+ 'cslug.workflow.run_id': this.runId,
142
+ 'cslug.workflow.step': name,
143
+ 'cslug.workflow.attempt': attempt,
144
+ },
145
+ },
146
+ fn,
147
+ )
148
+ }
149
+
150
+ private async record(entry: Parameters<WorkflowStore['save']>[1]): Promise<void> {
151
+ await this.store.save(this.runId, entry)
152
+ this.entries.set(entry.seq, { result: null, error: null, ...entry } as JournalEntry)
153
+ }
154
+
155
+ /**
156
+ * Run `fn` once and store its result (as JSON). `fn` runs in a database transaction together with the journal
157
+ * entry. A failure is retried after `backoff` without holding a worker; after `tries`, the run fails.
158
+ */
159
+ async step<T>(
160
+ name: string,
161
+ fn: () => T | Promise<T>,
162
+ options: StepOptions<Awaited<T>> = {},
163
+ ): Promise<Json<Awaited<T>>> {
164
+ const { seq, entry } = this.next(name, 'step')
165
+ const opts = options as StepOptions<never>
166
+ if (entry?.status === 'completed') return this.finished(seq, name, entry.result as Json<Awaited<T>>, opts)
167
+ if (entry?.status === 'failed') throw new StepFailedError(name, entry.error)
168
+ if (this.waiting(entry)) throw new Suspension('sleeping', entry?.wakeAt ?? null)
169
+ const attempts = (entry?.attempts ?? 0) + 1
170
+ try {
171
+ const value = await this.traced(name, attempts, () =>
172
+ this.db.transaction(async () => {
173
+ const value = toJson(await withTimeout(Promise.resolve(fn()), options.timeout, name))
174
+ await this.record({ seq, name, kind: 'step', status: 'completed', result: value, attempts, wakeAt: null })
175
+ return value as Json<Awaited<T>>
176
+ }),
177
+ )
178
+ return this.finished(seq, name, value, opts)
179
+ } catch (error) {
180
+ if (error instanceof Suspension) throw error
181
+ if (attempts < (options.tries ?? 3)) {
182
+ const wakeAt = new Date(this.clock.now().getTime() + backoffDelay(options.backoff ?? DEFAULT_BACKOFF, attempts))
183
+ await this.record({ seq, name, kind: 'step', status: 'retrying', error: errorJson(error), attempts, wakeAt })
184
+ throw new Suspension('sleeping', wakeAt)
185
+ }
186
+ await this.record({ seq, name, kind: 'step', status: 'failed', error: errorJson(error), attempts, wakeAt: null })
187
+ throw new StepFailedError(name, error)
188
+ }
189
+ }
190
+
191
+ /** Suspend the run for a duration (`'3d'`); a delayed job wakes it. */
192
+ sleep(duration: Duration): Promise<void> {
193
+ return this.sleepUntil(new Date(this.clock.now().getTime() + parseDuration(duration)))
194
+ }
195
+
196
+ /** Suspend the run until a moment. */
197
+ async sleepUntil(until: Date): Promise<void> {
198
+ const { seq, entry } = this.next('sleep', 'sleep')
199
+ if (entry?.status === 'completed') return
200
+ const wakeAt = entry?.wakeAt ? new Date(entry.wakeAt) : until
201
+ if (!entry) await this.record({ seq, name: 'sleep', kind: 'sleep', status: 'pending', attempts: 0, wakeAt })
202
+ if (!this.due(wakeAt)) throw new Suspension('sleeping', wakeAt)
203
+ await this.record({ seq, name: 'sleep', kind: 'sleep', status: 'completed', attempts: 0, wakeAt })
204
+ }
205
+
206
+ /**
207
+ * Suspend until `event` is emitted with a payload containing `match` (`{ bookingId }`); its payload (as JSON), or
208
+ * undefined after `timeout`. The workflow class lists the event in `static waitsFor`. Only runs already waiting
209
+ * see an event.
210
+ */
211
+ waitFor<E extends AnyEventClass>(
212
+ event: E,
213
+ match: Partial<Json<PayloadOf<E>>> = {},
214
+ options: { timeout?: Duration } = {},
215
+ ): Promise<Json<PayloadOf<E>> | undefined> {
216
+ const channel = `event:${event.eventName}`
217
+ return this.wait(channel, match as Record<string, unknown>, options.timeout) as Promise<
218
+ Json<PayloadOf<E>> | undefined
219
+ >
220
+ }
221
+
222
+ /** Suspend until `workflows.signal(runId, name, data)`; its data, or undefined after `timeout`. Kept if early. */
223
+ waitForSignal<T = unknown>(name: string, options: { timeout?: Duration } = {}): Promise<Json<T> | undefined> {
224
+ return this.wait(`signal:${name}`, undefined, options.timeout) as Promise<Json<T> | undefined>
225
+ }
226
+
227
+ private async wait(channel: string, match: Record<string, unknown> | undefined, timeout?: Duration) {
228
+ const { seq, entry } = this.next(channel, 'wait')
229
+ if (entry?.status === 'completed') return entry.result ?? undefined
230
+ const wakeAt = entry
231
+ ? entry.wakeAt && new Date(entry.wakeAt)
232
+ : timeout === undefined
233
+ ? null
234
+ : new Date(this.clock.now().getTime() + parseDuration(timeout))
235
+ if (!entry) await this.record({ seq, name: channel, kind: 'wait', status: 'pending', attempts: 0, wakeAt })
236
+ const got = await this.db.transaction(async () => {
237
+ const signal = await this.store.takeSignal(this.runId, channel)
238
+ if (signal)
239
+ await this.record({
240
+ seq,
241
+ name: channel,
242
+ kind: 'wait',
243
+ status: 'completed',
244
+ result: signal.data,
245
+ attempts: 0,
246
+ wakeAt,
247
+ })
248
+ return signal
249
+ })
250
+ if (got) return got.data ?? undefined
251
+ if (this.due(wakeAt)) {
252
+ await this.record({ seq, name: channel, kind: 'wait', status: 'completed', result: null, attempts: 0, wakeAt })
253
+ return undefined
254
+ }
255
+ throw new Suspension('waiting', wakeAt, channel, match)
256
+ }
257
+
258
+ /** The current time, recorded the first time (a replay sees the same value). */
259
+ async now(): Promise<Date> {
260
+ const { seq, entry } = this.next('now', 'now')
261
+ if (entry?.status === 'completed') return new Date(entry.result as string)
262
+ const now = this.clock.now()
263
+ await this.record({
264
+ seq,
265
+ name: 'now',
266
+ kind: 'now',
267
+ status: 'completed',
268
+ result: now.toISOString(),
269
+ attempts: 0,
270
+ wakeAt: null,
271
+ })
272
+ return now
273
+ }
274
+
275
+ /** A UUIDv7, recorded the first time. */
276
+ async uuid(): Promise<string> {
277
+ const { seq, entry } = this.next('uuid', 'uuid')
278
+ if (entry?.status === 'completed') return entry.result as string
279
+ const id = Bun.randomUUIDv7()
280
+ await this.record({ seq, name: 'uuid', kind: 'uuid', status: 'completed', result: id, attempts: 0, wakeAt: null })
281
+ return id
282
+ }
283
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,57 @@
1
+ import { CslugError } from '@cslug/core'
2
+
3
+ /** The message of an error, or of an error stored as JSON. */
4
+ const messageOf = (cause: unknown) =>
5
+ typeof (cause as { message?: unknown })?.message === 'string' ? (cause as { message: string }).message : String(cause)
6
+
7
+ /** A step failed on its last try; the run fails with it. */
8
+ export class StepFailedError extends CslugError {
9
+ constructor(
10
+ readonly step: string,
11
+ cause: unknown,
12
+ ) {
13
+ super('workflow.step_failed', `Step "${step}" failed: ${messageOf(cause)}`, {
14
+ cause,
15
+ })
16
+ }
17
+ }
18
+
19
+ /** The code no longer matches the run's journal (a call renamed, removed or moved before where the run is). */
20
+ export class NondeterminismError extends CslugError {
21
+ constructor(seq: number, expected: string, found: string) {
22
+ super(
23
+ 'workflow.nondeterministic',
24
+ `Call #${seq + 1} is "${found}" in the code but "${expected}" in the run's journal: steps before where a run is must not change (guide 25)`,
25
+ )
26
+ }
27
+ }
28
+
29
+ /**
30
+ * Thrown by `ctx` calls to stop a replay where the run must wait. Not an `Error`: let it through (a `catch`
31
+ * around `ctx` calls must rethrow it, or check `isSuspension`).
32
+ */
33
+ export class Suspension {
34
+ constructor(
35
+ readonly status: 'sleeping' | 'waiting',
36
+ readonly wakeAt: Date | null,
37
+ readonly waitingFor?: string,
38
+ readonly match?: Record<string, unknown>,
39
+ ) {}
40
+ }
41
+
42
+ /** Thrown by `ctx` calls of a run being cancelled, at the first call that has not run yet. */
43
+ export class Cancellation {}
44
+
45
+ /** A compensation failed on its last try. */
46
+ export class CompensationFailedError extends CslugError {
47
+ constructor(
48
+ readonly step: string,
49
+ cause: unknown,
50
+ ) {
51
+ super('workflow.compensation_failed', `Compensating "${step}" failed: ${messageOf(cause)}`, { cause })
52
+ }
53
+ }
54
+
55
+ /** True for what `ctx` throws to stop a replay (a suspension or a cancellation): rethrow it from a `catch`. */
56
+ export const isSuspension = (value: unknown): value is Suspension | Cancellation =>
57
+ value instanceof Suspension || value instanceof Cancellation