@accelerate/messaging 0.0.0-stage → 0.1.0-next.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 +25 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/modules/events-core/dist/index.d.ts +14 -0
- package/dist/modules/events-core/dist/index.js +3 -0
- package/dist/modules/events-core/dist/journal.d.ts +57 -0
- package/dist/modules/events-core/dist/journal.js +124 -0
- package/dist/modules/events-memory/dist/index.d.ts +3 -0
- package/dist/modules/events-memory/dist/index.js +7 -0
- package/dist/modules/events-memory/dist/journal.d.ts +37 -0
- package/dist/modules/events-memory/dist/journal.js +42 -0
- package/dist/modules/events-postgres/dist/index.d.ts +8 -0
- package/dist/modules/events-postgres/dist/index.js +4 -0
- package/dist/modules/events-postgres/dist/journal.d.ts +21 -0
- package/dist/modules/events-postgres/dist/journal.js +72 -0
- package/dist/modules/events-postgres/dist/schema.d.ts +1 -0
- package/dist/modules/events-postgres/dist/schema.js +1 -0
- package/dist/modules/events-redis/dist/index.d.ts +15 -0
- package/dist/modules/events-redis/dist/index.js +15 -0
- package/dist/modules/events-redis/dist/journal.d.ts +25 -0
- package/dist/modules/events-redis/dist/journal.js +45 -0
- package/dist/modules/jobs-core/dist/index.d.ts +21 -0
- package/dist/modules/jobs-core/dist/index.js +2 -0
- package/dist/modules/jobs-postgres/dist/index.d.ts +20 -0
- package/dist/modules/jobs-postgres/dist/index.js +123 -0
- package/dist/modules/jobs-postgres/dist/testing.d.ts +23 -0
- package/dist/modules/jobs-postgres/dist/testing.js +62 -0
- package/dist/modules/outbox-core/dist/index.d.ts +32 -0
- package/dist/modules/outbox-core/dist/index.js +34 -0
- package/dist/modules/outbox-postgres/dist/index.d.ts +13 -0
- package/dist/modules/outbox-postgres/dist/index.js +104 -0
- package/dist/modules/scheduler-core/dist/durable.d.ts +52 -0
- package/dist/modules/scheduler-core/dist/durable.js +153 -0
- package/dist/modules/scheduler-core/dist/index.d.ts +18 -0
- package/dist/modules/scheduler-core/dist/index.js +29 -0
- package/dist/modules/scheduler-postgres/dist/index.d.ts +19 -0
- package/dist/modules/scheduler-postgres/dist/index.js +97 -0
- package/dist/modules/workflows-core/dist/definition.d.ts +58 -0
- package/dist/modules/workflows-core/dist/definition.js +105 -0
- package/dist/modules/workflows-core/dist/durable.d.ts +60 -0
- package/dist/modules/workflows-core/dist/durable.js +300 -0
- package/dist/modules/workflows-core/dist/index.d.ts +19 -0
- package/dist/modules/workflows-core/dist/index.js +13 -0
- package/dist/modules/workflows-memory/dist/index.d.ts +2 -0
- package/dist/modules/workflows-memory/dist/index.js +32 -0
- package/dist/modules/workflows-postgres/dist/index.d.ts +5 -0
- package/dist/modules/workflows-postgres/dist/index.js +49 -0
- package/package.json +116 -4
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Database, Transaction } from "@accelerate/data/core";
|
|
2
|
+
import type { Migration } from "@accelerate/data/migrations";
|
|
3
|
+
import { type ScheduleDefinition, type ScheduleRun, type ScheduleState } from "../../scheduler-core/dist/index.js";
|
|
4
|
+
export declare const schedulerMigration: Migration;
|
|
5
|
+
export interface ScheduleHistoryEntry {
|
|
6
|
+
scheduledAt: number;
|
|
7
|
+
recordedAt: number;
|
|
8
|
+
runId: string | null;
|
|
9
|
+
skippedBefore: number | null;
|
|
10
|
+
}
|
|
11
|
+
/** Each tick owns at most one due schedule until the transaction commits. */
|
|
12
|
+
export declare function createPostgresScheduler(db: Database, writeRun: (tx: Transaction, run: ScheduleRun) => Promise<void>): {
|
|
13
|
+
inspect: (id: string) => Promise<ScheduleState | null>;
|
|
14
|
+
register(definition: ScheduleDefinition): Promise<void>;
|
|
15
|
+
control(id: string, action: "pause" | "resume" | "cancel"): Promise<boolean>;
|
|
16
|
+
upcoming(id: string, limit?: number): Promise<number[]>;
|
|
17
|
+
history(id: string, after?: number, limit?: number): Promise<ScheduleHistoryEntry[]>;
|
|
18
|
+
tick(): Promise<boolean>;
|
|
19
|
+
};
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { compileSchedule, decideSchedule, upcoming, } from "../../scheduler-core/dist/index.js";
|
|
2
|
+
export const schedulerMigration = {
|
|
3
|
+
id: "accelerate-scheduler/1",
|
|
4
|
+
statements: [
|
|
5
|
+
"CREATE TABLE accelerate_schedules (id text PRIMARY KEY, definition jsonb NOT NULL, status text NOT NULL CHECK (status IN ('active','paused','cancelled','completed')), next_at bigint)",
|
|
6
|
+
"CREATE INDEX accelerate_schedules_due ON accelerate_schedules(next_at,id) WHERE status='active'",
|
|
7
|
+
"CREATE TABLE accelerate_schedule_history (schedule_id text NOT NULL REFERENCES accelerate_schedules(id), slot bigint NOT NULL, recorded_at bigint NOT NULL, run_id text UNIQUE, skipped_before bigint, PRIMARY KEY(schedule_id,slot), CHECK ((run_id IS NULL) <> (skipped_before IS NULL)))",
|
|
8
|
+
],
|
|
9
|
+
};
|
|
10
|
+
function state(row) {
|
|
11
|
+
return {
|
|
12
|
+
definition: row.definition,
|
|
13
|
+
status: row.status,
|
|
14
|
+
nextAt: row.next_at === null ? null : Number(row.next_at),
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
/** Each tick owns at most one due schedule until the transaction commits. */
|
|
18
|
+
export function createPostgresScheduler(db, writeRun) {
|
|
19
|
+
async function inspect(id) {
|
|
20
|
+
const r = await db.query("SELECT definition,status,next_at FROM accelerate_schedules WHERE id=$1", [id]);
|
|
21
|
+
return r.rows.length ? state(r.rows[0]) : null;
|
|
22
|
+
}
|
|
23
|
+
return {
|
|
24
|
+
inspect,
|
|
25
|
+
async register(definition) {
|
|
26
|
+
const next = compileSchedule(definition).atOrAfter(definition.startAt);
|
|
27
|
+
const json = JSON.stringify(definition);
|
|
28
|
+
await db.transaction(async (tx) => {
|
|
29
|
+
const inserted = await tx.query("INSERT INTO accelerate_schedules(id,definition,status,next_at) VALUES ($1,$2::jsonb,$3,$4) ON CONFLICT (id) DO NOTHING", [definition.id, json, next === null ? "completed" : "active", next]);
|
|
30
|
+
if (!inserted.rowCount) {
|
|
31
|
+
const same = await tx.query("SELECT id FROM accelerate_schedules WHERE id=$1 AND definition=$2::jsonb", [definition.id, json]);
|
|
32
|
+
if (!same.rowCount)
|
|
33
|
+
throw new Error("Conflicting schedule definition");
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
},
|
|
37
|
+
async control(id, action) {
|
|
38
|
+
const transitions = {
|
|
39
|
+
pause: ["paused", ["active"]],
|
|
40
|
+
resume: ["active", ["paused"]],
|
|
41
|
+
cancel: ["cancelled", ["active", "paused"]],
|
|
42
|
+
};
|
|
43
|
+
if (!Object.hasOwn(transitions, action))
|
|
44
|
+
throw new TypeError("Invalid schedule action");
|
|
45
|
+
const [to, from] = transitions[action];
|
|
46
|
+
const r = await db.query("UPDATE accelerate_schedules SET status=$2 WHERE id=$1 AND status=ANY($3::text[])", [id, to, from]);
|
|
47
|
+
return r.rowCount === 1;
|
|
48
|
+
},
|
|
49
|
+
async upcoming(id, limit = 10) {
|
|
50
|
+
const row = await inspect(id);
|
|
51
|
+
return row?.status === "active" && row.nextAt !== null
|
|
52
|
+
? upcoming(row.definition, row.nextAt, limit)
|
|
53
|
+
: [];
|
|
54
|
+
},
|
|
55
|
+
async history(id, after = -1, limit = 100) {
|
|
56
|
+
if (!Number.isSafeInteger(after) ||
|
|
57
|
+
after < -1 ||
|
|
58
|
+
!Number.isInteger(limit) ||
|
|
59
|
+
limit < 1 ||
|
|
60
|
+
limit > 1000)
|
|
61
|
+
throw new RangeError("Invalid history page");
|
|
62
|
+
const r = await db.query("SELECT slot,recorded_at,run_id,skipped_before FROM accelerate_schedule_history WHERE schedule_id=$1 AND slot>$2 ORDER BY slot LIMIT $3", [id, after, limit]);
|
|
63
|
+
return r.rows.map((row) => ({
|
|
64
|
+
scheduledAt: Number(row.slot),
|
|
65
|
+
recordedAt: Number(row.recorded_at),
|
|
66
|
+
runId: row.run_id,
|
|
67
|
+
skippedBefore: row.skipped_before === null ? null : Number(row.skipped_before),
|
|
68
|
+
}));
|
|
69
|
+
},
|
|
70
|
+
async tick() {
|
|
71
|
+
return db.transaction(async (tx) => {
|
|
72
|
+
const result = await tx.query(`WITH clock AS (SELECT floor(extract(epoch FROM statement_timestamp())*1000)::bigint AS now_ms)
|
|
73
|
+
SELECT definition,status,next_at,now_ms FROM accelerate_schedules,clock
|
|
74
|
+
WHERE status='active' AND next_at<=now_ms ORDER BY next_at,id LIMIT 1 FOR UPDATE OF accelerate_schedules SKIP LOCKED`);
|
|
75
|
+
if (!result.rows.length)
|
|
76
|
+
return false;
|
|
77
|
+
const row = result.rows[0], current = state(row);
|
|
78
|
+
const decision = decideSchedule(current, Number(row.now_ms));
|
|
79
|
+
if (decision.run)
|
|
80
|
+
await writeRun(tx, decision.run);
|
|
81
|
+
await tx.query("INSERT INTO accelerate_schedule_history(schedule_id,slot,recorded_at,run_id,skipped_before) VALUES ($1,$2,$3,$4,$5)", [
|
|
82
|
+
current.definition.id,
|
|
83
|
+
current.nextAt,
|
|
84
|
+
row.now_ms,
|
|
85
|
+
decision.run?.id ?? null,
|
|
86
|
+
decision.skippedBefore ?? null,
|
|
87
|
+
]);
|
|
88
|
+
await tx.query("UPDATE accelerate_schedules SET next_at=$2,status=$3 WHERE id=$1", [
|
|
89
|
+
current.definition.id,
|
|
90
|
+
decision.nextAt,
|
|
91
|
+
decision.nextAt === null ? "completed" : "active",
|
|
92
|
+
]);
|
|
93
|
+
return true;
|
|
94
|
+
});
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { Json } from "@accelerate/data/idempotency";
|
|
2
|
+
export type { Json } from "@accelerate/data/idempotency";
|
|
3
|
+
export type Step = {
|
|
4
|
+
id: string;
|
|
5
|
+
} & ({
|
|
6
|
+
kind: "task";
|
|
7
|
+
handler: string;
|
|
8
|
+
compensate?: string;
|
|
9
|
+
attempts?: number;
|
|
10
|
+
retryMs?: number;
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
when?: {
|
|
13
|
+
field: string;
|
|
14
|
+
equals: Json;
|
|
15
|
+
};
|
|
16
|
+
} | {
|
|
17
|
+
kind: "wait";
|
|
18
|
+
delayMs: number;
|
|
19
|
+
} | {
|
|
20
|
+
kind: "approval";
|
|
21
|
+
} | {
|
|
22
|
+
kind: "child";
|
|
23
|
+
definition: string;
|
|
24
|
+
version: number;
|
|
25
|
+
});
|
|
26
|
+
export interface WorkflowDefinition {
|
|
27
|
+
name: string;
|
|
28
|
+
version: number;
|
|
29
|
+
stages: readonly (Step | readonly Step[])[];
|
|
30
|
+
concurrency?: number;
|
|
31
|
+
}
|
|
32
|
+
type Source = string | null | {
|
|
33
|
+
[key: string]: string;
|
|
34
|
+
};
|
|
35
|
+
export type Node = {
|
|
36
|
+
path: string;
|
|
37
|
+
source: Source;
|
|
38
|
+
step: Exclude<Step, {
|
|
39
|
+
kind: "child";
|
|
40
|
+
}> | {
|
|
41
|
+
id: string;
|
|
42
|
+
kind: "join";
|
|
43
|
+
definition: string;
|
|
44
|
+
version: number;
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
export interface Plan {
|
|
48
|
+
name: string;
|
|
49
|
+
version: number;
|
|
50
|
+
concurrency: number;
|
|
51
|
+
nodes: Node[];
|
|
52
|
+
result: Source;
|
|
53
|
+
}
|
|
54
|
+
export declare function checkId(id: string): void;
|
|
55
|
+
export declare function count(n: number, min: number, max?: number): void;
|
|
56
|
+
/** A canonical JSON snapshot independent of object key order or caller mutations. */
|
|
57
|
+
export declare function snapshot<T>(value: T): T;
|
|
58
|
+
export declare function compile(definitions: readonly WorkflowDefinition[], name: string, version: number): Plan;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
export function checkId(id) {
|
|
2
|
+
if (typeof id !== "string" || !/^[A-Za-z0-9_-]{1,128}$/.test(id))
|
|
3
|
+
throw new TypeError("Invalid workflow identifier");
|
|
4
|
+
}
|
|
5
|
+
export function count(n, min, max = 2147483647) {
|
|
6
|
+
if (!Number.isSafeInteger(n) || n < min || n > max)
|
|
7
|
+
throw new RangeError("Invalid workflow limit");
|
|
8
|
+
}
|
|
9
|
+
/** A canonical JSON snapshot independent of object key order or caller mutations. */
|
|
10
|
+
export function snapshot(value) {
|
|
11
|
+
const active = new Set();
|
|
12
|
+
function visit(v) {
|
|
13
|
+
if (v === null ||
|
|
14
|
+
typeof v === "boolean" ||
|
|
15
|
+
typeof v === "string" ||
|
|
16
|
+
(typeof v === "number" && Number.isFinite(v)))
|
|
17
|
+
return v;
|
|
18
|
+
if (!v || typeof v !== "object" || active.has(v))
|
|
19
|
+
throw new TypeError("Expected acyclic JSON");
|
|
20
|
+
active.add(v);
|
|
21
|
+
let result;
|
|
22
|
+
if (Array.isArray(v))
|
|
23
|
+
result = Array.from(v, visit);
|
|
24
|
+
else {
|
|
25
|
+
if (![Object.prototype, null].includes(Object.getPrototypeOf(v)))
|
|
26
|
+
throw new TypeError("Expected plain JSON object");
|
|
27
|
+
result = Object.fromEntries(Object.keys(v)
|
|
28
|
+
.sort()
|
|
29
|
+
.map((k) => [k, visit(v[k])]));
|
|
30
|
+
}
|
|
31
|
+
active.delete(v);
|
|
32
|
+
return result;
|
|
33
|
+
}
|
|
34
|
+
return visit(value);
|
|
35
|
+
}
|
|
36
|
+
export function compile(definitions, name, version) {
|
|
37
|
+
const nodes = [];
|
|
38
|
+
const registry = new Map();
|
|
39
|
+
for (const d of definitions) {
|
|
40
|
+
checkId(d.name);
|
|
41
|
+
count(d.version, 1);
|
|
42
|
+
const key = d.name + "/" + d.version;
|
|
43
|
+
if (registry.has(key))
|
|
44
|
+
throw Error("Duplicate workflow definition");
|
|
45
|
+
registry.set(key, d);
|
|
46
|
+
}
|
|
47
|
+
function expand(key, prefix, source, ancestors) {
|
|
48
|
+
const d = registry.get(key);
|
|
49
|
+
if (!d || ancestors.includes(key))
|
|
50
|
+
throw Error("Missing or cyclic workflow definition: " + key);
|
|
51
|
+
const used = new Set();
|
|
52
|
+
for (const stage of d.stages) {
|
|
53
|
+
const group = Array.isArray(stage);
|
|
54
|
+
const steps = group ? stage : [stage];
|
|
55
|
+
if (!steps.length)
|
|
56
|
+
throw Error("Empty parallel stage");
|
|
57
|
+
const outputs = [];
|
|
58
|
+
for (const step of steps) {
|
|
59
|
+
checkId(step.id);
|
|
60
|
+
if (used.has(step.id))
|
|
61
|
+
throw Error("Duplicate step ID");
|
|
62
|
+
used.add(step.id);
|
|
63
|
+
const path = prefix + "/" + step.id;
|
|
64
|
+
if (step.kind === "child") {
|
|
65
|
+
const inner = expand(step.definition + "/" + step.version, path, source, [...ancestors, key]);
|
|
66
|
+
nodes.push({
|
|
67
|
+
path,
|
|
68
|
+
source: inner,
|
|
69
|
+
step: {
|
|
70
|
+
id: step.id,
|
|
71
|
+
kind: "join",
|
|
72
|
+
definition: step.definition,
|
|
73
|
+
version: step.version,
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
if (step.kind === "task") {
|
|
79
|
+
checkId(step.handler);
|
|
80
|
+
if (step.compensate !== undefined)
|
|
81
|
+
checkId(step.compensate);
|
|
82
|
+
count(step.attempts ?? 3, 1);
|
|
83
|
+
count(step.timeoutMs ?? 30000, 1);
|
|
84
|
+
count(step.retryMs ?? 0, 0);
|
|
85
|
+
if (step.when)
|
|
86
|
+
checkId(step.when.field);
|
|
87
|
+
}
|
|
88
|
+
else if (step.kind === "wait")
|
|
89
|
+
count(step.delayMs, 0);
|
|
90
|
+
else if (step.kind !== "approval")
|
|
91
|
+
throw Error("Unknown step kind");
|
|
92
|
+
nodes.push({ path, source, step });
|
|
93
|
+
}
|
|
94
|
+
outputs.push([step.id, path]);
|
|
95
|
+
}
|
|
96
|
+
source = group ? Object.fromEntries(outputs) : outputs[0][1];
|
|
97
|
+
}
|
|
98
|
+
return source;
|
|
99
|
+
}
|
|
100
|
+
const key = name + "/" + version;
|
|
101
|
+
const result = expand(key, "", null, []);
|
|
102
|
+
const concurrency = registry.get(key).concurrency ?? 1;
|
|
103
|
+
count(concurrency, 1, 256);
|
|
104
|
+
return snapshot({ name, version, concurrency, nodes, result });
|
|
105
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { type Json, type Plan, type WorkflowDefinition } from "./definition.js";
|
|
2
|
+
export * from "./definition.js";
|
|
3
|
+
type Status = "running" | "unwinding" | "completed" | "failed" | "cancelled" | "compensation-failed";
|
|
4
|
+
type Phase = "pending" | "ready" | "active" | "done" | "skipped" | "waiting" | "approval" | "undoing" | "undone" | "failed";
|
|
5
|
+
interface Progress {
|
|
6
|
+
phase: Phase;
|
|
7
|
+
attempt: number;
|
|
8
|
+
input?: Json;
|
|
9
|
+
output?: Json;
|
|
10
|
+
at?: number;
|
|
11
|
+
token?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface Instance {
|
|
14
|
+
id: string;
|
|
15
|
+
plan: Plan;
|
|
16
|
+
input: Json;
|
|
17
|
+
status: Status;
|
|
18
|
+
steps: Record<string, Progress>;
|
|
19
|
+
completed: string[];
|
|
20
|
+
reason?: "failed" | "cancelled";
|
|
21
|
+
output?: Json;
|
|
22
|
+
}
|
|
23
|
+
export interface WorkflowEvent {
|
|
24
|
+
at: number;
|
|
25
|
+
type: string;
|
|
26
|
+
path?: string;
|
|
27
|
+
attempt?: number;
|
|
28
|
+
}
|
|
29
|
+
export interface WorkflowStore {
|
|
30
|
+
create(instance: Instance): Promise<boolean>;
|
|
31
|
+
get(id: string): Promise<Instance | undefined>;
|
|
32
|
+
/** Serialize callbacks per instance and atomically commit the instance and emitted events. */
|
|
33
|
+
update<T>(id: string, fn: (state: Instance, now: number, emit: (event: WorkflowEvent) => void) => T): Promise<T>;
|
|
34
|
+
history(id: string, after?: number, limit?: number): Promise<Array<WorkflowEvent & {
|
|
35
|
+
cursor: number;
|
|
36
|
+
}>>;
|
|
37
|
+
}
|
|
38
|
+
export interface ActivityContext {
|
|
39
|
+
instanceId: string;
|
|
40
|
+
path: string;
|
|
41
|
+
attempt: number;
|
|
42
|
+
idempotencyKey: string;
|
|
43
|
+
signal: AbortSignal;
|
|
44
|
+
}
|
|
45
|
+
export type Activity = (input: Json, ctx: ActivityContext) => Promise<Json>;
|
|
46
|
+
export declare class DurableWorkflowRunner {
|
|
47
|
+
private readonly store;
|
|
48
|
+
private readonly handlers;
|
|
49
|
+
private readonly definitions;
|
|
50
|
+
constructor(store: WorkflowStore, definitions: readonly WorkflowDefinition[], handlers: Readonly<Record<string, Activity>>);
|
|
51
|
+
start(id: string, name: string, version: number, input: Json): Promise<string>;
|
|
52
|
+
inspect(id: string): Promise<Instance | undefined>;
|
|
53
|
+
history(id: string, after?: number, limit?: number): Promise<(WorkflowEvent & {
|
|
54
|
+
cursor: number;
|
|
55
|
+
})[]>;
|
|
56
|
+
approve(id: string, path: string, accepted: boolean): Promise<boolean>;
|
|
57
|
+
cancel(id: string): Promise<boolean>;
|
|
58
|
+
/** Advance local transitions and execute at most one claimed activity. Multiple workers may call tick. */
|
|
59
|
+
tick(id: string): Promise<boolean>;
|
|
60
|
+
}
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import { checkId, compile, count, snapshot, } from "./definition.js";
|
|
2
|
+
export * from "./definition.js";
|
|
3
|
+
function read(s, source) {
|
|
4
|
+
if (source === null)
|
|
5
|
+
return s.input;
|
|
6
|
+
if (typeof source === "string") {
|
|
7
|
+
const p = s.steps[source];
|
|
8
|
+
return p.phase === "done" || p.phase === "skipped" ? p.output : undefined;
|
|
9
|
+
}
|
|
10
|
+
const entries = Object.entries(source).map(([key, path]) => [key, read(s, path)]);
|
|
11
|
+
return entries.some(([, value]) => value === undefined)
|
|
12
|
+
? undefined
|
|
13
|
+
: Object.fromEntries(entries);
|
|
14
|
+
}
|
|
15
|
+
function stop(s, reason) {
|
|
16
|
+
s.reason = reason;
|
|
17
|
+
s.status = "unwinding";
|
|
18
|
+
}
|
|
19
|
+
export class DurableWorkflowRunner {
|
|
20
|
+
constructor(store, definitions, handlers) {
|
|
21
|
+
this.store = store;
|
|
22
|
+
this.handlers = handlers;
|
|
23
|
+
this.definitions = snapshot(definitions);
|
|
24
|
+
}
|
|
25
|
+
async start(id, name, version, input) {
|
|
26
|
+
checkId(id);
|
|
27
|
+
const plan = compile(this.definitions, name, version);
|
|
28
|
+
for (const { step } of plan.nodes)
|
|
29
|
+
if (step.kind === "task")
|
|
30
|
+
for (const h of [step.handler, step.compensate])
|
|
31
|
+
if (h &&
|
|
32
|
+
(!Object.hasOwn(this.handlers, h) ||
|
|
33
|
+
typeof this.handlers[h] !== "function"))
|
|
34
|
+
throw Error("Missing workflow handler: " + h);
|
|
35
|
+
const state = {
|
|
36
|
+
id,
|
|
37
|
+
plan,
|
|
38
|
+
input: snapshot(input),
|
|
39
|
+
status: "running",
|
|
40
|
+
steps: Object.fromEntries(plan.nodes.map((n) => [n.path, { phase: "pending", attempt: 0 }])),
|
|
41
|
+
completed: [],
|
|
42
|
+
};
|
|
43
|
+
if (!(await this.store.create(state))) {
|
|
44
|
+
const existing = await this.store.get(id);
|
|
45
|
+
if (!existing ||
|
|
46
|
+
JSON.stringify(snapshot([existing.plan, existing.input])) !==
|
|
47
|
+
JSON.stringify(snapshot([plan, state.input])))
|
|
48
|
+
throw Error("Conflicting workflow start");
|
|
49
|
+
}
|
|
50
|
+
return id;
|
|
51
|
+
}
|
|
52
|
+
inspect(id) {
|
|
53
|
+
return this.store.get(id);
|
|
54
|
+
}
|
|
55
|
+
history(id, after = 0, limit = 100) {
|
|
56
|
+
count(after, 0, Number.MAX_SAFE_INTEGER);
|
|
57
|
+
count(limit, 1, 1000);
|
|
58
|
+
return this.store.history(id, after, limit);
|
|
59
|
+
}
|
|
60
|
+
approve(id, path, accepted) {
|
|
61
|
+
if (typeof accepted !== "boolean")
|
|
62
|
+
throw new TypeError("Approval decision required");
|
|
63
|
+
return this.store.update(id, (s, now, emit) => {
|
|
64
|
+
const p = s.steps[path];
|
|
65
|
+
if (s.status !== "running" || p?.phase !== "approval")
|
|
66
|
+
return false;
|
|
67
|
+
p.phase = accepted ? "done" : "failed";
|
|
68
|
+
if (accepted)
|
|
69
|
+
p.output = p.input;
|
|
70
|
+
else
|
|
71
|
+
stop(s, "failed");
|
|
72
|
+
emit({ at: now, type: accepted ? "approved" : "rejected", path });
|
|
73
|
+
return true;
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
cancel(id) {
|
|
77
|
+
return this.store.update(id, (s, now, emit) => {
|
|
78
|
+
if (s.status !== "running")
|
|
79
|
+
return false;
|
|
80
|
+
stop(s, "cancelled");
|
|
81
|
+
emit({ at: now, type: "cancel-requested" });
|
|
82
|
+
return true;
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
/** Advance local transitions and execute at most one claimed activity. Multiple workers may call tick. */
|
|
86
|
+
async tick(id) {
|
|
87
|
+
const work = await this.store.update(id, (s, now, emit) => {
|
|
88
|
+
if (s.status !== "running" && s.status !== "unwinding")
|
|
89
|
+
return;
|
|
90
|
+
const plan = compile(this.definitions, s.plan.name, s.plan.version);
|
|
91
|
+
if (JSON.stringify(snapshot(plan)) !== JSON.stringify(snapshot(s.plan)))
|
|
92
|
+
throw Error("Workflow definition changed");
|
|
93
|
+
const event = (type, path, attempt) => emit({
|
|
94
|
+
at: now,
|
|
95
|
+
type,
|
|
96
|
+
...(path ? { path } : {}),
|
|
97
|
+
...(attempt ? { attempt } : {}),
|
|
98
|
+
});
|
|
99
|
+
const claim = (node, p, undo) => {
|
|
100
|
+
if (node.step.kind !== "task")
|
|
101
|
+
throw Error("Invalid activity");
|
|
102
|
+
const timeout = node.step.timeoutMs ?? 30000;
|
|
103
|
+
const token = crypto.randomUUID();
|
|
104
|
+
const handler = undo ? node.step.compensate : node.step.handler;
|
|
105
|
+
if (!Object.hasOwn(this.handlers, handler) ||
|
|
106
|
+
typeof this.handlers[handler] !== "function")
|
|
107
|
+
throw Error("Missing workflow handler: " + handler);
|
|
108
|
+
p.phase = undo ? "undoing" : "active";
|
|
109
|
+
p.token = token;
|
|
110
|
+
p.at = now + timeout;
|
|
111
|
+
p.attempt++;
|
|
112
|
+
event(undo ? "compensation-started" : "step-started", node.path, p.attempt);
|
|
113
|
+
return {
|
|
114
|
+
path: node.path,
|
|
115
|
+
token,
|
|
116
|
+
attempt: p.attempt,
|
|
117
|
+
handler,
|
|
118
|
+
input: snapshot(undo ? { input: p.input, output: p.output } : p.input),
|
|
119
|
+
timeout,
|
|
120
|
+
undo,
|
|
121
|
+
};
|
|
122
|
+
};
|
|
123
|
+
for (const node of plan.nodes) {
|
|
124
|
+
const p = s.steps[node.path];
|
|
125
|
+
if ((p.phase !== "active" && p.phase !== "undoing") || p.at > now)
|
|
126
|
+
continue;
|
|
127
|
+
if (node.step.kind !== "task")
|
|
128
|
+
throw Error("Invalid active step");
|
|
129
|
+
const undo = p.phase === "undoing";
|
|
130
|
+
delete p.token;
|
|
131
|
+
event("lease-expired", node.path, p.attempt);
|
|
132
|
+
if (undo) {
|
|
133
|
+
if (p.attempt >= (node.step.attempts ?? 3)) {
|
|
134
|
+
p.phase = "failed";
|
|
135
|
+
s.status = "compensation-failed";
|
|
136
|
+
event(s.status, node.path);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
return claim(node, p, true);
|
|
140
|
+
}
|
|
141
|
+
if (p.attempt >= (node.step.attempts ?? 3) ||
|
|
142
|
+
s.status === "unwinding") {
|
|
143
|
+
p.phase = "failed";
|
|
144
|
+
if (s.status === "running")
|
|
145
|
+
stop(s, "failed");
|
|
146
|
+
}
|
|
147
|
+
else {
|
|
148
|
+
p.phase = "ready";
|
|
149
|
+
p.at = now + (node.step.retryMs ?? 0);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
const active = Object.values(s.steps).filter((p) => p.phase === "active" || p.phase === "undoing").length;
|
|
153
|
+
if (s.status === "unwinding") {
|
|
154
|
+
if (active)
|
|
155
|
+
return;
|
|
156
|
+
for (let i = s.completed.length - 1; i >= 0; i--) {
|
|
157
|
+
const path = s.completed[i], p = s.steps[path], node = plan.nodes.find((n) => n.path === path);
|
|
158
|
+
if (p.phase === "done" &&
|
|
159
|
+
node.step.kind === "task" &&
|
|
160
|
+
node.step.compensate) {
|
|
161
|
+
p.attempt = 0;
|
|
162
|
+
return claim(node, p, true);
|
|
163
|
+
}
|
|
164
|
+
if (p.phase === "ready" &&
|
|
165
|
+
node.step.kind === "task" &&
|
|
166
|
+
node.step.compensate) {
|
|
167
|
+
if (p.at > now)
|
|
168
|
+
return;
|
|
169
|
+
return claim(node, p, true);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
s.status = s.reason;
|
|
173
|
+
event(s.status);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
for (const node of plan.nodes) {
|
|
177
|
+
const p = s.steps[node.path], step = node.step;
|
|
178
|
+
if (p.phase === "pending") {
|
|
179
|
+
const value = read(s, node.source);
|
|
180
|
+
if (value === undefined)
|
|
181
|
+
continue;
|
|
182
|
+
p.input = value;
|
|
183
|
+
if (step.kind === "wait") {
|
|
184
|
+
p.phase = "waiting";
|
|
185
|
+
p.at = now + step.delayMs;
|
|
186
|
+
event("wait-started", node.path);
|
|
187
|
+
}
|
|
188
|
+
else if (step.kind === "approval") {
|
|
189
|
+
p.phase = "approval";
|
|
190
|
+
event("approval-requested", node.path);
|
|
191
|
+
}
|
|
192
|
+
else if (step.kind === "join") {
|
|
193
|
+
p.phase = "done";
|
|
194
|
+
p.output = value;
|
|
195
|
+
event("child-completed", node.path);
|
|
196
|
+
}
|
|
197
|
+
else if (step.when &&
|
|
198
|
+
(value === null ||
|
|
199
|
+
typeof value !== "object" ||
|
|
200
|
+
!Object.hasOwn(value, step.when.field) ||
|
|
201
|
+
JSON.stringify(snapshot(value[step.when.field])) !== JSON.stringify(snapshot(step.when.equals)))) {
|
|
202
|
+
p.phase = "skipped";
|
|
203
|
+
p.output = value;
|
|
204
|
+
event("step-skipped", node.path);
|
|
205
|
+
}
|
|
206
|
+
else {
|
|
207
|
+
p.phase = "ready";
|
|
208
|
+
p.at = now;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
if (p.phase === "waiting" && p.at <= now) {
|
|
212
|
+
p.phase = "done";
|
|
213
|
+
p.output = p.input;
|
|
214
|
+
event("wait-completed", node.path);
|
|
215
|
+
}
|
|
216
|
+
if (p.phase === "ready" && p.at <= now && active < plan.concurrency)
|
|
217
|
+
return claim(node, p, false);
|
|
218
|
+
}
|
|
219
|
+
const result = read(s, plan.result);
|
|
220
|
+
if (result !== undefined) {
|
|
221
|
+
s.status = "completed";
|
|
222
|
+
s.output = result;
|
|
223
|
+
event(s.status);
|
|
224
|
+
}
|
|
225
|
+
});
|
|
226
|
+
if (!work)
|
|
227
|
+
return false;
|
|
228
|
+
const controller = new AbortController();
|
|
229
|
+
let timer;
|
|
230
|
+
let result;
|
|
231
|
+
try {
|
|
232
|
+
result = snapshot(await Promise.race([
|
|
233
|
+
Promise.resolve().then(() => this.handlers[work.handler](work.input, {
|
|
234
|
+
instanceId: id,
|
|
235
|
+
path: work.path,
|
|
236
|
+
attempt: work.attempt,
|
|
237
|
+
idempotencyKey: JSON.stringify([
|
|
238
|
+
id,
|
|
239
|
+
work.path,
|
|
240
|
+
work.undo ? "undo" : "run",
|
|
241
|
+
]),
|
|
242
|
+
signal: controller.signal,
|
|
243
|
+
})),
|
|
244
|
+
new Promise((_, reject) => {
|
|
245
|
+
timer = setTimeout(() => {
|
|
246
|
+
controller.abort();
|
|
247
|
+
reject(Error("Workflow activity timed out"));
|
|
248
|
+
}, work.timeout);
|
|
249
|
+
}),
|
|
250
|
+
]));
|
|
251
|
+
}
|
|
252
|
+
catch {
|
|
253
|
+
/* Only sanitized outcomes enter history. */
|
|
254
|
+
}
|
|
255
|
+
finally {
|
|
256
|
+
clearTimeout(timer);
|
|
257
|
+
}
|
|
258
|
+
await this.store.update(id, (s, now, emit) => {
|
|
259
|
+
const p = s.steps[work.path];
|
|
260
|
+
if (p.token !== work.token || now >= p.at)
|
|
261
|
+
return;
|
|
262
|
+
const step = s.plan.nodes.find((n) => n.path === work.path).step;
|
|
263
|
+
if (step.kind !== "task")
|
|
264
|
+
throw Error("Invalid activity");
|
|
265
|
+
delete p.token;
|
|
266
|
+
if (result !== undefined) {
|
|
267
|
+
p.phase = work.undo ? "undone" : "done";
|
|
268
|
+
if (!work.undo) {
|
|
269
|
+
p.output = result;
|
|
270
|
+
s.completed.push(work.path);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
else if (p.attempt < (step.attempts ?? 3) &&
|
|
274
|
+
(work.undo || s.status === "running")) {
|
|
275
|
+
p.phase = "ready";
|
|
276
|
+
p.at = now + (step.retryMs ?? 0);
|
|
277
|
+
}
|
|
278
|
+
else {
|
|
279
|
+
p.phase = "failed";
|
|
280
|
+
if (work.undo)
|
|
281
|
+
s.status = "compensation-failed";
|
|
282
|
+
else if (s.status === "running")
|
|
283
|
+
stop(s, "failed");
|
|
284
|
+
}
|
|
285
|
+
emit({
|
|
286
|
+
at: now,
|
|
287
|
+
path: work.path,
|
|
288
|
+
attempt: p.attempt,
|
|
289
|
+
type: result !== undefined
|
|
290
|
+
? work.undo
|
|
291
|
+
? "compensated"
|
|
292
|
+
: "step-completed"
|
|
293
|
+
: work.undo
|
|
294
|
+
? "compensation-error"
|
|
295
|
+
: "step-error",
|
|
296
|
+
});
|
|
297
|
+
});
|
|
298
|
+
return true;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { JobQueue } from "../../jobs-core/dist/index.js";
|
|
2
|
+
import type { EventBus, DomainEvent } from "../../events-core/dist/index.js";
|
|
3
|
+
export interface WorkflowContext {
|
|
4
|
+
readonly id: string;
|
|
5
|
+
readonly signal: AbortSignal;
|
|
6
|
+
enqueue<T>(name: string, payload: T, id: string): Promise<string>;
|
|
7
|
+
publish<T>(event: DomainEvent<T>): Promise<void>;
|
|
8
|
+
}
|
|
9
|
+
export interface WorkflowStep<T> {
|
|
10
|
+
readonly id: string;
|
|
11
|
+
run(value: T, context: WorkflowContext): Promise<T>;
|
|
12
|
+
}
|
|
13
|
+
export declare class WorkflowRunner {
|
|
14
|
+
private readonly queue;
|
|
15
|
+
private readonly events;
|
|
16
|
+
constructor(queue: JobQueue, events: EventBus);
|
|
17
|
+
run<T>(id: string, initial: T, steps: readonly WorkflowStep<T>[], signal?: AbortSignal): Promise<T>;
|
|
18
|
+
}
|
|
19
|
+
export * from "./durable.js";
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export class WorkflowRunner {
|
|
2
|
+
constructor(queue, events) {
|
|
3
|
+
this.queue = queue;
|
|
4
|
+
this.events = events;
|
|
5
|
+
}
|
|
6
|
+
async run(id, initial, steps, signal = new AbortController().signal) { if (!id || steps.some(s => !s.id) || new Set(steps.map(s => s.id)).size !== steps.length)
|
|
7
|
+
throw new Error("Invalid workflow or duplicate step"); let value = initial; for (const step of steps) {
|
|
8
|
+
signal.throwIfAborted();
|
|
9
|
+
const context = { id, signal, enqueue: (name, payload, jobId) => this.queue.enqueue(name, payload, { id: JSON.stringify([id, step.id, jobId]) }), publish: event => this.events.publish(event) };
|
|
10
|
+
value = await step.run(value, context);
|
|
11
|
+
} signal.throwIfAborted(); return value; }
|
|
12
|
+
}
|
|
13
|
+
export * from "./durable.js";
|