@anatta.io/tva 0.1.0 → 0.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.
Files changed (75) hide show
  1. package/README.md +1 -1
  2. package/dist/adapters/cloudflare/index.d.ts +3 -3
  3. package/dist/adapters/cloudflare/index.js +2 -2
  4. package/dist/adapters/cloudflare/journal.d.ts +14 -11
  5. package/dist/adapters/cloudflare/journal.js +43 -23
  6. package/dist/adapters/cloudflare/{jobs.d.ts → pipelines.d.ts} +23 -23
  7. package/dist/adapters/cloudflare/{jobs.js → pipelines.js} +21 -21
  8. package/dist/adapters/cloudflare/workflow-pipelines.d.ts +66 -0
  9. package/dist/adapters/cloudflare/{workflow-jobs.js → workflow-pipelines.js} +46 -42
  10. package/dist/adapters/journal-records.d.ts +2 -1
  11. package/dist/adapters/journal-records.js +3 -2
  12. package/dist/adapters/memory/index.d.ts +1 -1
  13. package/dist/adapters/memory/index.js +1 -1
  14. package/dist/adapters/memory/journal.d.ts +5 -4
  15. package/dist/adapters/memory/journal.js +32 -13
  16. package/dist/adapters/memory/manifest.d.ts +1 -1
  17. package/dist/adapters/memory/manifest.js +1 -1
  18. package/dist/adapters/memory/{jobs.d.ts → pipelines.d.ts} +16 -16
  19. package/dist/adapters/memory/{jobs.js → pipelines.js} +6 -6
  20. package/dist/adapters/postgres/journal.d.ts +14 -11
  21. package/dist/adapters/postgres/journal.js +46 -23
  22. package/dist/adapters/postgres/manifest.d.ts +1 -1
  23. package/dist/adapters/postgres/manifest.js +1 -1
  24. package/dist/adapters/reference-executor.d.ts +26 -26
  25. package/dist/adapters/reference-executor.js +62 -57
  26. package/dist/contracts/index.d.ts +1 -1
  27. package/dist/contracts/index.js +1 -1
  28. package/dist/contracts/journal.d.ts +26 -16
  29. package/dist/contracts/manifest.d.ts +2 -2
  30. package/dist/contracts/{jobs.d.ts → pipelines.d.ts} +64 -51
  31. package/dist/pipelines/index.d.ts +1 -0
  32. package/dist/pipelines/index.js +2 -0
  33. package/dist/pipelines/pipeline.d.ts +142 -0
  34. package/dist/pipelines/pipeline.js +140 -0
  35. package/dist/pipelines/use-case-step.d.ts +24 -0
  36. package/dist/pipelines/use-case-step.js +34 -0
  37. package/dist/use-cases/index.d.ts +3 -0
  38. package/dist/use-cases/index.js +3 -0
  39. package/dist/use-cases/run-use-case.d.ts +33 -0
  40. package/dist/{actions/run-action.js → use-cases/run-use-case.js} +22 -18
  41. package/dist/{actions/action-consumer.d.ts → use-cases/use-case-consumer.d.ts} +11 -12
  42. package/dist/use-cases/use-case-consumer.js +98 -0
  43. package/dist/use-cases/use-case.d.ts +116 -0
  44. package/dist/use-cases/use-case.js +75 -0
  45. package/dist/webhooks/create-webhook-handler.d.ts +6 -6
  46. package/dist/webhooks/create-webhook-handler.js +32 -25
  47. package/dist/webhooks/dead-letter-consumer.d.ts +1 -1
  48. package/dist/webhooks/dead-letter-consumer.js +5 -5
  49. package/dist/webhooks/define-registry.d.ts +13 -13
  50. package/dist/webhooks/define-registry.js +15 -15
  51. package/dist/webhooks/once.d.ts +3 -3
  52. package/dist/webhooks/once.js +5 -5
  53. package/dist/webhooks/redact-customer-bodies.d.ts +1 -1
  54. package/dist/webhooks/redact-customer-bodies.js +1 -1
  55. package/dist/webhooks/replay-webhooks.d.ts +8 -8
  56. package/dist/webhooks/replay-webhooks.js +29 -26
  57. package/dist/webhooks/sweep-stuck-tasks.d.ts +32 -0
  58. package/dist/webhooks/sweep-stuck-tasks.js +73 -0
  59. package/dist/webhooks/webhook-consumer.d.ts +19 -18
  60. package/dist/webhooks/webhook-consumer.js +29 -24
  61. package/migrations/0012_rename_webhook_task_action_to_use_case.sql +11 -0
  62. package/migrations/0013_rename_job_tables_to_pipeline.sql +24 -0
  63. package/migrations/0016_add_webhook_task_requeues.sql +3 -0
  64. package/migrations/postgres/0012_rename_webhook_task_action_to_use_case.sql +5 -0
  65. package/migrations/postgres/0013_rename_job_tables_to_pipeline.sql +22 -0
  66. package/migrations/postgres/0016_add_webhook_task_requeues.sql +3 -0
  67. package/package.json +13 -6
  68. package/dist/actions/action-consumer.js +0 -90
  69. package/dist/actions/action.d.ts +0 -67
  70. package/dist/actions/action.js +0 -12
  71. package/dist/actions/index.d.ts +0 -3
  72. package/dist/actions/index.js +0 -4
  73. package/dist/actions/run-action.d.ts +0 -31
  74. package/dist/adapters/cloudflare/workflow-jobs.d.ts +0 -57
  75. /package/dist/contracts/{jobs.js → pipelines.js} +0 -0
