@cslug/workflow 0.0.0-stage → 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 +8 -2
- package/docs/README.md +71 -0
- package/docs/api.md +23 -0
- package/migrations/00000000_000800_cslug_workflows.sql +48 -0
- package/package.json +48 -4
- package/src/commands.ts +125 -0
- package/src/context.ts +283 -0
- package/src/errors.ts +57 -0
- package/src/fake.ts +88 -0
- package/src/index.ts +38 -0
- package/src/json.ts +21 -0
- package/src/provider.ts +66 -0
- package/src/store.ts +161 -0
- package/src/workflow.ts +78 -0
- package/src/workflows.ts +225 -0
package/src/fake.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { type Application, Clock, FakeClock } from '@cslug/core'
|
|
2
|
+
import { FINISHED, type JournalEntry, type WorkflowRun } from './store'
|
|
3
|
+
import { Workflows } from './workflows'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Workflows in tests (`testApp({ fakes: ['workflows'] })` → `t.workflows`): `runUntilIdle()` resumes every run that
|
|
7
|
+
* can move, synchronously, on the test's database, and fast-forwards the test clock (a `FakeClock`) over sleeps,
|
|
8
|
+
* retries and timeouts. Starting, signals and events work as in the app; nothing waits for a worker.
|
|
9
|
+
*/
|
|
10
|
+
export class WorkflowFake {
|
|
11
|
+
constructor(private readonly app: Application) {}
|
|
12
|
+
|
|
13
|
+
private get workflows(): Workflows {
|
|
14
|
+
return this.app.resolve(Workflows)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Resume runs until none can move: each unfinished run is resumed; when none moved, the clock jumps to the
|
|
19
|
+
* earliest wake-up and they are resumed again. Stops when the only runs left wait without a timeout (for a
|
|
20
|
+
* signal or an event). Returns how many resumes moved a run.
|
|
21
|
+
*/
|
|
22
|
+
async runUntilIdle(options: { max?: number; fastForward?: boolean } = {}): Promise<number> {
|
|
23
|
+
const max = options.max ?? 1000
|
|
24
|
+
let moved = 0
|
|
25
|
+
for (let round = 0; ; round++) {
|
|
26
|
+
if (round >= max) throw new Error(`runUntilIdle(): still busy after ${max} rounds; does a workflow loop?`)
|
|
27
|
+
const runs = await this.unfinished()
|
|
28
|
+
let progressed = false
|
|
29
|
+
for (const run of runs) {
|
|
30
|
+
const before = await this.fingerprint(run.id)
|
|
31
|
+
await this.workflows.resume(run.id)
|
|
32
|
+
if ((await this.fingerprint(run.id)) !== before) {
|
|
33
|
+
progressed = true
|
|
34
|
+
moved++
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (progressed) continue
|
|
38
|
+
const next = (await this.unfinished())
|
|
39
|
+
.map((r) => r.wakeAt?.getTime())
|
|
40
|
+
.filter((t): t is number => t !== undefined)
|
|
41
|
+
.sort((a, b) => a - b)[0]
|
|
42
|
+
const clock = this.app.resolve(Clock)
|
|
43
|
+
if (next === undefined || options.fastForward === false || !(clock instanceof FakeClock)) return moved
|
|
44
|
+
if (next > clock.now().getTime()) clock.travelTo(next)
|
|
45
|
+
else return moved // due but did not move: nothing more will happen
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
find(runId: string): Promise<WorkflowRun | null> {
|
|
50
|
+
return this.workflows.find(runId)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
journal(runId: string): Promise<JournalEntry[]> {
|
|
54
|
+
return this.workflows.store.journal(runId)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
signal(runId: string, name: string, data?: unknown): Promise<void> {
|
|
58
|
+
return this.workflows.signal(runId, name, data)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Throw unless the run has this status (and, when given, this output). */
|
|
62
|
+
async assertStatus(runId: string, status: WorkflowRun['status'], output?: unknown): Promise<void> {
|
|
63
|
+
const run = await this.find(runId)
|
|
64
|
+
if (!run) throw new Error(`No workflow run ${runId}`)
|
|
65
|
+
const outputMatches = output === undefined || JSON.stringify(run.output) === JSON.stringify(output)
|
|
66
|
+
if (run.status !== status || !outputMatches)
|
|
67
|
+
throw new Error(
|
|
68
|
+
`Expected run ${runId} to be ${status}${output === undefined ? '' : ` with ${JSON.stringify(output)}`}, ` +
|
|
69
|
+
`got ${run.status}${run.error ? ` (${run.error.message})` : ''} with ${JSON.stringify(run.output)}`,
|
|
70
|
+
)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
private async unfinished(): Promise<WorkflowRun[]> {
|
|
74
|
+
const all = await this.workflows.list({ limit: 10_000 })
|
|
75
|
+
return all.filter((r) => !FINISHED.includes(r.status))
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
private async fingerprint(runId: string): Promise<string> {
|
|
79
|
+
const run = await this.workflows.find(runId)
|
|
80
|
+
const journal = await this.workflows.store.journal(runId)
|
|
81
|
+
return JSON.stringify([run?.status, run?.wakeAt, journal.map((e) => [e.seq, e.status, e.attempts])])
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** For `@cslug/testing`: `t.workflows`. */
|
|
86
|
+
export function installWorkflowFake(app: Application): WorkflowFake {
|
|
87
|
+
return new WorkflowFake(app)
|
|
88
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @cslug/workflow: durable workflows on PostgreSQL and the queue. Journaled steps with retries, durable sleeps,
|
|
3
|
+
* waits for events and signals, idempotent starts (guide 25).
|
|
4
|
+
*/
|
|
5
|
+
export {
|
|
6
|
+
WorkflowCancelCommand,
|
|
7
|
+
WorkflowListCommand,
|
|
8
|
+
WorkflowPruneCommand,
|
|
9
|
+
WorkflowRetryCommand,
|
|
10
|
+
WorkflowShowCommand,
|
|
11
|
+
workflowCommands,
|
|
12
|
+
} from './commands'
|
|
13
|
+
export { type StepOptions, WorkflowContext } from './context'
|
|
14
|
+
export {
|
|
15
|
+
Cancellation,
|
|
16
|
+
CompensationFailedError,
|
|
17
|
+
isSuspension,
|
|
18
|
+
NondeterminismError,
|
|
19
|
+
StepFailedError,
|
|
20
|
+
Suspension,
|
|
21
|
+
} from './errors'
|
|
22
|
+
export { installWorkflowFake, WorkflowFake } from './fake'
|
|
23
|
+
export type { Json } from './json'
|
|
24
|
+
export { WORKFLOW_MIGRATIONS, WorkflowProvider } from './provider'
|
|
25
|
+
export { FINISHED, type JournalEntry, type RunStatus, type WorkflowRun, WorkflowStore } from './store'
|
|
26
|
+
export {
|
|
27
|
+
findWorkflow,
|
|
28
|
+
type InputOf,
|
|
29
|
+
isWorkflowClass,
|
|
30
|
+
registerWorkflow,
|
|
31
|
+
type StartedRun,
|
|
32
|
+
type StartOptions,
|
|
33
|
+
Workflow,
|
|
34
|
+
type WorkflowClass,
|
|
35
|
+
type WorkflowSettings,
|
|
36
|
+
workflowName,
|
|
37
|
+
} from './workflow'
|
|
38
|
+
export { type WorkflowAudit, WorkflowResumeJob, Workflows } from './workflows'
|
package/src/json.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** What a value becomes once stored as JSON: bigint and Date as strings, functions and undefined dropped. */
|
|
2
|
+
export type Json<T> = T extends bigint | Date
|
|
3
|
+
? string
|
|
4
|
+
: T extends (infer U)[]
|
|
5
|
+
? Json<U>[]
|
|
6
|
+
: T extends object
|
|
7
|
+
? { [K in keyof T]: Json<T[K]> }
|
|
8
|
+
: T
|
|
9
|
+
|
|
10
|
+
/** A JSON-safe copy (bigint → string); undefined → null. */
|
|
11
|
+
export function toJson<T>(value: T): Json<T> {
|
|
12
|
+
if (value === undefined) return null as Json<T>
|
|
13
|
+
return JSON.parse(JSON.stringify(value, (_k, v) => (typeof v === 'bigint' ? v.toString() : v))) as Json<T>
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** An error as JSON: name, message and code. */
|
|
17
|
+
export function errorJson(error: unknown): { name: string; message: string; code?: string } {
|
|
18
|
+
const e = error instanceof Error ? error : new Error(String(error))
|
|
19
|
+
const code = (e as { code?: unknown }).code
|
|
20
|
+
return { name: e.name, message: e.message, ...(typeof code === 'string' ? { code } : {}) }
|
|
21
|
+
}
|
package/src/provider.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { existsSync, readdirSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { ServiceProvider, type Token } from '@cslug/core'
|
|
4
|
+
import { addMigrations, DatabaseProvider } from '@cslug/database'
|
|
5
|
+
import { QueueProvider, registerJob } from '@cslug/queue'
|
|
6
|
+
import { workflowCommands } from './commands'
|
|
7
|
+
import { isWorkflowClass, registeredWorkflows, starter, workflowName } from './workflow'
|
|
8
|
+
import { WorkflowResumeJob, Workflows } from './workflows'
|
|
9
|
+
|
|
10
|
+
/** @cslug/security, as far as workflows use it (loaded at runtime: it is optional). */
|
|
11
|
+
type SecurityModule = {
|
|
12
|
+
Audit: Token<{
|
|
13
|
+
store?: unknown
|
|
14
|
+
record(action: string, options: { subject: { type: string; id: string }; data: Record<string, unknown> }): unknown
|
|
15
|
+
}>
|
|
16
|
+
}
|
|
17
|
+
const importOptional = <M>(name: string): Promise<M> => import(name)
|
|
18
|
+
|
|
19
|
+
/** The workflows migration: `cslug_workflow_runs`, `cslug_workflow_steps`, `cslug_workflow_signals`. */
|
|
20
|
+
export const WORKFLOW_MIGRATIONS = join(import.meta.dir, '../migrations')
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Binds `Workflows`, registers the migration and the resume job, and loads `app/workflows/` (so every process
|
|
24
|
+
* knows every workflow and watches the events they wait for).
|
|
25
|
+
*/
|
|
26
|
+
export class WorkflowProvider extends ServiceProvider {
|
|
27
|
+
static dependsOn = [DatabaseProvider, QueueProvider]
|
|
28
|
+
|
|
29
|
+
register() {
|
|
30
|
+
addMigrations(WORKFLOW_MIGRATIONS)
|
|
31
|
+
registerJob(WorkflowResumeJob)
|
|
32
|
+
this.app.singleton(Workflows, () => new Workflows(this.app))
|
|
33
|
+
this.commands(workflowCommands)
|
|
34
|
+
this.describe('workflows', () =>
|
|
35
|
+
registeredWorkflows().map((w) => ({
|
|
36
|
+
name: workflowName(w),
|
|
37
|
+
class: w.name,
|
|
38
|
+
waitsFor: (w.waitsFor ?? []).map((e) => e.eventName).join(', '),
|
|
39
|
+
})),
|
|
40
|
+
)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async boot() {
|
|
44
|
+
const workflows = this.app.resolve(Workflows)
|
|
45
|
+
starter.start = (workflow, input, options) => this.app.resolve(Workflows).start(workflow, input, options)
|
|
46
|
+
const dir = join(this.app.rootDir, 'app/workflows')
|
|
47
|
+
if (existsSync(dir)) {
|
|
48
|
+
const files = (readdirSync(dir, { recursive: true }) as string[])
|
|
49
|
+
.filter((f) => f.endsWith('.ts') && !f.endsWith('.test.ts') && !f.endsWith('.d.ts'))
|
|
50
|
+
.sort()
|
|
51
|
+
for (const file of files)
|
|
52
|
+
for (const value of Object.values((await import(join(dir, file))) as Record<string, unknown>))
|
|
53
|
+
if (isWorkflowClass(value)) workflows.register(value)
|
|
54
|
+
}
|
|
55
|
+
for (const workflow of registeredWorkflows()) workflows.register(workflow)
|
|
56
|
+
await this.auditWith(workflows)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** With @cslug/security: runs' starts and ends go to its audit log (once it has a store). */
|
|
60
|
+
private async auditWith(workflows: Workflows) {
|
|
61
|
+
const security = await importOptional<SecurityModule>('@cslug/security').catch(() => undefined)
|
|
62
|
+
if (!security || !this.app.has(security.Audit)) return
|
|
63
|
+
const audit = this.app.resolve(security.Audit)
|
|
64
|
+
workflows.audit = { record: (action, options) => (audit.store ? audit.record(action, options) : undefined) }
|
|
65
|
+
}
|
|
66
|
+
}
|
package/src/store.ts
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { type Database, sql } from '@cslug/database'
|
|
2
|
+
|
|
3
|
+
export type RunStatus =
|
|
4
|
+
| 'pending'
|
|
5
|
+
| 'running'
|
|
6
|
+
| 'sleeping'
|
|
7
|
+
| 'waiting'
|
|
8
|
+
/** Undoing finished steps after a failure (a compensation may be waiting for its retry). */
|
|
9
|
+
| 'compensating'
|
|
10
|
+
/** Cancelled, not yet stopped: its next wake-up undoes finished steps, then it is `cancelled`. */
|
|
11
|
+
| 'cancelling'
|
|
12
|
+
| 'completed'
|
|
13
|
+
| 'failed'
|
|
14
|
+
| 'cancelled'
|
|
15
|
+
/** Failed, and every compensation ran. */
|
|
16
|
+
| 'compensated'
|
|
17
|
+
/** Failed (or cancelled), and a compensation failed on its last try. */
|
|
18
|
+
| 'compensation_failed'
|
|
19
|
+
export const FINISHED: readonly RunStatus[] = ['completed', 'failed', 'cancelled', 'compensated', 'compensation_failed']
|
|
20
|
+
|
|
21
|
+
/** A workflow run as stored (`workflows.find(id)`). */
|
|
22
|
+
export type WorkflowRun = {
|
|
23
|
+
id: string
|
|
24
|
+
workflow: string
|
|
25
|
+
status: RunStatus
|
|
26
|
+
input: unknown
|
|
27
|
+
output: unknown
|
|
28
|
+
error: { name: string; message: string; code?: string } | null
|
|
29
|
+
/** What a waiting run waits for: `signal:<name>` or `event:<event name>`. */
|
|
30
|
+
waitingFor: string | null
|
|
31
|
+
waitingMatch: Record<string, unknown> | null
|
|
32
|
+
wakeAt: Date | null
|
|
33
|
+
createdAt: Date
|
|
34
|
+
updatedAt: Date
|
|
35
|
+
finishedAt: Date | null
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** One journal entry: a `ctx` call of a run, by position. */
|
|
39
|
+
export type JournalEntry = {
|
|
40
|
+
seq: number
|
|
41
|
+
name: string
|
|
42
|
+
kind: 'step' | 'sleep' | 'wait' | 'now' | 'uuid' | 'compensate'
|
|
43
|
+
status: 'completed' | 'pending' | 'retrying' | 'failed'
|
|
44
|
+
result: unknown
|
|
45
|
+
error: unknown
|
|
46
|
+
attempts: number
|
|
47
|
+
wakeAt: Date | null
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const json = (value: unknown) => (value === undefined || value === null ? null : sql.json(value))
|
|
51
|
+
|
|
52
|
+
/** The SQL behind workflows (tables from migration 000800). Every call uses the ambient transaction. */
|
|
53
|
+
export class WorkflowStore {
|
|
54
|
+
constructor(private readonly db: () => Database) {}
|
|
55
|
+
|
|
56
|
+
/** Insert a run; false when the id exists already. */
|
|
57
|
+
async insert(id: string, workflow: string, input: unknown): Promise<boolean> {
|
|
58
|
+
const n = await this.db().exec(sql`insert into cslug_workflow_runs (id, workflow, input)
|
|
59
|
+
values (${id}, ${workflow}, ${json(input)}) on conflict (id) do nothing`)
|
|
60
|
+
return n > 0
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
find(id: string): Promise<WorkflowRun | null> {
|
|
64
|
+
return this.db().maybeOne<WorkflowRun>(sql`select * from cslug_workflow_runs where id = ${id}`)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async setStatus(id: string, status: RunStatus): Promise<void> {
|
|
68
|
+
await this.db().exec(sql`update cslug_workflow_runs set status = ${status}, updated_at = now() where id = ${id}`)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async suspend(
|
|
72
|
+
id: string,
|
|
73
|
+
s: { status: RunStatus; wakeAt: Date | null; waitingFor?: string; match?: Record<string, unknown> },
|
|
74
|
+
): Promise<void> {
|
|
75
|
+
await this.db().exec(sql`update cslug_workflow_runs set status = ${s.status}, wake_at = ${s.wakeAt},
|
|
76
|
+
waiting_for = ${s.waitingFor ?? null}, waiting_match = ${json(s.match)}, updated_at = now() where id = ${id}`)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async finish(id: string, status: RunStatus, values: { output?: unknown; error?: unknown }): Promise<void> {
|
|
80
|
+
await this.db().exec(sql`update cslug_workflow_runs set status = ${status}, output = ${json(values.output)},
|
|
81
|
+
error = ${json(values.error)}, wake_at = null, waiting_for = null, waiting_match = null, updated_at = now(),
|
|
82
|
+
finished_at = now() where id = ${id}`)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Mark a run that has not finished `cancelling`; false when it had finished or was being cancelled. */
|
|
86
|
+
async cancel(id: string): Promise<boolean> {
|
|
87
|
+
const n = await this.db().exec(sql`update cslug_workflow_runs set status = 'cancelling', updated_at = now()
|
|
88
|
+
where id = ${id} and status not in ('completed', 'failed', 'cancelled', 'compensated', 'compensation_failed',
|
|
89
|
+
'cancelling')`)
|
|
90
|
+
return n > 0
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Runs, newest first, filtered by status and workflow name. */
|
|
94
|
+
list(filter: { status?: RunStatus; workflow?: string; limit?: number } = {}): Promise<WorkflowRun[]> {
|
|
95
|
+
const where = [
|
|
96
|
+
filter.status ? sql`status = ${filter.status}` : sql`true`,
|
|
97
|
+
filter.workflow ? sql`workflow = ${filter.workflow}` : sql`true`,
|
|
98
|
+
]
|
|
99
|
+
return this.db().many<WorkflowRun>(sql`select * from cslug_workflow_runs where ${where[0]} and ${where[1]}
|
|
100
|
+
order by created_at desc, id desc limit ${filter.limit ?? 50}`)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Make a failed run runnable again: its failed journal entries retry at once with fresh attempts; the run is
|
|
105
|
+
* `pending` (`compensating` after a failed compensation). False unless it was `failed` or `compensation_failed`.
|
|
106
|
+
*/
|
|
107
|
+
async retry(id: string): Promise<boolean> {
|
|
108
|
+
const run = await this.find(id)
|
|
109
|
+
if (!run || (run.status !== 'failed' && run.status !== 'compensation_failed')) return false
|
|
110
|
+
await this.db().exec(sql`update cslug_workflow_steps set status = 'retrying', attempts = 0, wake_at = null,
|
|
111
|
+
updated_at = now() where run_id = ${id} and status = 'failed'`)
|
|
112
|
+
const status: RunStatus = run.status === 'failed' ? 'pending' : 'compensating'
|
|
113
|
+
await this.db().exec(sql`update cslug_workflow_runs set status = ${status}, error = null, finished_at = null,
|
|
114
|
+
updated_at = now() where id = ${id}`)
|
|
115
|
+
return true
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Delete finished runs (and their journals and signals) that finished before `before`. */
|
|
119
|
+
prune(before: Date): Promise<number> {
|
|
120
|
+
return this.db().exec(sql`delete from cslug_workflow_runs
|
|
121
|
+
where status in ('completed', 'failed', 'cancelled', 'compensated', 'compensation_failed')
|
|
122
|
+
and finished_at < ${before}`)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async journal(runId: string): Promise<JournalEntry[]> {
|
|
126
|
+
return this.db().many<JournalEntry>(sql`select seq, name, kind, status, result, error, attempts, wake_at
|
|
127
|
+
from cslug_workflow_steps where run_id = ${runId} order by seq`)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async save(runId: string, e: Omit<JournalEntry, 'result' | 'error'> & { result?: unknown; error?: unknown }) {
|
|
131
|
+
await this.db().exec(sql`insert into cslug_workflow_steps
|
|
132
|
+
(run_id, seq, name, kind, status, result, error, attempts, wake_at)
|
|
133
|
+
values (${runId}, ${e.seq}, ${e.name}, ${e.kind}, ${e.status}, ${json(e.result)}, ${json(e.error)},
|
|
134
|
+
${e.attempts}, ${e.wakeAt})
|
|
135
|
+
on conflict (run_id, seq) do update set status = excluded.status, result = excluded.result,
|
|
136
|
+
error = excluded.error, attempts = excluded.attempts, wake_at = excluded.wake_at, updated_at = now()`)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async addSignal(runId: string, name: string, data: unknown): Promise<void> {
|
|
140
|
+
await this.db().exec(sql`insert into cslug_workflow_signals (id, run_id, name, data)
|
|
141
|
+
values (${Bun.randomUUIDv7()}, ${runId}, ${name}, ${json(data)})`)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The oldest signal `name` not yet taken by the run, marked taken (in the caller's transaction). */
|
|
145
|
+
async takeSignal(runId: string, name: string): Promise<{ data: unknown } | null> {
|
|
146
|
+
const row = await this.db().maybeOne<{ id: string; data: unknown }>(sql`select id, data
|
|
147
|
+
from cslug_workflow_signals where run_id = ${runId} and name = ${name} and consumed_at is null
|
|
148
|
+
order by created_at, id limit 1 for update skip locked`)
|
|
149
|
+
if (!row) return null
|
|
150
|
+
await this.db().exec(sql`update cslug_workflow_signals set consumed_at = now() where id = ${row.id}`)
|
|
151
|
+
return { data: row.data }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Runs waiting for `channel` whose match is contained in `payload`. */
|
|
155
|
+
async waitingFor(channel: string, payload: unknown): Promise<string[]> {
|
|
156
|
+
const rows = await this.db().many<{ id: string }>(sql`select id from cslug_workflow_runs
|
|
157
|
+
where status = 'waiting' and waiting_for = ${channel}
|
|
158
|
+
and (waiting_match is null or waiting_match <@ ${json(payload ?? {})})`)
|
|
159
|
+
return rows.map((r) => r.id)
|
|
160
|
+
}
|
|
161
|
+
}
|
package/src/workflow.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { type AnyEventClass, CslugError } from '@cslug/core'
|
|
2
|
+
import type { WorkflowContext } from './context'
|
|
3
|
+
|
|
4
|
+
/** The static settings a workflow class may declare (not declared on `Workflow`, so no `override` is needed). */
|
|
5
|
+
export type WorkflowSettings = {
|
|
6
|
+
/** Stored with each run (default: the class name). Keep it when you rename the class while runs are in flight. */
|
|
7
|
+
readonly workflowName?: string
|
|
8
|
+
/** The events `ctx.waitFor()` may wait for: only those are watched. */
|
|
9
|
+
readonly waitsFor?: readonly AnyEventClass[]
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** A workflow class. */
|
|
13
|
+
export type WorkflowClass<I = unknown, O = unknown> = (abstract new (
|
|
14
|
+
...args: never[]
|
|
15
|
+
) => Workflow<I, O>) &
|
|
16
|
+
WorkflowSettings
|
|
17
|
+
|
|
18
|
+
/** The input type of a workflow class (the second parameter of its `run`). */
|
|
19
|
+
export type InputOf<W> = W extends abstract new (...args: never[]) => Workflow<infer I, unknown> ? I : never
|
|
20
|
+
|
|
21
|
+
export type StartOptions = {
|
|
22
|
+
/** The run's id (default: a UUIDv7). Starting an id that exists returns that run instead of a new one. */
|
|
23
|
+
id?: string
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** What `start()` returns: the run's id, and whether this call created it. */
|
|
27
|
+
export type StartedRun = { id: string; created: boolean }
|
|
28
|
+
|
|
29
|
+
/** Set by `WorkflowProvider`: how `Workflow.start()` reaches the app's `Workflows`. */
|
|
30
|
+
export const starter: {
|
|
31
|
+
start?: (workflow: WorkflowClass, input: unknown, options: StartOptions) => Promise<StartedRun>
|
|
32
|
+
} = {}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* A durable workflow: an `@inject()` class with `run(ctx, input)`, replayed from its journal each time the run
|
|
36
|
+
* wakes up (guide 25). Optional statics: `workflowName`, `waitsFor`.
|
|
37
|
+
*
|
|
38
|
+
* ```ts
|
|
39
|
+
* @inject(PaymentGateway)
|
|
40
|
+
* export class BookingDepositWorkflow extends Workflow<{ bookingId: string }> {
|
|
41
|
+
* static waitsFor = [DepositPaid]
|
|
42
|
+
* constructor(private gateway: PaymentGateway) { super() }
|
|
43
|
+
* async run(ctx: WorkflowContext, { bookingId }: { bookingId: string }) { … }
|
|
44
|
+
* }
|
|
45
|
+
* await BookingDepositWorkflow.start({ bookingId }, { id: `deposit:${bookingId}` })
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
export abstract class Workflow<I = unknown, O = unknown> {
|
|
49
|
+
abstract run(ctx: WorkflowContext, input: I): Promise<O>
|
|
50
|
+
|
|
51
|
+
/** Start a run (after the current transaction commits; a rollback leaves no run). */
|
|
52
|
+
static start<W extends WorkflowClass<never>>(this: W, input: InputOf<W>, options: StartOptions = {}) {
|
|
53
|
+
if (!starter.start) throw new CslugError('workflow.no_provider', 'Workflows need WorkflowProvider')
|
|
54
|
+
// biome-ignore lint/complexity/noThisInStatic: `this` is the concrete workflow class
|
|
55
|
+
return starter.start(this as unknown as WorkflowClass, input, options)
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// ── the registry: workflow name → class, for workers ─────────────────────────────────────────────────
|
|
60
|
+
|
|
61
|
+
const registry = new Map<string, WorkflowClass>()
|
|
62
|
+
|
|
63
|
+
export const workflowName = (workflow: WorkflowClass): string => workflow.workflowName ?? workflow.name
|
|
64
|
+
|
|
65
|
+
/** Remember a workflow class by name (start and discovery call this). Two classes with one name is an error. */
|
|
66
|
+
export function registerWorkflow(workflow: WorkflowClass): void {
|
|
67
|
+
const name = workflowName(workflow)
|
|
68
|
+
const known = registry.get(name)
|
|
69
|
+
if (known && known !== workflow)
|
|
70
|
+
throw new CslugError('workflow.duplicate', `Two workflow classes are named ${name}: set static workflowName`)
|
|
71
|
+
registry.set(name, workflow)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export const findWorkflow = (name: string): WorkflowClass | undefined => registry.get(name)
|
|
75
|
+
export const registeredWorkflows = (): WorkflowClass[] => [...registry.values()]
|
|
76
|
+
|
|
77
|
+
export const isWorkflowClass = (value: unknown): value is WorkflowClass =>
|
|
78
|
+
typeof value === 'function' && value.prototype instanceof Workflow
|
package/src/workflows.ts
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type AnyEventClass,
|
|
3
|
+
type Application,
|
|
4
|
+
Clock,
|
|
5
|
+
currentContext,
|
|
6
|
+
type Duration,
|
|
7
|
+
EventBus,
|
|
8
|
+
Logger,
|
|
9
|
+
NotFoundError,
|
|
10
|
+
resolve,
|
|
11
|
+
Tracer,
|
|
12
|
+
} from '@cslug/core'
|
|
13
|
+
import { Database } from '@cslug/database'
|
|
14
|
+
import { Job, Outbox } from '@cslug/queue'
|
|
15
|
+
import { WorkflowContext } from './context'
|
|
16
|
+
import { Cancellation, NondeterminismError, Suspension } from './errors'
|
|
17
|
+
import { errorJson, toJson } from './json'
|
|
18
|
+
import { FINISHED, type RunStatus, type WorkflowRun, WorkflowStore } from './store'
|
|
19
|
+
import {
|
|
20
|
+
findWorkflow,
|
|
21
|
+
registerWorkflow,
|
|
22
|
+
type StartedRun,
|
|
23
|
+
type StartOptions,
|
|
24
|
+
type WorkflowClass,
|
|
25
|
+
workflowName,
|
|
26
|
+
} from './workflow'
|
|
27
|
+
|
|
28
|
+
/** Wakes a run up: replays it from its journal (one at a time per run). */
|
|
29
|
+
export class WorkflowResumeJob extends Job<{ runId: string; wakeAt?: string }> {
|
|
30
|
+
static jobName = 'cslug.workflow.resume'
|
|
31
|
+
static tries = 5
|
|
32
|
+
static timeout = '1h'
|
|
33
|
+
|
|
34
|
+
async handle({ runId, wakeAt }: { runId: string; wakeAt?: string }) {
|
|
35
|
+
await resolve(Workflows).resume(runId, { wakeAt })
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Starts, resumes, signals, finds and cancels workflow runs (guide 25). Runs are rows in `cslug_workflow_runs`; their
|
|
41
|
+
* journals in `cslug_workflow_steps`.
|
|
42
|
+
*/
|
|
43
|
+
/** What `Workflows` needs of @cslug/security's `Audit` (set by `WorkflowProvider` when it is there). */
|
|
44
|
+
export type WorkflowAudit = {
|
|
45
|
+
record(action: string, options: { subject: { type: string; id: string }; data: Record<string, unknown> }): unknown
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export class Workflows {
|
|
49
|
+
readonly store: WorkflowStore
|
|
50
|
+
private readonly watched = new Set<AnyEventClass>()
|
|
51
|
+
/** With @cslug/security: starts and ends of runs go to its audit log. */
|
|
52
|
+
audit?: WorkflowAudit
|
|
53
|
+
|
|
54
|
+
constructor(private readonly app: Application) {
|
|
55
|
+
this.store = new WorkflowStore(() => app.resolve(Database))
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Start a run of `workflow` (idempotent by `id`); it begins after the current transaction commits. */
|
|
59
|
+
async start(workflow: WorkflowClass, input: unknown, options: StartOptions = {}): Promise<StartedRun> {
|
|
60
|
+
this.register(workflow)
|
|
61
|
+
const id = options.id ?? Bun.randomUUIDv7()
|
|
62
|
+
const created = await this.store.insert(id, workflowName(workflow), toJson(input))
|
|
63
|
+
if (created) {
|
|
64
|
+
await this.wake(id, undefined, true)
|
|
65
|
+
await this.audited(id, workflowName(workflow), 'started')
|
|
66
|
+
}
|
|
67
|
+
return { id, created }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Runs, newest first (`cslug workflow:list`). */
|
|
71
|
+
list(filter: { status?: RunStatus; workflow?: string; limit?: number } = {}): Promise<WorkflowRun[]> {
|
|
72
|
+
return this.store.list(filter)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Run a `failed` or `compensation_failed` run again from where it failed (`cslug workflow:retry`): its failed
|
|
77
|
+
* step (or compensation) gets fresh attempts. False for any other run.
|
|
78
|
+
*/
|
|
79
|
+
async retry(runId: string): Promise<boolean> {
|
|
80
|
+
if (!(await this.store.retry(runId))) return false
|
|
81
|
+
await this.wake(runId)
|
|
82
|
+
return true
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Delete runs that finished more than `olderThan` ago, with their journals (`cslug workflow:prune`). */
|
|
86
|
+
prune(olderThan: Duration): Promise<number> {
|
|
87
|
+
return this.store.prune(this.app.resolve(Clock).subtract(olderThan))
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** An audit entry `workflow.<what>` (with @cslug/security); a failure to record is logged, not thrown. */
|
|
91
|
+
private async audited(runId: string, workflow: string, what: string): Promise<void> {
|
|
92
|
+
if (!this.audit) return
|
|
93
|
+
try {
|
|
94
|
+
await this.audit.record(`workflow.${what}`, { subject: { type: 'workflow_run', id: runId }, data: { workflow } })
|
|
95
|
+
} catch (error) {
|
|
96
|
+
this.app.resolve(Logger).error('workflow.audit_failed', { runId, error })
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
private async finish(
|
|
101
|
+
runId: string,
|
|
102
|
+
workflow: string,
|
|
103
|
+
status: RunStatus,
|
|
104
|
+
values: { output?: unknown; error?: unknown },
|
|
105
|
+
) {
|
|
106
|
+
await this.store.finish(runId, status, values)
|
|
107
|
+
await this.audited(runId, workflow, status)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Send a signal to a run: `ctx.waitForSignal(name)` returns `data`. Kept until the run asks for it. */
|
|
111
|
+
async signal(runId: string, name: string, data?: unknown): Promise<void> {
|
|
112
|
+
const run = await this.store.find(runId)
|
|
113
|
+
if (!run) throw new NotFoundError('workflow_run', runId)
|
|
114
|
+
if (FINISHED.includes(run.status)) return
|
|
115
|
+
await this.store.addSignal(runId, `signal:${name}`, toJson(data))
|
|
116
|
+
await this.wake(runId)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
find(runId: string): Promise<WorkflowRun | null> {
|
|
120
|
+
return this.store.find(runId)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Cancel a run that has not finished: it is `cancelling` until its next wake-up (queued now), which undoes its
|
|
125
|
+
* finished steps (their `compensate`) and ends it `cancelled`. False when it had finished or was being cancelled.
|
|
126
|
+
*/
|
|
127
|
+
async cancel(runId: string): Promise<boolean> {
|
|
128
|
+
if (!(await this.store.cancel(runId))) return false
|
|
129
|
+
await this.wake(runId)
|
|
130
|
+
return true
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Remember a workflow class, and watch the events it waits for. */
|
|
134
|
+
register(workflow: WorkflowClass): void {
|
|
135
|
+
registerWorkflow(workflow)
|
|
136
|
+
for (const event of workflow.waitsFor ?? []) this.watch(event)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Runs waiting for this event (and whose match the payload contains) get it, and wake up. */
|
|
140
|
+
private watch(event: AnyEventClass): void {
|
|
141
|
+
if (this.watched.has(event)) return
|
|
142
|
+
this.watched.add(event)
|
|
143
|
+
const channel = `event:${event.eventName}`
|
|
144
|
+
this.app.resolve(EventBus).on(event as never, async (payload: unknown) => {
|
|
145
|
+
const data = toJson(payload)
|
|
146
|
+
for (const runId of await this.store.waitingFor(channel, data)) {
|
|
147
|
+
await this.store.addSignal(runId, channel, data)
|
|
148
|
+
await this.wake(runId)
|
|
149
|
+
}
|
|
150
|
+
})
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Queue a resume (now, or at `at`); durable through the outbox when started inside a transaction. */
|
|
154
|
+
private async wake(runId: string, at?: Date, durable = false): Promise<void> {
|
|
155
|
+
const dispatch = WorkflowResumeJob.dispatch(at ? { runId, wakeAt: at.toISOString() } : { runId })
|
|
156
|
+
if (at) dispatch.at(at)
|
|
157
|
+
const tx = currentContext()?.tx
|
|
158
|
+
if (durable && tx && this.app.has(Outbox)) dispatch.durable()
|
|
159
|
+
await dispatch
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Replay a run from its journal until it finishes or suspends. One process at a time per run (advisory lock).
|
|
164
|
+
* `wakeAt`: the moment the job that called it was scheduled for.
|
|
165
|
+
*/
|
|
166
|
+
async resume(runId: string, options: { wakeAt?: string } = {}): Promise<void> {
|
|
167
|
+
const db = this.app.resolve(Database)
|
|
168
|
+
await db.advisoryLock(`cslug:workflow:${runId}`, async () => {
|
|
169
|
+
const run = await this.store.find(runId)
|
|
170
|
+
if (!run || FINISHED.includes(run.status)) return
|
|
171
|
+
const workflow = findWorkflow(run.workflow)
|
|
172
|
+
if (!workflow) {
|
|
173
|
+
await this.finish(runId, run.workflow, 'failed', {
|
|
174
|
+
error: { name: 'CslugError', code: 'workflow.unknown', message: `No workflow named ${run.workflow}` },
|
|
175
|
+
})
|
|
176
|
+
return
|
|
177
|
+
}
|
|
178
|
+
this.register(workflow)
|
|
179
|
+
const cancelling = run.status === 'cancelling'
|
|
180
|
+
if (!cancelling) await this.store.setStatus(runId, 'running')
|
|
181
|
+
const ctx = new WorkflowContext(
|
|
182
|
+
runId,
|
|
183
|
+
await this.store.journal(runId),
|
|
184
|
+
this.store,
|
|
185
|
+
db,
|
|
186
|
+
this.app.resolve(Clock),
|
|
187
|
+
cancelling,
|
|
188
|
+
this.app.resolve(Tracer),
|
|
189
|
+
)
|
|
190
|
+
const scope = currentContext()?.scope ?? this.app
|
|
191
|
+
const suspend = async (s: Suspension, status = s.status as RunStatus) => {
|
|
192
|
+
await this.store.suspend(runId, { ...s, status })
|
|
193
|
+
const at = s.wakeAt?.getTime()
|
|
194
|
+
// one job per suspension point; again if this job ran before its time (the queue's clock was ahead)
|
|
195
|
+
if (at !== undefined && (at !== run.wakeAt?.getTime() || options.wakeAt === s.wakeAt?.toISOString()))
|
|
196
|
+
await this.wake(runId, s.wakeAt as Date)
|
|
197
|
+
}
|
|
198
|
+
let failure: unknown
|
|
199
|
+
try {
|
|
200
|
+
const instance = scope.resolve(workflow as never) as { run(c: WorkflowContext, input: unknown): unknown }
|
|
201
|
+
const output = await instance.run(ctx, run.input)
|
|
202
|
+
if (!cancelling) return await this.finish(runId, run.workflow, 'completed', { output: toJson(output) })
|
|
203
|
+
} catch (error) {
|
|
204
|
+
if (error instanceof Suspension) return await suspend(error)
|
|
205
|
+
if (!(error instanceof Cancellation)) failure = error
|
|
206
|
+
}
|
|
207
|
+
// failed or cancelled: undo the finished steps (a saga); a nondeterministic run cannot be trusted to
|
|
208
|
+
if (failure !== undefined && !cancelling)
|
|
209
|
+
this.app.resolve(Logger).error('workflow.failed', { runId, workflow: run.workflow, error: failure })
|
|
210
|
+
const error = cancelling || failure === undefined ? undefined : errorJson(failure)
|
|
211
|
+
if (!ctx.hasCompensations || failure instanceof NondeterminismError)
|
|
212
|
+
return await this.finish(runId, run.workflow, cancelling ? 'cancelled' : 'failed', { error })
|
|
213
|
+
try {
|
|
214
|
+
if (!cancelling) await this.store.setStatus(runId, 'compensating')
|
|
215
|
+
await ctx.compensate()
|
|
216
|
+
await this.finish(runId, run.workflow, cancelling ? 'cancelled' : 'compensated', { error })
|
|
217
|
+
} catch (compensation) {
|
|
218
|
+
if (compensation instanceof Suspension)
|
|
219
|
+
return await suspend(compensation, cancelling ? 'cancelling' : 'compensating')
|
|
220
|
+
this.app.resolve(Logger).error('workflow.compensation_failed', { runId, error: compensation })
|
|
221
|
+
await this.finish(runId, run.workflow, 'compensation_failed', { error: errorJson(compensation) })
|
|
222
|
+
}
|
|
223
|
+
})
|
|
224
|
+
}
|
|
225
|
+
}
|