@marianmeres/workflow 1.0.1 → 2.2.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/dist/types.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import type { FSMConfig, FSMSnapshot } from "@marianmeres/fsm";
1
+ import type { FSMConfig, FSMSnapshot, FSMStatesConfigValue } from "@marianmeres/fsm";
2
2
  /**
3
- * Default project id used when none is supplied. Mirrors the convention from
3
+ * Default tenant id used when none is supplied. Mirrors the convention from
4
4
  * `@marianmeres/cron`.
5
5
  */
6
- export declare const DEFAULT_PROJECT_ID = "_default";
6
+ export declare const DEFAULT_TENANT_ID = "_default";
7
7
  /** Execution-lifecycle states. Independent of the FSM cursor. */
8
8
  export declare const EXECUTION_STATE: {
9
9
  readonly PENDING: "pending";
@@ -32,6 +32,21 @@ export type NodeMeta = {
32
32
  * Context carried by a workflow instance. Plain JSON. Accumulates across nodes.
33
33
  */
34
34
  export type WorkflowContext = Record<string, unknown>;
35
+ /**
36
+ * An fsm state config narrowed for workflow use: `meta` is a required
37
+ * {@link NodeMeta} instead of fsm's `unknown`, so a misspelled `kind` or a
38
+ * missing `handler` is an editor error rather than a construction-time throw.
39
+ */
40
+ export type WorkflowStateConfig<TState extends string = string, TEvent extends string = string> = FSMStatesConfigValue<TState, TEvent, WorkflowContext> & {
41
+ meta: NodeMeta;
42
+ };
43
+ /**
44
+ * An fsm config whose states are {@link WorkflowStateConfig}s. Narrowing only —
45
+ * still assignable to `FSMConfig`, so `FSM.fromSnapshot(def.fsm, …)` accepts it.
46
+ */
47
+ export type WorkflowFSMConfig<TState extends string = string, TEvent extends string = string> = Omit<FSMConfig<TState, TEvent, WorkflowContext>, "states"> & {
48
+ states: Record<TState, WorkflowStateConfig<TState, TEvent>>;
49
+ };
35
50
  /**
36
51
  * A workflow definition: pure, JSON-serializable data. The fsm config carries
37
52
  * per-state {@link NodeMeta} on its `meta` field; the driver dispatches on
@@ -40,17 +55,34 @@ export type WorkflowContext = Record<string, unknown>;
40
55
  export interface WorkflowDefinition<TState extends string = string, TEvent extends string = string> {
41
56
  id: string;
42
57
  version: string;
43
- fsm: FSMConfig<TState, TEvent, WorkflowContext>;
58
+ fsm: WorkflowFSMConfig<TState, TEvent>;
44
59
  }
45
60
  /** Result returned by an effectful node's handler. */
46
61
  export interface HandlerResult {
47
62
  outcome: string;
48
63
  data?: Record<string, unknown>;
64
+ /**
65
+ * Correlation token to put on the instance row, written at the settle point
66
+ * this result leads to — so a wait point can key on something that only
67
+ * exists once the effect has run (an SMTP `Message-ID`, a payment-provider
68
+ * session id). `null` clears the token; omitting the field leaves whatever
69
+ * `create({ correlationToken })` set.
70
+ */
71
+ correlationToken?: string | null;
72
+ /**
73
+ * Shallow patch for the instance context, applied before the outcome
74
+ * transition — so guards and actions on the outcome edge already see it, and
75
+ * it is persisted at the settle point. Top-level keys replace.
76
+ *
77
+ * Opt-in on purpose: `data` alone is the fsm payload and never reaches the
78
+ * context, so the persisted shape stays a per-handler choice.
79
+ */
80
+ context?: Partial<WorkflowContext>;
49
81
  }
50
82
  /** Arguments passed to an effectful handler. */
51
83
  export interface HandlerArgs {
52
84
  instanceId: string;
53
- projectId: string;
85
+ tenantId: string;
54
86
  context: WorkflowContext;
55
87
  signal?: AbortSignal;
56
88
  }
@@ -64,7 +96,7 @@ export type Handler = (args: HandlerArgs) => Promise<HandlerResult> | HandlerRes
64
96
  /** Arguments passed to a matcher predicate. */
65
97
  export interface MatcherArgs {
66
98
  instanceId: string;
67
- projectId: string;
99
+ tenantId: string;
68
100
  context: WorkflowContext;
69
101
  signal: InboxRow;
70
102
  }
@@ -78,7 +110,7 @@ export type Matcher = (args: MatcherArgs) => boolean | Promise<boolean>;
78
110
  /** A single row from `__workflow_instances`. Matches the schema 1:1. */
79
111
  export interface WorkflowInstanceRow {
80
112
  id: string;
81
- project_id: string;
113
+ tenant_id: string;
82
114
  definition_id: string;
83
115
  definition_version: string;
84
116
  cursor: string;
@@ -87,13 +119,18 @@ export interface WorkflowInstanceRow {
87
119
  execution_state: ExecutionState;
88
120
  wake_at: Date | null;
89
121
  correlation_token: string | null;
122
+ /**
123
+ * Fencing token. Bumped by every settle-point write; jobs carry the value
124
+ * they were issued against, so a stale one is recognized and dropped.
125
+ */
126
+ seq: number;
90
127
  created_at: Date;
91
128
  updated_at: Date;
92
129
  }
93
130
  /** A single row from `__workflow_inbox`. */
94
131
  export interface InboxRow {
95
132
  id: string;
96
- project_id: string;
133
+ tenant_id: string;
97
134
  received_at: Date;
98
135
  source: string;
99
136
  correlation_token: string;
@@ -114,13 +151,14 @@ export declare const HISTORY_EVENT: {
114
151
  readonly COMPLETED: "completed";
115
152
  readonly FAILED: "failed";
116
153
  readonly CANCELLED: "cancelled";
154
+ readonly RETRIED: "retried";
117
155
  };
118
156
  /** Union of all valid {@link HISTORY_EVENT} string values. */
119
157
  export type HistoryEventType = (typeof HISTORY_EVENT)[keyof typeof HISTORY_EVENT];
120
158
  /** A single row from `__workflow_history`. */
121
159
  export interface HistoryRow {
122
160
  id: number;
123
- project_id: string;
161
+ tenant_id: string;
124
162
  instance_id: string;
125
163
  at: Date;
126
164
  event_type: HistoryEventType;
@@ -128,27 +166,102 @@ export interface HistoryRow {
128
166
  to_node: string | null;
129
167
  data: Record<string, unknown>;
130
168
  }
169
+ /**
170
+ * Synthetic event fired by the driver when entering a pure (decision) state,
171
+ * so the user's guarded transitions can route by inspecting context.
172
+ *
173
+ * Pure nodes typically look like:
174
+ *
175
+ * foo: {
176
+ * meta: { kind: "pure" },
177
+ * on: {
178
+ * ENTER: [
179
+ * { target: "go_left", guard: (ctx) => ctx.x > 5 },
180
+ * { target: "go_right" },
181
+ * ],
182
+ * },
183
+ * }
184
+ */
185
+ export declare const PURE_ENTER_EVENT = "ENTER";
186
+ /**
187
+ * Event fired at a suspending node when a correlated inbox signal is delivered.
188
+ * A node that does not accept it is not a delivery target at all — the
189
+ * correlator defers the signal instead of poking (see `WorkflowInboxCorrelator`).
190
+ */
191
+ export declare const SIGNAL_MATCHED_EVENT = "MATCHED";
192
+ /** Event fired at a suspending node by the scheduler once its `wake_at` is due. */
193
+ export declare const TIMEOUT_EVENT = "TIMEOUT";
131
194
  /** Steve job type for "advance this instance one step". */
132
195
  export declare const JOB_TYPE_ADVANCE = "workflow.advance";
133
196
  /** Steve job-type prefix for effect-handler jobs. Full type is `workflow.effect.<handlerName>`. */
134
197
  export declare const JOB_TYPE_EFFECT_PREFIX = "workflow.effect.";
198
+ /** What produced a `workflow.advance` job. Drives the driver's preconditions. */
199
+ export type AdvanceKind = "start" | "effect" | "timeout" | "signal";
135
200
  /** Payload of a `workflow.advance` job. */
136
201
  export interface AdvanceJobPayload {
137
- project_id: string;
202
+ tenant_id: string;
138
203
  instance_id: string;
204
+ /**
205
+ * What produced this advance. Absent on jobs queued before the fence
206
+ * existed — the driver then infers it from the payload shape.
207
+ */
208
+ kind?: AdvanceKind;
209
+ /**
210
+ * Fencing token: the instance `seq` this advance was issued against. The
211
+ * driver drops the job if the locked row has moved past it. Absent =
212
+ * unfenced (a job queued before the fence existed).
213
+ */
214
+ expected_seq?: number;
139
215
  /** Optional outcome label to apply before dispatching. Set when an effect/signal completes. */
140
216
  outcome?: string;
141
217
  /** Optional payload to merge into context via the outcome's `data` field. */
142
218
  outcome_data?: Record<string, unknown>;
143
- /** Marks this advance as a TIMEOUT wake-up (so the driver emits a TIMEOUT outcome). */
144
- timeout?: boolean;
219
+ /**
220
+ * Inbox row being delivered. `kind: "signal"` only — the driver reads the
221
+ * outcome data off the row and marks it processed in the same transaction as
222
+ * the transition, so delivery and transition commit together.
223
+ */
224
+ inbox_id?: string;
225
+ /** Effect handler that produced the outcome. `kind: "effect"` only; for history. */
226
+ handler?: string;
227
+ /**
228
+ * Correlation token the handler returned ({@link HandlerResult.correlationToken}).
229
+ * Written at this advance's settle point; `null` clears the token, absent
230
+ * leaves the row's own value alone. `kind: "effect"` only.
231
+ */
232
+ correlation_token?: string | null;
233
+ /**
234
+ * Shallow context patch the handler returned ({@link HandlerResult.context}).
235
+ * Merged into the instance context before the outcome is applied.
236
+ * `kind: "effect"` only.
237
+ */
238
+ context_patch?: Partial<WorkflowContext>;
239
+ /**
240
+ * How many times this payload has been re-dispatched after its job expired
241
+ * (i.e. its worker died mid-run — steve never retries those). Bounded by
242
+ * `redispatchLimit`; absent on a first dispatch.
243
+ */
244
+ redispatch?: number;
145
245
  [key: string]: unknown;
146
246
  }
147
247
  /** Payload of a `workflow.effect.<handlerName>` job. */
148
248
  export interface EffectJobPayload {
149
- project_id: string;
249
+ tenant_id: string;
150
250
  instance_id: string;
151
251
  handler: string;
252
+ /**
253
+ * Fencing token: the instance `seq` at dispatch time. A handler is not run
254
+ * against a row that has moved past it. Absent = unfenced (a job queued
255
+ * before the fence existed).
256
+ */
257
+ seq?: number;
258
+ /** Node that dispatched this effect. Diagnostics only. */
259
+ cursor?: string;
260
+ /**
261
+ * How many times this payload has been re-dispatched after its job expired.
262
+ * See {@link AdvanceJobPayload.redispatch}.
263
+ */
264
+ redispatch?: number;
152
265
  [key: string]: unknown;
153
266
  }
154
267
  /** Convenience re-export — the FSM snapshot shape the driver passes around. */
package/dist/types.js CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
- * Default project id used when none is supplied. Mirrors the convention from
2
+ * Default tenant id used when none is supplied. Mirrors the convention from
3
3
  * `@marianmeres/cron`.
4
4
  */
5
- export const DEFAULT_PROJECT_ID = "_default";
5
+ export const DEFAULT_TENANT_ID = "_default";
6
6
  /** Execution-lifecycle states. Independent of the FSM cursor. */
7
7
  export const EXECUTION_STATE = {
8
8
  PENDING: "pending",
@@ -26,7 +26,33 @@ export const HISTORY_EVENT = {
26
26
  COMPLETED: "completed",
27
27
  FAILED: "failed",
28
28
  CANCELLED: "cancelled",
29
+ RETRIED: "retried",
29
30
  };
31
+ /**
32
+ * Synthetic event fired by the driver when entering a pure (decision) state,
33
+ * so the user's guarded transitions can route by inspecting context.
34
+ *
35
+ * Pure nodes typically look like:
36
+ *
37
+ * foo: {
38
+ * meta: { kind: "pure" },
39
+ * on: {
40
+ * ENTER: [
41
+ * { target: "go_left", guard: (ctx) => ctx.x > 5 },
42
+ * { target: "go_right" },
43
+ * ],
44
+ * },
45
+ * }
46
+ */
47
+ export const PURE_ENTER_EVENT = "ENTER";
48
+ /**
49
+ * Event fired at a suspending node when a correlated inbox signal is delivered.
50
+ * A node that does not accept it is not a delivery target at all — the
51
+ * correlator defers the signal instead of poking (see `WorkflowInboxCorrelator`).
52
+ */
53
+ export const SIGNAL_MATCHED_EVENT = "MATCHED";
54
+ /** Event fired at a suspending node by the scheduler once its `wake_at` is due. */
55
+ export const TIMEOUT_EVENT = "TIMEOUT";
30
56
  /** Steve job type for "advance this instance one step". */
31
57
  export const JOB_TYPE_ADVANCE = "workflow.advance";
32
58
  /** Steve job-type prefix for effect-handler jobs. Full type is `workflow.effect.<handlerName>`. */
@@ -17,8 +17,8 @@ export interface WorkflowOptions {
17
17
  * by `type` on the same `__job` table.
18
18
  */
19
19
  jobs: Jobs;
20
- /** Project scope (multi-tenancy). Defaults to `_default`. */
21
- projectId?: string;
20
+ /** Tenant scope (multi-tenancy). Defaults to `_default`. */
21
+ tenantId?: string;
22
22
  /** Workflow definitions to register. Each is keyed by `(id, version)`. */
23
23
  definitions: WorkflowDefinition[];
24
24
  /** Handlers keyed by name (referenced from `state.meta.handler`). */
@@ -29,6 +29,28 @@ export interface WorkflowOptions {
29
29
  effectMaxAttempts?: number;
30
30
  /** Per-effect-job timeout in ms. Default: 0 (no limit). */
31
31
  effectMaxAttemptDurationMs?: number;
32
+ /**
33
+ * Per-advance-job retry count. Default: 10 — an advance only fails on a
34
+ * throwing guard/action or a database error, and steve's exponential backoff
35
+ * over 10 attempts spans ~17 minutes, so a brief outage does not cost an
36
+ * instance. When they are exhausted the instance is marked `failed` with the
37
+ * last attempt's error message.
38
+ */
39
+ advanceMaxAttempts?: number;
40
+ /**
41
+ * How many times a single job payload may be dispatched, counting the
42
+ * original. Default: 3.
43
+ *
44
+ * An `expired` job is one whose worker died mid-run; steve never retries
45
+ * those, so the framework re-queues the identical payload instead. The fence
46
+ * (`seq`) makes the re-dispatch a no-op if the dead worker's transaction did
47
+ * commit, and handlers are required to be idempotent, so a crash becomes a
48
+ * recovery. Once the budget is spent the instance is marked `failed`.
49
+ *
50
+ * Note that expiry only happens at all when the `Jobs` instance runs with
51
+ * `autoCleanup` (or something calls `jobs.cleanup()` periodically).
52
+ */
53
+ redispatchLimit?: number;
32
54
  }
33
55
  /**
34
56
  * The user-facing API for creating workflow instances and appending inbox
@@ -47,9 +69,23 @@ export declare class Workflow implements JobEnqueuer {
47
69
  #private;
48
70
  readonly db: pg.Pool;
49
71
  readonly jobs: Jobs;
50
- readonly projectId: string;
72
+ readonly tenantId: string;
51
73
  readonly registry: WorkflowRegistry;
52
74
  constructor(options: WorkflowOptions);
75
+ /**
76
+ * Removes everything the constructor registered on the `Jobs` instance — the
77
+ * `workflow.advance` and `workflow.effect.<name>` handlers plus the `onDone`
78
+ * subscriptions — and releases the one-Workflow-per-Jobs claim, so a
79
+ * replacement can be constructed on the same queue (tests, hot reload).
80
+ *
81
+ * Detaching does not stop the queue and does not touch running instances:
82
+ * jobs enqueued for this `Workflow` stay in the table and fall back to
83
+ * steve's noop handler until something re-attaches.
84
+ *
85
+ * A no-op when this instance is not the attached one (already detached, or
86
+ * superseded by a later `Workflow`).
87
+ */
88
+ detach(): void;
53
89
  /** Internal — used by the driver to enqueue an advance job. */
54
90
  enqueueAdvance(_client: pg.PoolClient | pg.Client | pg.Pool, payload: AdvanceJobPayload): Promise<void>;
55
91
  /** Internal — used by the driver to enqueue an effect job. */
@@ -57,6 +93,8 @@ export declare class Workflow implements JobEnqueuer {
57
93
  /**
58
94
  * Creates a new workflow instance and enqueues its first advance.
59
95
  *
96
+ * @param input.context - shallow-merged over the definition's own
97
+ * `fsm.context` defaults (top-level keys replace, they do not deep-merge).
60
98
  * @param input.correlationToken - optional, set up-front for signal-suspending
61
99
  * nodes that need to be matchable from the moment the instance is born
62
100
  * (e.g., outbound emails using UUID subaddressing).
@@ -67,7 +105,41 @@ export declare class Workflow implements JobEnqueuer {
67
105
  context?: WorkflowContext;
68
106
  correlationToken?: string | null;
69
107
  }): Promise<WorkflowInstanceRow>;
70
- /** Looks up an instance by id, scoped to this Workflow's project. */
108
+ /**
109
+ * Operator escape hatch: aborts a live instance. The row goes `cancelled`
110
+ * (terminal), loses its `wake_at` and its correlation token — so no timer, no
111
+ * signal and no queued job can move it again: the `seq` bump makes every job
112
+ * already in flight for it stale, and a stale effect job skips its handler
113
+ * instead of running the side effect.
114
+ *
115
+ * Returns `false` when the instance does not exist, belongs to another tenant,
116
+ * or is already terminal.
117
+ *
118
+ * @param reason - free-form, recorded on the `cancelled` history row.
119
+ */
120
+ cancel(id: string, reason?: string): Promise<boolean>;
121
+ /**
122
+ * Operator escape hatch: resumes a `failed` instance from its current cursor,
123
+ * rather than starting a new one and replaying every side effect from the top.
124
+ * The row goes back to `pending` and a fresh `start` advance re-runs whatever
125
+ * the cursor node calls for — typically re-dispatching its effect.
126
+ *
127
+ * Nothing is fixed by retrying alone: an instance failed by a rejected
128
+ * transition or a deterministically throwing handler will fail again unless
129
+ * the code changed.
130
+ *
131
+ * Returns `false` when the instance does not exist, belongs to another tenant,
132
+ * or is in a state this does not cover.
133
+ *
134
+ * @param opts.force - also allow a `running` instance, i.e. the operator
135
+ * asserting that its effect job is dead (a worker crashed with no reaper to
136
+ * expire the job). Safe by construction: the `seq` bump makes the zombie
137
+ * stale, so a late completion is dropped.
138
+ */
139
+ retry(id: string, opts?: {
140
+ force?: boolean;
141
+ }): Promise<boolean>;
142
+ /** Looks up an instance by id, scoped to this Workflow's tenant. */
71
143
  find(id: string): Promise<WorkflowInstanceRow | null>;
72
144
  /**
73
145
  * Appends an external signal to the inbox. The {@link WorkflowInboxCorrelator}