@@ -17,8 +17,9 @@ const TOOL = 'journal';
17
17
  * failuresByReason journal_units_recorded_at
18
18
  * delivery webhook_deliveries_pkey, webhook_tasks_pkey
19
19
  * deadTasks webhook_tasks_state
20
- * deadTasksByAction webhook_tasks_action_state
20
+ * deadTasksByUseCase webhook_tasks_use_case_state
21
21
  * stuckTasks webhook_tasks_state
22
+ * reclaimStuckTask webhook_tasks_pkey or webhook_tasks_action_state
22
23
  */
23
24
  const Q = {
24
25
  startRun: `
@@ -100,34 +101,46 @@ const Q = {
100
101
  VALUES ($1, $2, $3, $4, $5, $6, $7)
101
102
  ON CONFLICT (delivery_id) DO NOTHING
102
103
  )
103
- INSERT INTO webhook_tasks (delivery_id, action, state, updated_at)
104
- SELECT $1, action, 'received', $7 FROM unnest($8::text[]) AS action
105
- ON CONFLICT (delivery_id, action) DO NOTHING
104
+ INSERT INTO webhook_tasks (delivery_id, use_case, state, updated_at)
105
+ SELECT $1, use_case, 'received', $7 FROM unnest($8::text[]) AS use_case
106
+ ON CONFLICT (delivery_id, use_case) DO NOTHING
106
107
  `,
107
108
  // $5 is the states TASK_TRANSITIONS allows the move from.
108
109
  moveTask: `
109
- UPDATE webhook_tasks SET state = $3, updated_at = $4, reason_code = $6
110
- WHERE delivery_id = $1 AND action = $2 AND state = ANY($5::text[])
110
+ UPDATE webhook_tasks SET state = $3, updated_at = $4, reason_code = $6,
111
+ requeues = CASE WHEN $3 = 'replayed' THEN 0 ELSE requeues END
112
+ WHERE delivery_id = $1 AND use_case = $2 AND state = ANY($5::text[])
111
113
  `,
112
114
  delivery: `SELECT * FROM webhook_deliveries WHERE delivery_id = $1`,
113
115
  tasksForDelivery: `
114
- SELECT * FROM webhook_tasks WHERE delivery_id = $1 ORDER BY action
116
+ SELECT * FROM webhook_tasks WHERE delivery_id = $1 ORDER BY use_case
115
117
  `,
116
118
  deadTasks: `
117
119
  SELECT * FROM webhook_tasks
118
- WHERE state = 'dead' AND (updated_at, delivery_id, action) > ($1, $2, $3)
119
- ORDER BY updated_at, delivery_id, action LIMIT $4
120
+ WHERE state = 'dead' AND (updated_at, delivery_id, use_case) > ($1, $2, $3)
121
+ ORDER BY updated_at, delivery_id, use_case LIMIT $4
120
122
  `,
121
- deadTasksByAction: `
123
+ deadTasksByUseCase: `
122
124
  SELECT * FROM webhook_tasks
123
- WHERE action = $5 AND state = 'dead'
124
- AND (updated_at, delivery_id, action) > ($1, $2, $3)
125
+ WHERE use_case = $5 AND state = 'dead'
126
+ AND (updated_at, delivery_id, use_case) > ($1, $2, $3)
125
127
  ORDER BY updated_at, delivery_id LIMIT $4
126
128
  `,
127
129
  stuckTasks: `
128
130
  SELECT * FROM webhook_tasks
129
- WHERE state IN ('received', 'processing') AND updated_at < $1
130
- ORDER BY updated_at, delivery_id, action LIMIT $2
131
+ WHERE state IN ('received', 'processing', 'replayed') AND updated_at < $1
132
+ ORDER BY updated_at, delivery_id, use_case LIMIT $2
133
+ `,
134
+ // The state and updated_at the sweeper read are re-checked in the write, so
135
+ // a task that moved since, or another sweeper's claim, makes it change no row.
136
+ reclaimStuckTask: `
137
+ UPDATE webhook_tasks SET
138
+ updated_at = $5,
139
+ state = CASE WHEN $4 = 'dead' THEN 'dead' ELSE state END,
140
+ reason_code = CASE WHEN $4 = 'dead' THEN 'stuck' ELSE reason_code END,
141
+ requeues = CASE WHEN $4 = 'dead' THEN requeues ELSE requeues + 1 END
142
+ WHERE delivery_id = $1 AND use_case = $2 AND updated_at = $3
143
+ AND state IN ('received', 'processing', 'replayed')
131
144
  `,
132
145
  };
133
146
  export class PostgresJournal {
@@ -255,7 +268,7 @@ export class PostgresJournal {
255
268
  const { rows } = await this.#call('recentRuns', async () => this.o.pool.query(Q.recentRuns, [limit]));
256
269
  return rows.map(toRunRow);
257
270
  }
258
- async recordDelivery(delivery, actions) {
271
+ async recordDelivery(delivery, useCases) {
259
272
  await this.#call('recordDelivery', async () => this.o.pool.query(Q.recordDelivery, [
260
273
  delivery.deliveryId,
261
274
  delivery.source,
@@ -264,13 +277,13 @@ export class PostgresJournal {
264
277
  delivery.webhookId,
265
278
  delivery.bodyKey,
266
279
  delivery.receivedAt,
267
- actions,
280
+ useCases,
268
281
  ]));
269
282
  }
270
- async moveTask(deliveryId, action, to, at, reasonCode) {
283
+ async moveTask(deliveryId, useCase, to, at, reasonCode) {
271
284
  const { rowCount } = await this.#call('moveTask', async () => this.o.pool.query(Q.moveTask, [
272
285
  deliveryId,
273
- action,
286
+ useCase,
274
287
  to,
275
288
  at,
276
289
  TASK_TRANSITIONS[to],
@@ -288,13 +301,13 @@ export class PostgresJournal {
288
301
  ? undefined
289
302
  : { delivery: toDeliveryRow(record), tasks: tasks.rows.map(toTaskRow) };
290
303
  }
291
- async deadTasks({ action, after = FIRST_TASK, limit = DEFAULT_UNIT_LIMIT, } = {}) {
292
- const cursor = [after.updatedAt, after.deliveryId, after.action, limit];
293
- const { rows } = await this.#call('deadTasks', async () => action === undefined
304
+ async deadTasks({ useCase, after = FIRST_TASK, limit = DEFAULT_UNIT_LIMIT, } = {}) {
305
+ const cursor = [after.updatedAt, after.deliveryId, after.useCase, limit];
306
+ const { rows } = await this.#call('deadTasks', async () => useCase === undefined
294
307
  ? this.o.pool.query(Q.deadTasks, cursor)
295
- : this.o.pool.query(Q.deadTasksByAction, [
308
+ : this.o.pool.query(Q.deadTasksByUseCase, [
296
309
  ...cursor,
297
- action,
310
+ useCase,
298
311
  ]));
299
312
  return rows.map(toTaskRow);
300
313
  }
@@ -302,6 +315,16 @@ export class PostgresJournal {
302
315
  const { rows } = await this.#call('stuckTasks', async () => this.o.pool.query(Q.stuckTasks, [before, limit]));
303
316
  return rows.map(toTaskRow);
304
317
  }
318
+ async reclaimStuckTask(task, at, to) {
319
+ const { rowCount } = await this.#call('reclaimStuckTask', async () => this.o.pool.query(Q.reclaimStuckTask, [
320
+ task.deliveryId,
321
+ task.useCase,
322
+ task.updatedAt,
323
+ to,
324
+ at,
325
+ ]));
326
+ return rowCount === 1;
327
+ }
305
328
  async #call(operation, f) {
306
329
  try {
307
330
  return await f();
@@ -43,7 +43,7 @@ export declare const POSTGRES_MANIFEST: {
43
43
  readonly scheduleMinIntervalSeconds: 1;
44
44
  /**
45
45
  * 1 MiB, the same as Workflows and the memory adapter. This target has no
46
- * Jobs executor yet. When it has one, a result is TEXT like every JSON
46
+ * Pipelines executor yet. When it has one, a result is TEXT like every JSON
47
47
  * column here (decision 0007), which holds about 1 GB, so this is the
48
48
  * library's limit, not Postgres's. A larger one would let a step pass on
49
49
  * Postgres and fail on Workflows.
@@ -44,7 +44,7 @@ export const POSTGRES_MANIFEST = {
44
44
  scheduleMinIntervalSeconds: 1,
45
45
  /**
46
46
  * 1 MiB, the same as Workflows and the memory adapter. This target has no
47
- * Jobs executor yet. When it has one, a result is TEXT like every JSON
47
+ * Pipelines executor yet. When it has one, a result is TEXT like every JSON
48
48
  * column here (decision 0007), which holds about 1 GB, so this is the
49
49
  * library's limit, not Postgres's. A larger one would let a step pass on
50
50
  * Postgres and fail on Workflows.
@@ -1,9 +1,9 @@
1
- import type { Clock, DispatchOptions, DispatchResult, Exhaustion, Instant, Job, JobInstanceId, JobRegistration, JobStatus, Jobs, Journal, JsonValue, Logger, Queue, QueueBatch, ToolManifest } from '../contracts/index.js';
1
+ import type { Clock, DispatchOptions, DispatchResult, Exhaustion, Instant, PipelineDefinition, PipelineInstanceId, PipelineRegistration, PipelineStatus, Pipelines, Journal, JsonValue, Logger, Queue, QueueBatch, ToolManifest } from '../contracts/index.js';
2
2
  /**
3
3
  * THE REFERENCE EXECUTOR'S ALGORITHM, ONCE, FOR EVERY ADAPTER THAT SHIPS IT.
4
4
  *
5
5
  * docs/decisions/0006 is the specification. This file is that protocol and
6
- * nothing else: every adapter that runs Jobs without a native executor (the
6
+ * nothing else: every adapter that runs Pipelines without a native executor (the
7
7
  * memory adapter, D1 on Cloudflare, Postgres later) builds this class over its
8
8
  * own `ReferenceStore` and its own queue. Two executors that share a name but
9
9
  * not an algorithm double the bugs (#69), so the storage is the only thing an
@@ -14,14 +14,14 @@ import type { Clock, DispatchOptions, DispatchResult, Exhaustion, Instant, Job,
14
14
  */
15
15
  /** A wake-up. The state tables are the truth; a message only says "look". */
16
16
  export type WakeUp = {
17
- readonly instanceId: JobInstanceId;
17
+ readonly instanceId: PipelineInstanceId;
18
18
  readonly stepIndex: number;
19
19
  };
20
- /** The `status` column of `job_instances` (decision 0006). */
20
+ /** The `status` column of `pipeline_instances` (decision 0006). */
21
21
  export type InstanceState = 'running' | 'failing' | 'completed' | 'failed';
22
22
  /**
23
- * One row of `job_instances`. Times are epoch milliseconds from the injected
24
- * `Clock`. `input` is the Job input as JSON.
23
+ * One row of `pipeline_instances`. Times are epoch milliseconds from the injected
24
+ * `Clock`. `input` is the Pipeline input as JSON.
25
25
  *
26
26
  * `cause` is not one of decision 0006's columns. Without it the exhaustion
27
27
  * handler cannot be told whether a step was terminal, ran out of retries or
@@ -29,8 +29,8 @@ export type InstanceState = 'running' | 'failing' | 'completed' | 'failed';
29
29
  * only when the cause is `terminal`.
30
30
  */
31
31
  export type InstanceRow = {
32
- readonly instanceId: JobInstanceId;
33
- readonly job: string;
32
+ readonly instanceId: PipelineInstanceId;
33
+ readonly pipeline: string;
34
34
  readonly input: string;
35
35
  readonly runId: string;
36
36
  readonly unitKey: string;
@@ -49,15 +49,15 @@ export type InstanceRow = {
49
49
  export type InstanceChange = Partial<Pick<InstanceRow, 'status' | 'cause' | 'reasonCode' | 'currentStep' | 'attempts' | 'leaseExpiresAt' | 'nextWakeAt' | 'endedAt'>>;
50
50
  /**
51
51
  * THE ONLY THING AN ADAPTER IMPLEMENTS. The two tables of decision 0006,
52
- * `job_instances` and `job_steps`, behind the writes the protocol makes.
52
+ * `pipeline_instances` and `pipeline_steps`, behind the writes the protocol makes.
53
53
  *
54
54
  * This is not a tool and has no conformance suite of its own: 0006 rejected a
55
- * `JobStore` tool, and the Jobs suite tests it through the executor. It is
55
+ * `PipelineStore` tool, and the Pipelines suite tests it through the executor. It is
56
56
  * the seam that keeps the algorithm in one place.
57
57
  *
58
58
  * NO ADAPTER NEEDS A TRANSACTION. Every method but two writes one table.
59
59
  * `remove` and `removeEndedBefore` write both, and each one deletes in a fixed
60
- * order: the `job_steps` rows first, then the `job_instances` row, both only
60
+ * order: the `pipeline_steps` rows first, then the `pipeline_instances` row, both only
61
61
  * for an instance whose `ended_at` is at or before the cutoff. A crash between
62
62
  * the two deletes leaves an ended instance with no stored results, which the
63
63
  * next removal deletes. A new instance cannot take the id while the old
@@ -68,35 +68,35 @@ export type InstanceChange = Partial<Pick<InstanceRow, 'status' | 'cause' | 'rea
68
68
  export interface ReferenceStore {
69
69
  /** Inserts the row, or reports that its id is already taken. */
70
70
  insert(row: InstanceRow): Promise<'inserted' | 'exists'>;
71
- get(id: JobInstanceId): Promise<InstanceRow | undefined>;
71
+ get(id: PipelineInstanceId): Promise<InstanceRow | undefined>;
72
72
  /**
73
73
  * `UPDATE … WHERE instance_id = ? AND version = ?`, which also sets
74
74
  * `version = version + 1`. Exactly one more: the executor computes the
75
75
  * row's next version itself and conditions its next write on it. False
76
76
  * when the version did not match: another consumer won.
77
77
  */
78
- update(id: JobInstanceId, version: number, change: InstanceChange): Promise<boolean>;
78
+ update(id: PipelineInstanceId, version: number, change: InstanceChange): Promise<boolean>;
79
79
  /**
80
80
  * Deletes the instance and its stored results if it ended at or before
81
- * `cutoff`: the `job_steps` rows first, then the instance row (above). Used
81
+ * `cutoff`: the `pipeline_steps` rows first, then the instance row (above). Used
82
82
  * only for an instance whose retention has passed.
83
83
  */
84
- remove(id: JobInstanceId, cutoff: Instant): Promise<void>;
84
+ remove(id: PipelineInstanceId, cutoff: Instant): Promise<void>;
85
85
  /**
86
- * `INSERT OR IGNORE` into `job_steps`: the first result stored for a step
86
+ * `INSERT OR IGNORE` into `pipeline_steps`: the first result stored for a step
87
87
  * is the one that stays. `result` is the step result as JSON.
88
88
  */
89
- storeResult(id: JobInstanceId, stepIndex: number, result: string, completedAt: Instant): Promise<void>;
89
+ storeResult(id: PipelineInstanceId, stepIndex: number, result: string, completedAt: Instant): Promise<void>;
90
90
  /** The stored results of the instance, as JSON, by step index. */
91
- results(id: JobInstanceId): Promise<ReadonlyMap<number, string>>;
91
+ results(id: PipelineInstanceId): Promise<ReadonlyMap<number, string>>;
92
92
  /**
93
93
  * `status IN ('running', 'failing') AND next_wake_at <= now AND
94
94
  * (lease_expires_at IS NULL OR lease_expires_at <= now)`.
95
95
  */
96
96
  due(now: Instant): Promise<readonly InstanceRow[]>;
97
97
  /**
98
- * Instances with `ended_at <= cutoff`, with their `job_steps` rows: the
99
- * `job_steps` rows first, then the instance rows (above).
98
+ * Instances with `ended_at <= cutoff`, with their `pipeline_steps` rows: the
99
+ * `pipeline_steps` rows first, then the instance rows (above).
100
100
  */
101
101
  removeEndedBefore(cutoff: Instant): Promise<void>;
102
102
  }
@@ -112,11 +112,11 @@ export type ExecutorWindow = 'after-dispatch-insert' | 'before-result-stored' |
112
112
  * code passes nothing.
113
113
  */
114
114
  export type Interrupt = (window: ExecutorWindow, at: {
115
- readonly instanceId: JobInstanceId;
115
+ readonly instanceId: PipelineInstanceId;
116
116
  readonly stepIndex: number;
117
117
  }) => Promise<void> | undefined;
118
118
  export type ReferenceExecutorOptions = {
119
- readonly registrations: readonly JobRegistration[];
119
+ readonly registrations: readonly PipelineRegistration[];
120
120
  readonly store: ReferenceStore;
121
121
  readonly queue: Queue<WakeUp>;
122
122
  readonly clock: Clock;
@@ -145,16 +145,16 @@ export declare const HANDLER_LEASE_MS: number;
145
145
  */
146
146
  export declare const HANDLER_RETRY_MS = 60000;
147
147
  /**
148
- * `Jobs` over a `ReferenceStore` and a queue of wake-ups, by the protocol of
148
+ * `Pipelines` over a `ReferenceStore` and a queue of wake-ups, by the protocol of
149
149
  * docs/decisions/0006. The adapter delivers the queue's batches to `consume`
150
150
  * and calls `sweep` on a schedule.
151
151
  */
152
- export declare class ReferenceExecutor implements Jobs {
152
+ export declare class ReferenceExecutor implements Pipelines {
153
153
  #private;
154
154
  private readonly o;
155
155
  constructor(o: ReferenceExecutorOptions);
156
- dispatch<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps>(definition: Job<Input, Results, Deps>, input: Input, options: DispatchOptions): Promise<DispatchResult>;
157
- status(id: JobInstanceId): Promise<JobStatus>;
156
+ dispatch<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps>(definition: PipelineDefinition<Input, Results, Deps>, input: Input, options: DispatchOptions): Promise<DispatchResult>;
157
+ status(id: PipelineInstanceId): Promise<PipelineStatus>;
158
158
  /**
159
159
  * THE QUEUE CONSUMER. Each message is acknowledged or retried on its own.
160
160
  * A message whose handling throws is neither, so the queue redelivers it:
@@ -62,68 +62,68 @@ function backoffMs(retries, n) {
62
62
  * `Infinity`, would set `next_wake_at` to a value no sweep ever reaches, and
63
63
  * the instance would stay `running` for ever.
64
64
  */
65
- function checkSteps(job) {
65
+ function checkSteps(pipeline) {
66
66
  const names = new Set();
67
- for (const step of job.steps) {
68
- const where = `Job ${job.name}, step ${JSON.stringify(step.name)}`;
67
+ for (const step of pipeline.steps) {
68
+ const where = `Pipeline ${pipeline.name}, step ${JSON.stringify(step.name)}`;
69
69
  if (names.has(step.name)) {
70
- throw new Misconfigured('jobs', `${where}: the name is used twice`);
70
+ throw new Misconfigured('pipelines', `${where}: the name is used twice`);
71
71
  }
72
72
  names.add(step.name);
73
73
  const { limit, delaySeconds } = step.retries;
74
74
  if (!Number.isInteger(limit) || limit < 0) {
75
- throw new Misconfigured('jobs', `${where}: retries.limit must be an integer of 0 or more`);
75
+ throw new Misconfigured('pipelines', `${where}: retries.limit must be an integer of 0 or more`);
76
76
  }
77
77
  if (!Number.isFinite(delaySeconds) || delaySeconds < 0) {
78
- throw new Misconfigured('jobs', `${where}: retries.delaySeconds must be a finite number of 0 or more`);
78
+ throw new Misconfigured('pipelines', `${where}: retries.delaySeconds must be a finite number of 0 or more`);
79
79
  }
80
80
  if (limit > 0 && !Number.isFinite(backoffMs(step.retries, limit))) {
81
- throw new Misconfigured('jobs', `${where}: the backoff before retry ${limit} is not a finite delay`);
81
+ throw new Misconfigured('pipelines', `${where}: the backoff before retry ${limit} is not a finite delay`);
82
82
  }
83
83
  if (!Number.isFinite(step.timeoutSeconds) || step.timeoutSeconds <= 0) {
84
- throw new Misconfigured('jobs', `${where}: timeoutSeconds must be a finite number above 0`);
84
+ throw new Misconfigured('pipelines', `${where}: timeoutSeconds must be a finite number above 0`);
85
85
  }
86
86
  }
87
87
  }
88
88
  const bytes = (json) => new TextEncoder().encode(json).byteLength;
89
89
  /**
90
- * `Jobs` over a `ReferenceStore` and a queue of wake-ups, by the protocol of
90
+ * `Pipelines` over a `ReferenceStore` and a queue of wake-ups, by the protocol of
91
91
  * docs/decisions/0006. The adapter delivers the queue's batches to `consume`
92
92
  * and calls `sweep` on a schedule.
93
93
  */
94
94
  export class ReferenceExecutor {
95
95
  o;
96
- #jobs = new Map();
96
+ #pipelines = new Map();
97
97
  constructor(o) {
98
98
  this.o = o;
99
99
  for (const registration of o.registrations) {
100
- const job = unpack(registration);
100
+ const pipeline = unpack(registration);
101
101
  // Refused when the executor is built, not at the first dispatch: a bad
102
- // name is a defect in the definition (rule 7, `Job.name`).
103
- if (!NAME.test(job.name)) {
104
- throw new LimitExceeded('jobs', `Job name ${JSON.stringify(job.name)} must be 1 to 64 characters of [A-Za-z0-9_]`);
102
+ // name is a defect in the definition (rule 7, `PipelineDefinition.name`).
103
+ if (!NAME.test(pipeline.name)) {
104
+ throw new LimitExceeded('pipelines', `Pipeline name ${JSON.stringify(pipeline.name)} must be 1 to 64 characters of [A-Za-z0-9_]`);
105
105
  }
106
- if (this.#jobs.has(job.name)) {
107
- throw new Misconfigured('jobs', `Job name ${job.name} is registered twice`);
106
+ if (this.#pipelines.has(pipeline.name)) {
107
+ throw new Misconfigured('pipelines', `Pipeline name ${pipeline.name} is registered twice`);
108
108
  }
109
- checkSteps(job);
110
- this.#jobs.set(job.name, job);
109
+ checkSteps(pipeline);
110
+ this.#pipelines.set(pipeline.name, pipeline);
111
111
  }
112
112
  }
113
113
  async dispatch(definition, input, options) {
114
- const job = this.#jobs.get(definition.name);
115
- if (job === undefined) {
116
- throw new Misconfigured('jobs', `Job ${definition.name} is not registered with this executor`);
114
+ const pipeline = this.#pipelines.get(definition.name);
115
+ if (pipeline === undefined) {
116
+ throw new Misconfigured('pipelines', `Pipeline ${definition.name} is not registered with this executor`);
117
117
  }
118
- const key = job.key(input);
119
- const id = `${job.name}-${key}`;
118
+ const key = pipeline.key(input);
119
+ const id = `${pipeline.name}-${key}`;
120
120
  if (!KEY.test(key) || id.length > ID_MAX) {
121
- throw new LimitExceeded('jobs', `key ${JSON.stringify(key)} must be [A-Za-z0-9_-], at least one character, and fit an id of ${ID_MAX}`);
121
+ throw new LimitExceeded('pipelines', `key ${JSON.stringify(key)} must be [A-Za-z0-9_-], at least one character, and fit an id of ${ID_MAX}`);
122
122
  }
123
123
  const now = this.o.clock.now();
124
124
  const row = {
125
125
  instanceId: id,
126
- job: job.name,
126
+ pipeline: pipeline.name,
127
127
  input: JSON.stringify(input),
128
128
  runId: options.runId,
129
129
  unitKey: key,
@@ -183,7 +183,7 @@ export class ReferenceExecutor {
183
183
  }
184
184
  }
185
185
  catch (error) {
186
- this.o.logger.error('jobs: wake-up failed, left for redelivery', {
186
+ this.o.logger.error('pipelines: wake-up failed, left for redelivery', {
187
187
  instanceId: message.body.instanceId,
188
188
  stepIndex: message.body.stepIndex,
189
189
  error: String(error),
@@ -246,15 +246,15 @@ export class ReferenceExecutor {
246
246
  if (row.leaseExpiresAt !== null && row.leaseExpiresAt > now) {
247
247
  return undefined;
248
248
  }
249
- const job = this.#jobs.get(row.job);
250
- if (job === undefined) {
251
- this.o.logger.error('jobs: no registration for an instance', {
249
+ const pipeline = this.#pipelines.get(row.pipeline);
250
+ if (pipeline === undefined) {
251
+ this.o.logger.error('pipelines: no registration for an instance', {
252
252
  instanceId,
253
- job: row.job,
253
+ pipeline: row.pipeline,
254
254
  });
255
255
  return undefined;
256
256
  }
257
- const step = job.steps[row.currentStep];
257
+ const step = pipeline.steps[row.currentStep];
258
258
  const leaseMs = row.status === 'failing' || step === undefined
259
259
  ? HANDLER_LEASE_MS
260
260
  : (step.timeoutSeconds + 60) * 1000;
@@ -271,18 +271,18 @@ export class ReferenceExecutor {
271
271
  return undefined;
272
272
  }
273
273
  if (leased.status === 'failing') {
274
- await this.#runHandler(job, leased);
274
+ await this.#runHandler(pipeline, leased);
275
275
  }
276
276
  else {
277
- await this.#runStep(job, leased);
277
+ await this.#runStep(pipeline, leased);
278
278
  }
279
279
  return undefined;
280
280
  }
281
- async #base(row, job) {
281
+ async #base(row, pipeline) {
282
282
  const stored = await this.o.store.results(row.instanceId);
283
283
  const results = {};
284
284
  for (const [index, json] of [...stored].sort(([a], [b]) => a - b)) {
285
- const name = job.steps[index]?.name;
285
+ const name = pipeline.steps[index]?.name;
286
286
  if (name !== undefined && index < row.currentStep) {
287
287
  results[name] = JSON.parse(json);
288
288
  }
@@ -293,24 +293,29 @@ export class ReferenceExecutor {
293
293
  unitKey: row.unitKey,
294
294
  input: JSON.parse(row.input),
295
295
  results,
296
+ toolkit: {
297
+ journal: this.o.journal,
298
+ clock: this.o.clock,
299
+ logger: this.o.logger,
300
+ },
296
301
  };
297
302
  }
298
- async #runStep(job, row) {
303
+ async #runStep(pipeline, row) {
299
304
  const index = row.currentStep;
300
- const step = job.steps[index];
305
+ const step = pipeline.steps[index];
301
306
  if (step === undefined) {
302
- // A Job with no steps left completes. Only an empty Job gets here.
303
- await this.#advance(job, row, undefined);
307
+ // A Pipeline with no steps left completes. Only an empty Pipeline gets here.
308
+ await this.#advance(pipeline, row, undefined);
304
309
  return;
305
310
  }
306
311
  // The step completed but the instance did not advance: a crash between
307
312
  // the result write and the advance. Do not run it again.
308
313
  const stored = (await this.o.store.results(row.instanceId)).get(index);
309
314
  if (stored !== undefined) {
310
- await this.#advance(job, row, undefined);
315
+ await this.#advance(pipeline, row, undefined);
311
316
  return;
312
317
  }
313
- const base = await this.#base(row, job);
318
+ const base = await this.#base(row, pipeline);
314
319
  const started = this.o.clock.now();
315
320
  const attempt = await this.#attempt(step, base, started);
316
321
  const durationMs = this.o.clock.now() - started;
@@ -321,7 +326,7 @@ export class ReferenceExecutor {
321
326
  await this.o.interrupt?.('before-result-stored', window);
322
327
  await this.o.store.storeResult(row.instanceId, index, attempt.result, this.o.clock.now());
323
328
  await this.o.interrupt?.('after-result-stored', window);
324
- await this.#advance(job, row, record);
329
+ await this.#advance(pipeline, row, record);
325
330
  return;
326
331
  }
327
332
  case 'fault': {
@@ -337,7 +342,7 @@ export class ReferenceExecutor {
337
342
  return;
338
343
  }
339
344
  await record('retry', attempt.reasonCode);
340
- this.o.logger.warn('jobs: step faulted, retrying', {
345
+ this.o.logger.warn('pipelines: step faulted, retrying', {
341
346
  instanceId: row.instanceId,
342
347
  step: step.name,
343
348
  attempt: row.attempts,
@@ -399,7 +404,7 @@ export class ReferenceExecutor {
399
404
  if (size > this.o.manifest.stepResultMaxBytes) {
400
405
  // Rule 7: the executor enforces the manifest. The same input gives the
401
406
  // same result, so this is terminal, not a fault.
402
- const error = new LimitExceeded('jobs', `step ${step.name} returned ${size} bytes, above stepResultMaxBytes ${this.o.manifest.stepResultMaxBytes}`);
407
+ const error = new LimitExceeded('pipelines', `step ${step.name} returned ${size} bytes, above stepResultMaxBytes ${this.o.manifest.stepResultMaxBytes}`);
403
408
  this.o.logger.error(error.message, { instanceId: base.instanceId });
404
409
  return {
405
410
  kind: 'exhausted',
@@ -412,9 +417,9 @@ export class ReferenceExecutor {
412
417
  * Write 2 of a success: advance, or complete on the last step. Then the
413
418
  * next wake-up. `record` is set when this consumer ran the step.
414
419
  */
415
- async #advance(job, row, record) {
420
+ async #advance(pipeline, row, record) {
416
421
  const index = row.currentStep;
417
- const last = index + 1 >= job.steps.length;
422
+ const last = index + 1 >= pipeline.steps.length;
418
423
  const now = this.o.clock.now();
419
424
  const won = await this.o.store.update(row.instanceId, row.version, last
420
425
  ? {
@@ -430,12 +435,12 @@ export class ReferenceExecutor {
430
435
  nextWakeAt: now,
431
436
  });
432
437
  if (!won) {
433
- await this.#superseded(row, job.steps[index]?.name ?? '', record);
438
+ await this.#superseded(row, pipeline.steps[index]?.name ?? '', record);
434
439
  return;
435
440
  }
436
441
  await record?.('ok');
437
442
  if (last) {
438
- this.o.logger.info('jobs: instance completed', {
443
+ this.o.logger.info('pipelines: instance completed', {
439
444
  instanceId: row.instanceId,
440
445
  });
441
446
  return;
@@ -465,7 +470,7 @@ export class ReferenceExecutor {
465
470
  }
466
471
  const reasonCode = exhaustion.cause === 'terminal' ? exhaustion.reasonCode : exhaustion.cause;
467
472
  await record('failed', reasonCode);
468
- this.o.logger.error('jobs: step failed, running the exhaustion handler', {
473
+ this.o.logger.error('pipelines: step failed, running the exhaustion handler', {
469
474
  instanceId: row.instanceId,
470
475
  step,
471
476
  cause: exhaustion.cause,
@@ -485,21 +490,21 @@ export class ReferenceExecutor {
485
490
  * `failed`. A crash before that write runs the handler again, so it runs
486
491
  * at least once and never after `failed`.
487
492
  */
488
- async #runHandler(job, row) {
489
- const step = job.steps[row.currentStep]?.name ?? '';
493
+ async #runHandler(pipeline, row) {
494
+ const step = pipeline.steps[row.currentStep]?.name ?? '';
490
495
  const exhaustion = row.cause === 'terminal'
491
496
  ? { step, cause: 'terminal', reasonCode: row.reasonCode ?? '' }
492
497
  : { step, cause: row.cause ?? 'retries-exhausted' };
493
- if (job.onExhausted !== undefined) {
498
+ if (pipeline.onExhausted !== undefined) {
494
499
  try {
495
- await job.onExhausted(await this.#base(row, job), exhaustion);
500
+ await pipeline.onExhausted(await this.#base(row, pipeline), exhaustion);
496
501
  }
497
502
  catch (error) {
498
503
  const won = await this.o.store.update(row.instanceId, row.version, {
499
504
  leaseExpiresAt: null,
500
505
  nextWakeAt: fromEpochMs(this.o.clock.now() + HANDLER_RETRY_MS),
501
506
  });
502
- this.o.logger.error('jobs: exhaustion handler threw, running it again', {
507
+ this.o.logger.error('pipelines: exhaustion handler threw, running it again', {
503
508
  instanceId: row.instanceId,
504
509
  attempt: row.attempts,
505
510
  error: String(error),
@@ -517,7 +522,7 @@ export class ReferenceExecutor {
517
522
  leaseExpiresAt: null,
518
523
  });
519
524
  if (won) {
520
- this.o.logger.info('jobs: instance failed', {
525
+ this.o.logger.info('pipelines: instance failed', {
521
526
  instanceId: row.instanceId,
522
527
  });
523
528
  }
@@ -528,7 +533,7 @@ export class ReferenceExecutor {
528
533
  */
529
534
  async #superseded(row, step, record) {
530
535
  await record?.('superseded', 'superseded');
531
- this.o.logger.info('jobs: superseded by another consumer', {
536
+ this.o.logger.info('pipelines: superseded by another consumer', {
532
537
  instanceId: row.instanceId,
533
538
  step,
534
539
  });
@@ -554,7 +559,7 @@ export class ReferenceExecutor {
554
559
  });
555
560
  }
556
561
  catch (error) {
557
- this.o.logger.warn('jobs: step row not written', {
562
+ this.o.logger.warn('pipelines: step row not written', {
558
563
  instanceId: row.instanceId,
559
564
  step,
560
565
  error: String(error),
@@ -8,7 +8,7 @@ export * from './ledger.js';
8
8
  export * from './cache.js';
9
9
  export * from './blob-store.js';
10
10
  export * from './journal.js';
11
- export * from './jobs.js';
11
+ export * from './pipelines.js';
12
12
  export * from './logger.js';
13
13
  export * from './session-storage.js';
14
14
  export * from './toolkit.js';
@@ -9,7 +9,7 @@ export * from './ledger.js';
9
9
  export * from './cache.js';
10
10
  export * from './blob-store.js';
11
11
  export * from './journal.js';
12
- export * from './jobs.js';
12
+ export * from './pipelines.js';
13
13
  export * from './logger.js';
14
14
  export * from './session-storage.js';
15
15
  export * from './toolkit.js';