@marianmeres/workflow 2.1.0 → 3.0.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/mod.js CHANGED
@@ -4,11 +4,14 @@
4
4
  * Durable workflow / orchestration framework for long-lived state machines.
5
5
  * Built on PostgreSQL. Instances persist across process restarts, sleep for
6
6
  * days waiting for a signal or a timer, and resume from disk via
7
- * {@link https://jsr.io/@marianmeres/fsm | @marianmeres/fsm}'s `fromSnapshot`.
8
- * Effects run as {@link https://jsr.io/@marianmeres/steve | @marianmeres/steve}
7
+ * {@link https://www.npmjs.com/package/@marianmeres/fsm | @marianmeres/fsm}'s `fromSnapshot`.
8
+ * Effects run as {@link https://www.npmjs.com/package/@marianmeres/steve | @marianmeres/steve}
9
9
  * jobs (transactional outbox). The scheduler and inbox correlator are driven
10
- * by {@link https://jsr.io/@marianmeres/cron | @marianmeres/cron}. Schema is
11
- * managed by {@link https://jsr.io/@marianmeres/migrate | @marianmeres/migrate}.
10
+ * by {@link https://www.npmjs.com/package/@marianmeres/cron | @marianmeres/cron}.
11
+ * Every statement runs through
12
+ * {@link https://www.npmjs.com/package/@marianmeres/sqlkit | @marianmeres/sqlkit},
13
+ * which also runs the schema migrations
14
+ * ({@link https://www.npmjs.com/package/@marianmeres/migrate | @marianmeres/migrate}).
12
15
  *
13
16
  * Ships no domain code — userland brings the definitions, handlers, and
14
17
  * matchers. The framework provides the dispatch core and the durability story.
@@ -20,6 +23,9 @@
20
23
  * import { Cron } from "@marianmeres/cron";
21
24
  * import { createMigrate, Workflow } from "@marianmeres/workflow";
22
25
  *
26
+ * // `db` is a pg.Pool, a connected pg.Client, or a sqlkit Driver. Give the
27
+ * // same one to Jobs and Workflow: they then share transactions, so a job is
28
+ * // enqueued in the same transaction as the instance write it belongs to.
23
29
  * const pool = new pg.Pool({ /* ... *\/ });
24
30
  * await createMigrate(pool).up("latest");
25
31
  *
@@ -38,12 +44,12 @@
38
44
  * await wf.create({ definitionId: "...", definitionVersion: "1.0.0" });
39
45
  * ```
40
46
  */
41
- export { Workflow } from "./workflow.js";
42
- export { WorkflowScheduler, } from "./scheduler.js";
43
47
  export { WorkflowInboxCorrelator, } from "./correlator.js";
44
- export { WorkflowRegistry } from "./registry.js";
45
48
  export { defKey, validateDefinition } from "./definition.js";
49
+ export { effectJobType, JOB_TYPE_ADVANCE, PURE_ENTER_EVENT } from "./driver.js";
46
50
  export { createMigrate } from "./migrations/index.js";
47
51
  export { getHistory } from "./persistence/history.js";
48
- export { effectJobType, JOB_TYPE_ADVANCE, PURE_ENTER_EVENT } from "./driver.js";
52
+ export { WorkflowRegistry } from "./registry.js";
53
+ export { WorkflowScheduler, } from "./scheduler.js";
49
54
  export { DEFAULT_TENANT_ID, EXECUTION_STATE, HISTORY_EVENT, JOB_TYPE_EFFECT_PREFIX, } from "./types.js";
55
+ export { Workflow } from "./workflow.js";
@@ -1,12 +1,12 @@
1
- import type pg from "pg";
2
- import type { HistoryEventType, HistoryRow } from "../types.js";
3
- type Executor = pg.Pool | pg.PoolClient | pg.Client;
1
+ import { type Driver } from "@marianmeres/sqlkit";
2
+ import { type PgDb } from "@marianmeres/sqlkit/pg";
3
+ import type { HistoryEventType, HistoryRow } from "../types.ts";
4
4
  /**
5
- * Appends a single audit row to `__workflow_history`. Accepts a pool, a
6
- * client, or a transaction-bound client — call this inside the same
7
- * transaction as the state change it describes.
5
+ * Appends a single audit row to `__workflow_history`. Call this inside the
6
+ * `db.transaction()` callback of the state change it describes: a statement
7
+ * issued there is part of that transaction.
8
8
  */
9
- export declare function appendHistory(exec: Executor, input: {
9
+ export declare function appendHistory(db: Driver, input: {
10
10
  tenant_id: string;
11
11
  instance_id: string;
12
12
  event_type: HistoryEventType;
@@ -18,9 +18,9 @@ export declare function appendHistory(exec: Executor, input: {
18
18
  * Reads the audit log for an instance in chronological order (oldest first).
19
19
  * Useful for `/admin/workflows`-style observability surfaces and tests.
20
20
  *
21
- * @param exec - pool, client, or transaction-bound client
21
+ * @param db - a `pg.Pool`, a connected `pg.Client`, or a sqlkit `Driver` of the
22
+ * `pg` dialect — what {@link Workflow} takes as its `db`
22
23
  * @param instance_id - id of the instance whose history to read
23
24
  * @param limit - max rows to return; default `200`
24
25
  */
25
- export declare function getHistory(exec: Executor, instance_id: string, limit?: number): Promise<HistoryRow[]>;
26
- export {};
26
+ export declare function getHistory(db: PgDb, instance_id: string, limit?: number): Promise<HistoryRow[]>;
@@ -1,33 +1,34 @@
1
- const SELECT_COLUMNS = `id, tenant_id, instance_id, at, event_type, from_node, to_node, data`;
1
+ import { insert, json, sql } from "@marianmeres/sqlkit";
2
+ import { toPgDriver } from "@marianmeres/sqlkit/pg";
2
3
  /**
3
- * Appends a single audit row to `__workflow_history`. Accepts a pool, a
4
- * client, or a transaction-bound client — call this inside the same
5
- * transaction as the state change it describes.
4
+ * Appends a single audit row to `__workflow_history`. Call this inside the
5
+ * `db.transaction()` callback of the state change it describes: a statement
6
+ * issued there is part of that transaction.
6
7
  */
7
- export async function appendHistory(exec, input) {
8
- await exec.query(`INSERT INTO __workflow_history
9
- (tenant_id, instance_id, event_type, from_node, to_node, data)
10
- VALUES ($1, $2, $3, $4, $5, $6::jsonb)`, [
11
- input.tenant_id,
12
- input.instance_id,
13
- input.event_type,
14
- input.from_node ?? null,
15
- input.to_node ?? null,
16
- JSON.stringify(input.data ?? {}),
17
- ]);
8
+ export async function appendHistory(db, input) {
9
+ await db.query(insert("__workflow_history", {
10
+ tenant_id: input.tenant_id,
11
+ instance_id: input.instance_id,
12
+ event_type: input.event_type,
13
+ from_node: input.from_node ?? null,
14
+ to_node: input.to_node ?? null,
15
+ data: json(input.data ?? {}),
16
+ }));
18
17
  }
19
18
  /**
20
19
  * Reads the audit log for an instance in chronological order (oldest first).
21
20
  * Useful for `/admin/workflows`-style observability surfaces and tests.
22
21
  *
23
- * @param exec - pool, client, or transaction-bound client
22
+ * @param db - a `pg.Pool`, a connected `pg.Client`, or a sqlkit `Driver` of the
23
+ * `pg` dialect — what {@link Workflow} takes as its `db`
24
24
  * @param instance_id - id of the instance whose history to read
25
25
  * @param limit - max rows to return; default `200`
26
26
  */
27
- export async function getHistory(exec, instance_id, limit = 200) {
28
- const r = await exec.query(`SELECT ${SELECT_COLUMNS} FROM __workflow_history
29
- WHERE instance_id = $1
30
- ORDER BY at, id
31
- LIMIT $2`, [instance_id, limit]);
32
- return r.rows;
27
+ export async function getHistory(db, instance_id, limit = 200) {
28
+ const { rows } = await toPgDriver(db).query(sql `SELECT id, tenant_id, instance_id, at, event_type, from_node, to_node, data
29
+ FROM __workflow_history
30
+ WHERE instance_id = ${instance_id}
31
+ ORDER BY at, id
32
+ LIMIT ${limit}`);
33
+ return rows;
33
34
  }
@@ -1,11 +1,10 @@
1
- import type pg from "pg";
2
- import type { InboxRow } from "../types.js";
3
- type Executor = pg.Pool | pg.PoolClient | pg.Client;
1
+ import { type Driver } from "@marianmeres/sqlkit";
2
+ import type { InboxRow } from "../types.ts";
4
3
  /**
5
4
  * Inserts an external signal into `__workflow_inbox`. The correlator will
6
5
  * pick it up on its next tick and attempt to match it to a waiting instance.
7
6
  */
8
- export declare function appendInbox(exec: Executor, input: {
7
+ export declare function appendInbox(db: Driver, input: {
9
8
  tenant_id: string;
10
9
  source: string;
11
10
  correlation_token: string;
@@ -14,16 +13,16 @@ export declare function appendInbox(exec: Executor, input: {
14
13
  /**
15
14
  * Claims a batch of unprocessed inbox rows for the tenant. Uses
16
15
  * `FOR UPDATE SKIP LOCKED` so two concurrent correlator workers don't grab
17
- * the same row. Caller MUST be inside a transaction and either mark them
18
- * processed or roll back.
16
+ * the same row. Call it inside a `db.transaction()` callback, which either
17
+ * marks them processed or leaves them for the next tick: the claim lasts as
18
+ * long as that transaction.
19
19
  */
20
- export declare function claimUnprocessed(client: pg.PoolClient | pg.Client, tenant_id: string, limit?: number): Promise<InboxRow[]>;
20
+ export declare function claimUnprocessed(db: Driver, tenant_id: string, limit?: number): Promise<InboxRow[]>;
21
21
  /**
22
- * Loads a single inbox row with a row-level lock — caller MUST be inside a
23
- * transaction. Used by the advance to mark delivery in the same transaction as
24
- * the transition it triggers.
22
+ * Loads a single inbox row with a row-level lock, held until the transaction
23
+ * this is called in ends. Used by the advance to mark delivery in the same
24
+ * transaction as the transition it triggers.
25
25
  */
26
- export declare function lockInboxRow(client: pg.PoolClient | pg.Client, id: string): Promise<InboxRow | null>;
26
+ export declare function lockInboxRow(db: Driver, id: string): Promise<InboxRow | null>;
27
27
  /** Marks an inbox row as processed (sets `processed_at = now()`). */
28
- export declare function markProcessed(exec: Executor, id: string): Promise<void>;
29
- export {};
28
+ export declare function markProcessed(db: Driver, id: string): Promise<void>;
@@ -1,46 +1,55 @@
1
- const SELECT_COLUMNS = `
2
- id, tenant_id, received_at, source, correlation_token, payload, processed_at
3
- `;
1
+ import { insert, json, raw, sql, update } from "@marianmeres/sqlkit";
2
+ const TABLE = "__workflow_inbox";
3
+ /** Every column of an {@link InboxRow}, in the order a read returns them. */
4
+ const COLUMNS = [
5
+ "id",
6
+ "tenant_id",
7
+ "received_at",
8
+ "source",
9
+ "correlation_token",
10
+ "payload",
11
+ "processed_at",
12
+ ];
13
+ const SELECT_COLUMNS = raw(COLUMNS.join(", "));
4
14
  /**
5
15
  * Inserts an external signal into `__workflow_inbox`. The correlator will
6
16
  * pick it up on its next tick and attempt to match it to a waiting instance.
7
17
  */
8
- export async function appendInbox(exec, input) {
9
- const r = await exec.query(`INSERT INTO __workflow_inbox (tenant_id, source, correlation_token, payload)
10
- VALUES ($1, $2, $3, $4::jsonb)
11
- RETURNING ${SELECT_COLUMNS}`, [
12
- input.tenant_id,
13
- input.source,
14
- input.correlation_token,
15
- JSON.stringify(input.payload),
16
- ]);
17
- return r.rows[0];
18
+ export async function appendInbox(db, input) {
19
+ const { rows } = await db.query(insert(TABLE, {
20
+ tenant_id: input.tenant_id,
21
+ source: input.source,
22
+ correlation_token: input.correlation_token,
23
+ payload: json(input.payload),
24
+ }, { returning: COLUMNS }));
25
+ return rows[0];
18
26
  }
19
27
  /**
20
28
  * Claims a batch of unprocessed inbox rows for the tenant. Uses
21
29
  * `FOR UPDATE SKIP LOCKED` so two concurrent correlator workers don't grab
22
- * the same row. Caller MUST be inside a transaction and either mark them
23
- * processed or roll back.
30
+ * the same row. Call it inside a `db.transaction()` callback, which either
31
+ * marks them processed or leaves them for the next tick: the claim lasts as
32
+ * long as that transaction.
24
33
  */
25
- export async function claimUnprocessed(client, tenant_id, limit = 100) {
26
- const r = await client.query(`SELECT ${SELECT_COLUMNS} FROM __workflow_inbox
27
- WHERE tenant_id = $1
28
- AND processed_at IS NULL
29
- ORDER BY received_at
30
- LIMIT $2
31
- FOR UPDATE SKIP LOCKED`, [tenant_id, limit]);
32
- return r.rows;
34
+ export async function claimUnprocessed(db, tenant_id, limit = 100) {
35
+ const { rows } = await db.query(sql `SELECT ${SELECT_COLUMNS} FROM __workflow_inbox
36
+ WHERE tenant_id = ${tenant_id}
37
+ AND processed_at IS NULL
38
+ ORDER BY received_at
39
+ LIMIT ${limit}
40
+ FOR UPDATE SKIP LOCKED`);
41
+ return rows;
33
42
  }
34
43
  /**
35
- * Loads a single inbox row with a row-level lock — caller MUST be inside a
36
- * transaction. Used by the advance to mark delivery in the same transaction as
37
- * the transition it triggers.
44
+ * Loads a single inbox row with a row-level lock, held until the transaction
45
+ * this is called in ends. Used by the advance to mark delivery in the same
46
+ * transaction as the transition it triggers.
38
47
  */
39
- export async function lockInboxRow(client, id) {
40
- const r = await client.query(`SELECT ${SELECT_COLUMNS} FROM __workflow_inbox WHERE id = $1 FOR UPDATE`, [id]);
41
- return r.rows[0] ?? null;
48
+ export async function lockInboxRow(db, id) {
49
+ const { rows } = await db.query(sql `SELECT ${SELECT_COLUMNS} FROM __workflow_inbox WHERE id = ${id} FOR UPDATE`);
50
+ return rows[0] ?? null;
42
51
  }
43
52
  /** Marks an inbox row as processed (sets `processed_at = now()`). */
44
- export async function markProcessed(exec, id) {
45
- await exec.query(`UPDATE __workflow_inbox SET processed_at = now() WHERE id = $1`, [id]);
53
+ export async function markProcessed(db, id) {
54
+ await db.query(update(TABLE, { processed_at: raw("now()") }, { id }));
46
55
  }
@@ -1,12 +1,11 @@
1
- import type pg from "pg";
2
- import { type ExecutionState, type WorkflowContext, type WorkflowInstanceRow } from "../types.js";
3
- type Executor = pg.Pool | pg.PoolClient | pg.Client;
1
+ import { type Driver } from "@marianmeres/sqlkit";
2
+ import { type ExecutionState, type WorkflowContext, type WorkflowInstanceRow } from "../types.ts";
4
3
  /**
5
4
  * Inserts a new workflow instance row in `execution_state='pending'` at the
6
5
  * provided cursor (typically `def.fsm.initial`). Caller is responsible for
7
6
  * enqueuing the first `workflow.advance` job.
8
7
  */
9
- export declare function createInstance(exec: Executor, input: {
8
+ export declare function createInstance(db: Driver, input: {
10
9
  tenant_id: string;
11
10
  definition_id: string;
12
11
  definition_version: string;
@@ -15,9 +14,13 @@ export declare function createInstance(exec: Executor, input: {
15
14
  correlation_token?: string | null;
16
15
  }): Promise<WorkflowInstanceRow>;
17
16
  /** Reads a workflow instance by id, or `null` if not found. No lock. */
18
- export declare function findInstance(exec: Executor, id: string): Promise<WorkflowInstanceRow | null>;
19
- /** Loads with a row-level lock — caller MUST be inside a transaction. */
20
- export declare function lockInstance(client: pg.PoolClient | pg.Client, id: string): Promise<WorkflowInstanceRow | null>;
17
+ export declare function findInstance(db: Driver, id: string): Promise<WorkflowInstanceRow | null>;
18
+ /**
19
+ * Loads with a row-level lock, held until the transaction this is called in ends
20
+ * — call it inside a `db.transaction()` callback. Outside one the statement is its
21
+ * own transaction, and the lock is gone the moment it returns.
22
+ */
23
+ export declare function lockInstance(db: Driver, id: string): Promise<WorkflowInstanceRow | null>;
21
24
  /**
22
25
  * Partial-update of a workflow instance row. Only fields present in `patch`
23
26
  * are written; `updated_at` is bumped automatically.
@@ -26,7 +29,7 @@ export declare function lockInstance(client: pg.PoolClient | pg.Client, id: stri
26
29
  * settle-point writes, so every job issued against the pre-write row becomes
27
30
  * recognizably stale.
28
31
  */
29
- export declare function updateInstance(exec: Executor, id: string, patch: {
32
+ export declare function updateInstance(db: Driver, id: string, patch: {
30
33
  cursor?: string;
31
34
  previous_cursor?: string | null;
32
35
  context?: WorkflowContext;
@@ -48,18 +51,21 @@ export interface InstancePoke {
48
51
  * not yet advanced stays due and is poked again next tick; the fence turns the
49
52
  * duplicate into a no-op. Nothing is left stranded by a crash mid-tick.
50
53
  */
51
- export declare function selectDueWakeUps(exec: Executor, tenant_id: string, limit?: number): Promise<InstancePoke[]>;
54
+ export declare function selectDueWakeUps(db: Driver, tenant_id: string, limit?: number): Promise<InstancePoke[]>;
52
55
  /**
53
- * Instances stuck in `pending` for longer than `older_than_sec` — the residue of
54
- * a crash between `create()`'s commit and steve's (separate-connection) job
55
- * insert, i.e. rows no job will ever pick up.
56
+ * Instances stuck in `pending` for longer than `older_than_sec`: rows with no
57
+ * `start` advance left to move them. `retry()` enqueues once its transaction
58
+ * has committed, so a crash in between leaves one; so does a `start` job that
59
+ * was consumed without effect — claimed by a `Jobs` with no handler for it, or,
60
+ * on a queue with a database connection of its own, out of attempts before the
61
+ * transaction that created the row had committed.
56
62
  *
57
- * Only meaningful because `create()` is the sole producer of `pending`: every
58
- * other write path settles the row into a state this scan ignores. A row that is
59
- * merely waiting on a slow queue is re-poked too, harmlessly — the second
60
- * advance to reach it is fenced out.
63
+ * Only meaningful because `create()` and `retry()` are the sole producers of
64
+ * `pending`: every other write path settles the row into a state this scan
65
+ * ignores. A row that is merely waiting on a slow queue is re-poked too,
66
+ * harmlessly — the second advance to reach it is fenced out.
61
67
  */
62
- export declare function selectStalePending(exec: Executor, tenant_id: string, older_than_sec: number, limit?: number): Promise<InstancePoke[]>;
68
+ export declare function selectStalePending(db: Driver, tenant_id: string, older_than_sec: number, limit?: number): Promise<InstancePoke[]>;
63
69
  /**
64
70
  * Finds the live (non-terminal) instance owning this correlation token, if any.
65
71
  * Used by the inbox correlator — the instance may be in any live execution
@@ -70,7 +76,7 @@ export declare function selectStalePending(exec: Executor, tenant_id: string, ol
70
76
  * a violation deterministic (oldest wins) rather than arbitrary. Does not lock —
71
77
  * the advance re-reads under a lock and is fenced by `seq`.
72
78
  */
73
- export declare function findByCorrelation(exec: Executor, tenant_id: string, correlation_token: string): Promise<WorkflowInstanceRow | null>;
79
+ export declare function findByCorrelation(db: Driver, tenant_id: string, correlation_token: string): Promise<WorkflowInstanceRow | null>;
74
80
  /**
75
81
  * Finds the most recent terminal instance owning this correlation token, if any.
76
82
  * Only consulted when {@link findByCorrelation} misses, to tell "the instance is
@@ -79,5 +85,4 @@ export declare function findByCorrelation(exec: Executor, tenant_id: string, cor
79
85
  * Note that a *completed* or *cancelled* instance has its token cleared, so in
80
86
  * practice this finds the failed ones.
81
87
  */
82
- export declare function findTerminalByCorrelation(exec: Executor, tenant_id: string, correlation_token: string): Promise<WorkflowInstanceRow | null>;
83
- export {};
88
+ export declare function findTerminalByCorrelation(db: Driver, tenant_id: string, correlation_token: string): Promise<WorkflowInstanceRow | null>;
@@ -1,38 +1,53 @@
1
+ import { inList, insert, json, raw, sql, update } from "@marianmeres/sqlkit";
1
2
  import { EXECUTION_STATE, } from "../types.js";
2
- const SELECT_COLUMNS = `
3
- id, tenant_id, definition_id, definition_version,
4
- cursor, previous_cursor, context, execution_state,
5
- wake_at, correlation_token, seq, created_at, updated_at
6
- `;
3
+ const TABLE = "__workflow_instances";
4
+ /** Every column of a {@link WorkflowInstanceRow}, in the order a read returns them. */
5
+ const COLUMNS = [
6
+ "id",
7
+ "tenant_id",
8
+ "definition_id",
9
+ "definition_version",
10
+ "cursor",
11
+ "previous_cursor",
12
+ "context",
13
+ "execution_state",
14
+ "wake_at",
15
+ "correlation_token",
16
+ "seq",
17
+ "created_at",
18
+ "updated_at",
19
+ ];
20
+ const SELECT_COLUMNS = raw(COLUMNS.join(", "));
7
21
  /**
8
22
  * Inserts a new workflow instance row in `execution_state='pending'` at the
9
23
  * provided cursor (typically `def.fsm.initial`). Caller is responsible for
10
24
  * enqueuing the first `workflow.advance` job.
11
25
  */
12
- export async function createInstance(exec, input) {
13
- const r = await exec.query(`INSERT INTO __workflow_instances
14
- (tenant_id, definition_id, definition_version, cursor, context, execution_state, correlation_token)
15
- VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7)
16
- RETURNING ${SELECT_COLUMNS}`, [
17
- input.tenant_id,
18
- input.definition_id,
19
- input.definition_version,
20
- input.cursor,
21
- JSON.stringify(input.context),
22
- EXECUTION_STATE.PENDING,
23
- input.correlation_token ?? null,
24
- ]);
25
- return r.rows[0];
26
+ export async function createInstance(db, input) {
27
+ const { rows } = await db.query(insert(TABLE, {
28
+ tenant_id: input.tenant_id,
29
+ definition_id: input.definition_id,
30
+ definition_version: input.definition_version,
31
+ cursor: input.cursor,
32
+ context: json(input.context),
33
+ execution_state: EXECUTION_STATE.PENDING,
34
+ correlation_token: input.correlation_token ?? null,
35
+ }, { returning: COLUMNS }));
36
+ return rows[0];
26
37
  }
27
38
  /** Reads a workflow instance by id, or `null` if not found. No lock. */
28
- export async function findInstance(exec, id) {
29
- const r = await exec.query(`SELECT ${SELECT_COLUMNS} FROM __workflow_instances WHERE id = $1`, [id]);
30
- return r.rows[0] ?? null;
39
+ export async function findInstance(db, id) {
40
+ const { rows } = await db.query(sql `SELECT ${SELECT_COLUMNS} FROM __workflow_instances WHERE id = ${id}`);
41
+ return rows[0] ?? null;
31
42
  }
32
- /** Loads with a row-level lock — caller MUST be inside a transaction. */
33
- export async function lockInstance(client, id) {
34
- const r = await client.query(`SELECT ${SELECT_COLUMNS} FROM __workflow_instances WHERE id = $1 FOR UPDATE`, [id]);
35
- return r.rows[0] ?? null;
43
+ /**
44
+ * Loads with a row-level lock, held until the transaction this is called in ends
45
+ * — call it inside a `db.transaction()` callback. Outside one the statement is its
46
+ * own transaction, and the lock is gone the moment it returns.
47
+ */
48
+ export async function lockInstance(db, id) {
49
+ const { rows } = await db.query(sql `SELECT ${SELECT_COLUMNS} FROM __workflow_instances WHERE id = ${id} FOR UPDATE`);
50
+ return rows[0] ?? null;
36
51
  }
37
52
  /**
38
53
  * Partial-update of a workflow instance row. Only fields present in `patch`
@@ -42,41 +57,19 @@ export async function lockInstance(client, id) {
42
57
  * settle-point writes, so every job issued against the pre-write row becomes
43
58
  * recognizably stale.
44
59
  */
45
- export async function updateInstance(exec, id, patch, options = {}) {
46
- const sets = [];
47
- const values = [];
48
- let i = 1;
49
- if (patch.cursor !== undefined) {
50
- sets.push(`cursor = $${i++}`);
51
- values.push(patch.cursor);
52
- }
53
- if (patch.previous_cursor !== undefined) {
54
- sets.push(`previous_cursor = $${i++}`);
55
- values.push(patch.previous_cursor);
56
- }
57
- if (patch.context !== undefined) {
58
- sets.push(`context = $${i++}::jsonb`);
59
- values.push(JSON.stringify(patch.context));
60
- }
61
- if (patch.execution_state !== undefined) {
62
- sets.push(`execution_state = $${i++}`);
63
- values.push(patch.execution_state);
64
- }
65
- if (patch.wake_at !== undefined) {
66
- sets.push(`wake_at = $${i++}`);
67
- values.push(patch.wake_at);
68
- }
69
- if (patch.correlation_token !== undefined) {
70
- sets.push(`correlation_token = $${i++}`);
71
- values.push(patch.correlation_token);
72
- }
73
- if (options.bumpSeq)
74
- sets.push(`seq = seq + 1`);
75
- sets.push(`updated_at = now()`);
76
- values.push(id);
77
- const r = await exec.query(`UPDATE __workflow_instances SET ${sets.join(", ")} WHERE id = $${i}
78
- RETURNING ${SELECT_COLUMNS}`, values);
79
- return r.rows[0];
60
+ export async function updateInstance(db, id, patch, options = {}) {
61
+ // An `undefined` key is left out of the `SET` list; `null` is written as NULL.
62
+ const { rows } = await db.query(update(TABLE, {
63
+ cursor: patch.cursor,
64
+ previous_cursor: patch.previous_cursor,
65
+ context: patch.context === undefined ? undefined : json(patch.context),
66
+ execution_state: patch.execution_state,
67
+ wake_at: patch.wake_at,
68
+ correlation_token: patch.correlation_token,
69
+ seq: options.bumpSeq ? raw("seq + 1") : undefined,
70
+ updated_at: raw("now()"),
71
+ }, { id }, { returning: COLUMNS }));
72
+ return rows[0];
80
73
  }
81
74
  /**
82
75
  * Instances whose timer has expired. Read-only on purpose: the scheduler only
@@ -85,40 +78,43 @@ export async function updateInstance(exec, id, patch, options = {}) {
85
78
  * not yet advanced stays due and is poked again next tick; the fence turns the
86
79
  * duplicate into a no-op. Nothing is left stranded by a crash mid-tick.
87
80
  */
88
- export async function selectDueWakeUps(exec, tenant_id, limit = 100) {
89
- const r = await exec.query(`SELECT id, seq FROM __workflow_instances
90
- WHERE tenant_id = $1
91
- AND execution_state = $2
92
- AND wake_at IS NOT NULL
93
- AND wake_at <= now()
94
- ORDER BY wake_at
95
- LIMIT $3`, [tenant_id, EXECUTION_STATE.WAITING, limit]);
96
- return r.rows;
81
+ export async function selectDueWakeUps(db, tenant_id, limit = 100) {
82
+ const { rows } = await db.query(sql `SELECT id, seq FROM __workflow_instances
83
+ WHERE tenant_id = ${tenant_id}
84
+ AND execution_state = ${EXECUTION_STATE.WAITING}
85
+ AND wake_at IS NOT NULL
86
+ AND wake_at <= now()
87
+ ORDER BY wake_at
88
+ LIMIT ${limit}`);
89
+ return rows;
97
90
  }
98
91
  /**
99
- * Instances stuck in `pending` for longer than `older_than_sec` — the residue of
100
- * a crash between `create()`'s commit and steve's (separate-connection) job
101
- * insert, i.e. rows no job will ever pick up.
92
+ * Instances stuck in `pending` for longer than `older_than_sec`: rows with no
93
+ * `start` advance left to move them. `retry()` enqueues once its transaction
94
+ * has committed, so a crash in between leaves one; so does a `start` job that
95
+ * was consumed without effect — claimed by a `Jobs` with no handler for it, or,
96
+ * on a queue with a database connection of its own, out of attempts before the
97
+ * transaction that created the row had committed.
102
98
  *
103
- * Only meaningful because `create()` is the sole producer of `pending`: every
104
- * other write path settles the row into a state this scan ignores. A row that is
105
- * merely waiting on a slow queue is re-poked too, harmlessly — the second
106
- * advance to reach it is fenced out.
99
+ * Only meaningful because `create()` and `retry()` are the sole producers of
100
+ * `pending`: every other write path settles the row into a state this scan
101
+ * ignores. A row that is merely waiting on a slow queue is re-poked too,
102
+ * harmlessly — the second advance to reach it is fenced out.
107
103
  */
108
- export async function selectStalePending(exec, tenant_id, older_than_sec, limit = 100) {
109
- const r = await exec.query(`SELECT id, seq FROM __workflow_instances
110
- WHERE tenant_id = $1
111
- AND execution_state = $2
112
- AND updated_at < now() - make_interval(secs => $3::float8)
113
- ORDER BY updated_at
114
- LIMIT $4`, [tenant_id, EXECUTION_STATE.PENDING, older_than_sec, limit]);
115
- return r.rows;
104
+ export async function selectStalePending(db, tenant_id, older_than_sec, limit = 100) {
105
+ const { rows } = await db.query(sql `SELECT id, seq FROM __workflow_instances
106
+ WHERE tenant_id = ${tenant_id}
107
+ AND execution_state = ${EXECUTION_STATE.PENDING}
108
+ AND updated_at < now() - make_interval(secs => ${older_than_sec}::float8)
109
+ ORDER BY updated_at
110
+ LIMIT ${limit}`);
111
+ return rows;
116
112
  }
117
- const TERMINAL_STATES = [
113
+ const TERMINAL_STATES = inList([
118
114
  EXECUTION_STATE.COMPLETED,
119
115
  EXECUTION_STATE.FAILED,
120
116
  EXECUTION_STATE.CANCELLED,
121
- ];
117
+ ]);
122
118
  /**
123
119
  * Finds the live (non-terminal) instance owning this correlation token, if any.
124
120
  * Used by the inbox correlator — the instance may be in any live execution
@@ -129,14 +125,14 @@ const TERMINAL_STATES = [
129
125
  * a violation deterministic (oldest wins) rather than arbitrary. Does not lock —
130
126
  * the advance re-reads under a lock and is fenced by `seq`.
131
127
  */
132
- export async function findByCorrelation(exec, tenant_id, correlation_token) {
133
- const r = await exec.query(`SELECT ${SELECT_COLUMNS} FROM __workflow_instances
134
- WHERE tenant_id = $1
135
- AND correlation_token = $2
136
- AND NOT (execution_state = ANY($3))
137
- ORDER BY created_at
138
- LIMIT 1`, [tenant_id, correlation_token, TERMINAL_STATES]);
139
- return r.rows[0] ?? null;
128
+ export async function findByCorrelation(db, tenant_id, correlation_token) {
129
+ const { rows } = await db.query(sql `SELECT ${SELECT_COLUMNS} FROM __workflow_instances
130
+ WHERE tenant_id = ${tenant_id}
131
+ AND correlation_token = ${correlation_token}
132
+ AND execution_state NOT IN ${TERMINAL_STATES}
133
+ ORDER BY created_at
134
+ LIMIT 1`);
135
+ return rows[0] ?? null;
140
136
  }
141
137
  /**
142
138
  * Finds the most recent terminal instance owning this correlation token, if any.
@@ -146,12 +142,12 @@ export async function findByCorrelation(exec, tenant_id, correlation_token) {
146
142
  * Note that a *completed* or *cancelled* instance has its token cleared, so in
147
143
  * practice this finds the failed ones.
148
144
  */
149
- export async function findTerminalByCorrelation(exec, tenant_id, correlation_token) {
150
- const r = await exec.query(`SELECT ${SELECT_COLUMNS} FROM __workflow_instances
151
- WHERE tenant_id = $1
152
- AND correlation_token = $2
153
- AND execution_state = ANY($3)
154
- ORDER BY created_at DESC
155
- LIMIT 1`, [tenant_id, correlation_token, TERMINAL_STATES]);
156
- return r.rows[0] ?? null;
145
+ export async function findTerminalByCorrelation(db, tenant_id, correlation_token) {
146
+ const { rows } = await db.query(sql `SELECT ${SELECT_COLUMNS} FROM __workflow_instances
147
+ WHERE tenant_id = ${tenant_id}
148
+ AND correlation_token = ${correlation_token}
149
+ AND execution_state IN ${TERMINAL_STATES}
150
+ ORDER BY created_at DESC
151
+ LIMIT 1`);
152
+ return rows[0] ?? null;
157
153
  }
@@ -1,4 +1,4 @@
1
- import type { Handler, Matcher, WorkflowDefinition } from "./types.js";
1
+ import type { Handler, Matcher, WorkflowDefinition } from "./types.ts";
2
2
  /**
3
3
  * In-memory registry of definitions, handlers, and matchers. Built once at
4
4
  * startup; immutable after construction (use `Workflow`'s constructor).
@@ -1,5 +1,5 @@
1
1
  import type { Cron } from "@marianmeres/cron";
2
- import type { Workflow } from "./workflow.js";
2
+ import type { Workflow } from "./workflow.ts";
3
3
  /** Options accepted by {@link WorkflowScheduler}. */
4
4
  export interface WorkflowSchedulerOptions {
5
5
  /**
@@ -20,9 +20,10 @@ export interface WorkflowSchedulerOptions {
20
20
  tickName?: string;
21
21
  /**
22
22
  * Age in seconds at which a `pending` instance is assumed stranded and
23
- * re-poked with a fresh `start` advance. Covers the window between
24
- * `create()`'s commit and steve's job insert, which happens on its own
25
- * connection and can be lost to a crash. Default: 300. `0` disables the scan.
23
+ * re-poked with a fresh `start` advance. Covers a `start` advance that was
24
+ * lost: `retry()` enqueues after its commit, so a crash in between leaves the
25
+ * row with no job, and a job claimed by a `Jobs` that has no handler for it is
26
+ * consumed without effect. Default: 300. `0` disables the scan.
26
27
  */
27
28
  stalePendingSec?: number;
28
29
  }