@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
@@ -14,7 +14,7 @@ export type UnitOutcome = 'written' | 'skipped' | 'failed' | 'unchanged' | 'woul
14
14
  export type RunRow = {
15
15
  readonly runId: RunId;
16
16
  readonly job: string;
17
- readonly trigger: 'schedule' | 'http' | 'queue' | 'admin' | 'replay';
17
+ readonly trigger: 'schedule' | 'http' | 'queue' | 'admin' | 'replay' | 'pipeline';
18
18
  readonly mode: 'live' | 'dry-run';
19
19
  readonly startedAt: Instant;
20
20
  readonly identity: DeploymentIdentity;
@@ -36,7 +36,7 @@ export type UnitRow = {
36
36
  };
37
37
  export type StepOutcome = 'ok' | 'retry' | 'failed' | 'superseded';
38
38
  /**
39
- * One attempt of one Job step on one unit. The Step grain of plan §9.2.
39
+ * One attempt of one Pipeline step on one unit. The Step grain of plan §9.2.
40
40
  *
41
41
  * **A record, not state.** Nothing reads a step row to decide what runs next:
42
42
  * the reference executor keeps its own step state, and Workflows keeps its
@@ -50,7 +50,7 @@ export type StepOutcome = 'ok' | 'retry' | 'failed' | 'superseded';
50
50
  export type StepRow = {
51
51
  readonly runId: RunId;
52
52
  readonly unitKey: UnitKey;
53
- /** The step's name in its Job definition. */
53
+ /** The step's name in its Pipeline definition. */
54
54
  readonly step: string;
55
55
  /** 1 for the first attempt. A retry writes a new row with the next number. */
56
56
  readonly attempt: number;
@@ -81,8 +81,8 @@ export type ReasonCount = {
81
81
  readonly count: number;
82
82
  };
83
83
  /**
84
- * A webhook task: one Action's work on one delivery. `failed` means a retry is
85
- * scheduled; `dead` means the retries ran out. An Action's non-retryable
84
+ * A webhook task: one use case's work on one delivery. `failed` means a retry is
85
+ * scheduled; `dead` means the retries ran out. A use case's non-retryable
86
86
  * failure is `done`, and its unit row says why.
87
87
  */
88
88
  export type TaskState = 'received' | 'processing' | 'done' | 'failed' | 'dead' | 'replayed';
@@ -102,16 +102,18 @@ export type DeliveryRow = {
102
102
  };
103
103
  export type TaskRow = {
104
104
  readonly deliveryId: string;
105
- /** The Action's name. */
106
- readonly action: string;
105
+ /** The use case's name. */
106
+ readonly useCase: string;
107
107
  readonly state: TaskState;
108
108
  /** When the task last moved. */
109
109
  readonly updatedAt: Instant;
110
- /** Why it is `dead`: the Action's last retryable reason, `fault` or `dead-lettered`. Set by the move that set the state. */
110
+ /** Why it is `dead`: the use case's last retryable reason, `fault`, `dead-lettered` or `stuck`. Set by the move that set the state. */
111
111
  readonly reasonCode?: string;
112
+ /** How many times the stuck-task sweeper re-sent it. A move to `replayed` resets it. */
113
+ readonly requeues: number;
112
114
  };
113
115
  /** Where `deadTasks` resumes: the last row of the previous page. */
114
- export type TaskCursor = Pick<TaskRow, 'updatedAt' | 'deliveryId' | 'action'>;
116
+ export type TaskCursor = Pick<TaskRow, 'updatedAt' | 'deliveryId' | 'useCase'>;
115
117
  /**
116
118
  * Named queries only. No method takes SQL.
117
119
  *
@@ -136,7 +138,7 @@ export interface Journal {
136
138
  * Append-only. A step row is never a correction, so writing the same row
137
139
  * twice records it twice rather than merging it.
138
140
  *
139
- * There is no query that reads step rows back by Job instance, and there must
141
+ * There is no query that reads step rows back by Pipeline instance, and there must
140
142
  * not be one: that would make the journal the executor's state store, which
141
143
  * decision 0006 rejected. Step rows are read only through `unit`.
142
144
  */
@@ -158,29 +160,37 @@ export interface Journal {
158
160
  failuresByReason(since: Instant): Promise<readonly ReasonCount[]>;
159
161
  recentRuns(limit?: number): Promise<readonly RunRow[]>;
160
162
  /**
161
- * The delivery and one `received` task per Action, in one atomic write.
163
+ * The delivery and one `received` task per use case, in one atomic write.
162
164
  * Recording it again, as a retried delivery does, changes no row already
163
165
  * there: it adds only the tasks it lacks.
164
166
  */
165
- recordDelivery(delivery: DeliveryRow, actions: readonly string[]): Promise<void>;
167
+ recordDelivery(delivery: DeliveryRow, useCases: readonly string[]): Promise<void>;
166
168
  /**
167
169
  * Moves a task to `to` only from a state `TASK_TRANSITIONS` allows, in one
168
170
  * conditional update. False when the task is in another state or missing.
169
171
  * Writes `reasonCode`, or clears it when absent: a reason describes the
170
172
  * state it came with.
171
173
  */
172
- moveTask(deliveryId: string, action: string, to: Exclude<TaskState, 'received'>, at: Instant, reasonCode?: string): Promise<boolean>;
173
- /** The delivery with its tasks, by Action name. */
174
+ moveTask(deliveryId: string, useCase: string, to: Exclude<TaskState, 'received'>, at: Instant, reasonCode?: string): Promise<boolean>;
175
+ /** The delivery with its tasks, by use case name. */
174
176
  delivery(deliveryId: string): Promise<{
175
177
  delivery: DeliveryRow;
176
178
  tasks: readonly TaskRow[];
177
179
  } | undefined>;
178
180
  /** Dead tasks, oldest first, keyset-paged by `after`. */
179
181
  deadTasks(options?: {
180
- readonly action?: string;
182
+ readonly useCase?: string;
181
183
  readonly after?: TaskCursor;
182
184
  readonly limit?: number;
183
185
  }): Promise<readonly TaskRow[]>;
184
- /** Tasks still `received` or `processing` that last moved before `before`, oldest first. */
186
+ /** Tasks still `received`, `processing` or `replayed` that last moved before `before`, oldest first. */
185
187
  stuckTasks(before: Instant, limit?: number): Promise<readonly TaskRow[]>;
188
+ /**
189
+ * Claims a task `stuckTasks` returned, in one conditional write: only while
190
+ * it is still stuck and last moved at `task.updatedAt`, so of two sweepers
191
+ * that read it, one wins. `requeued` keeps its state, sets `updatedAt` to
192
+ * `at` and counts one more requeue; `dead` makes it `dead` with reason
193
+ * `stuck`. False when the task moved since it was read.
194
+ */
195
+ reclaimStuckTask(task: Pick<TaskRow, 'deliveryId' | 'useCase' | 'updatedAt'>, at: Instant, to: 'requeued' | 'dead'): Promise<boolean>;
186
196
  }
@@ -10,11 +10,11 @@ export type ToolManifest = {
10
10
  readonly blobMaxBytes: number;
11
11
  readonly cacheMinTtlSeconds: number;
12
12
  /**
13
- * The largest step result a Jobs executor stores, in bytes of the result's
13
+ * The largest step result a Pipelines executor stores, in bytes of the result's
14
14
  * JSON encoding as UTF-8. The executor checks it when a step returns, before
15
15
  * the result is stored or handed to the platform, and rejects a larger one
16
16
  * with `LimitExceeded` (rule 7). The step then fails terminally, with no
17
- * retry, because the same input produces the same result. A Job's exhaustion
17
+ * retry, because the same input produces the same result. A Pipeline's exhaustion
18
18
  * handler sees the cause `result-too-large`.
19
19
  */
20
20
  readonly stepResultMaxBytes: number;
@@ -1,16 +1,17 @@
1
1
  import type { RunId, UnitKey } from './journal.js';
2
+ import type { Toolkit } from './toolkit.js';
2
3
  /**
3
- * DURABLE JOBS. The definition is ours; the executor is the platform's.
4
+ * DURABLE PIPELINES. The definition is ours; the executor is the platform's.
4
5
  *
5
- * Two executors run the same `Job` value: Cloudflare Workflows when deployed,
6
+ * Two executors run the same `PipelineDefinition` value: Cloudflare Workflows when deployed,
6
7
  * and the reference executor (docs/decisions/0006) locally, in tests and on
7
8
  * Postgres. Nothing in this file may be something only one of them can do.
8
- * That is why there is no sleep, no wait-for-event and no sub-job here:
9
+ * That is why there is no sleep, no wait-for-event and no sub-pipeline here:
9
10
  * Workflows has them, the reference executor does not yet, and no domain needs
10
11
  * them yet.
11
12
  */
12
13
  /**
13
- * What a step may return and a Job may take as input. A step result is stored
14
+ * What a step may return and a Pipeline may take as input. A step result is stored
14
15
  * by the executor and handed to later steps, possibly after a restart, so it
15
16
  * must survive serialisation. A `Date`, a `Map`, a class instance or
16
17
  * `undefined` would not come back as itself, and the type refuses them.
@@ -26,19 +27,19 @@ export type JsonValue = null | boolean | number | string | readonly JsonValue[]
26
27
  readonly [key: string]: JsonValue;
27
28
  };
28
29
  /**
29
- * `name + '-' + key(input)`, derived by the executor from the Job definition
30
+ * `name + '-' + key(input)`, derived by the executor from the Pipeline definition
30
31
  * and the input. The caller never chooses it, so a caller that retries its own
31
- * request with the same input gets `already-started` instead of a second Job.
32
+ * request with the same input gets `already-started` instead of a second Pipeline.
32
33
  *
33
34
  * Workflows' rule applies on every executor: at most 100 characters, matching
34
- * `^[a-zA-Z0-9_][a-zA-Z0-9-_]*$` (docs/platform-facts.md). `Job.name` and
35
- * `Job.key` say what that leaves for each part.
35
+ * `^[a-zA-Z0-9_][a-zA-Z0-9-_]*$` (docs/platform-facts.md). `PipelineDefinition.name` and
36
+ * `PipelineDefinition.key` say what that leaves for each part.
36
37
  *
37
- * Because the name is in the id, two Jobs that key on the same reference get
38
- * different ids, and `status(id)` needs no Job name. A name has no `-`
39
- * (`Job`), so the id's first `-` ends the name.
38
+ * Because the name is in the id, two Pipelines that key on the same reference get
39
+ * different ids, and `status(id)` needs no Pipeline name. A name has no `-`
40
+ * (`PipelineDefinition`), so the id's first `-` ends the name.
40
41
  */
41
- export type JobInstanceId = string;
42
+ export type PipelineInstanceId = string;
42
43
  /**
43
44
  * WORKFLOWS' MEANING, ON EVERY EXECUTOR.
44
45
  *
@@ -51,9 +52,9 @@ export type JobInstanceId = string;
51
52
  * backoff, and `delaySeconds * 2 ** (n - 1)` with `exponential`. A 1-second
52
53
  * exponential delay waits 1, 2, then 4 seconds (spike, run 2).
53
54
  *
54
- * Every field is required, with no default. Workflows defaults to five
55
- * exponential retries from ten seconds, and a step that does not say how often
56
- * it may repeat a side effect has not been thought about.
55
+ * Every field is required here, so an executor always receives a complete
56
+ * value. Defaults belong to whatever builds the definition: the `Pipeline`
57
+ * class in `@anatta.io/tva/pipelines` fills them in (decision 0015).
57
58
  */
58
59
  export type StepRetries = {
59
60
  readonly limit: number;
@@ -80,17 +81,23 @@ export type StepRetries = {
80
81
  * outcome (rule 8), and because a value cannot be lost by a `catch` that
81
82
  * wraps the real error.
82
83
  */
83
- export type JobStepOutcome<Result extends JsonValue> = {
84
+ export type PipelineStepOutcome<Result extends JsonValue> = {
84
85
  readonly status: 'done';
85
86
  readonly result: Result;
86
87
  } | {
87
88
  readonly status: 'terminal';
88
89
  readonly reasonCode: string;
89
90
  };
91
+ /**
92
+ * The tools every step receives from its executor, whatever its deps: the
93
+ * journal, the clock and the logger. A use case run as a step records its
94
+ * own run with them.
95
+ */
96
+ export type StepToolkit = Pick<Toolkit, 'journal' | 'clock' | 'logger'>;
90
97
  /** What every step attempt, and the exhaustion handler, receives. */
91
98
  export type StepContext<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps> = {
92
99
  /** `name + '-' + key(input)`. */
93
- readonly instanceId: JobInstanceId;
100
+ readonly instanceId: PipelineInstanceId;
94
101
  /**
95
102
  * From `dispatch`. The journal records each step under this run and unit.
96
103
  */
@@ -107,15 +114,21 @@ export type StepContext<Input extends JsonValue, Results extends Record<string,
107
114
  readonly results: Partial<Results>;
108
115
  /**
109
116
  * What the steps call: the Shopify client, the ledger, the logger. The
110
- * executor builds it, from the builder registered with this Job's
111
- * definition (`JobRegistration`), in the invocation that runs the step. It
117
+ * executor builds it, from the builder registered with this Pipeline's
118
+ * definition (`PipelineRegistration`), in the invocation that runs the step. It
112
119
  * is not stored and does not survive a restart: a later attempt gets a
113
120
  * newly built one.
114
121
  */
115
122
  readonly deps: Deps;
123
+ /**
124
+ * The executor's own journal, clock and logger. Unlike `deps`, the app does
125
+ * not build it: every executor already has one, and passes it to every
126
+ * attempt and to the exhaustion handler.
127
+ */
128
+ readonly toolkit: StepToolkit;
116
129
  };
117
130
  /**
118
- * One step of a Job. ALL I/O IN A JOB HAPPENS INSIDE A STEP.
131
+ * One step of a Pipeline. ALL I/O IN A PIPELINE HAPPENS INSIDE A STEP.
119
132
  *
120
133
  * **A step must be idempotent under concurrent execution, not only under a
121
134
  * re-run.** Two attempts of one step can overlap. The reference executor's
@@ -134,22 +147,22 @@ export type StepContext<Input extends JsonValue, Results extends Record<string,
134
147
  * land (run 5). A timeout is a fault, so the step is retried, and the timed-out
135
148
  * attempt may still finish its side effect alongside the retry.
136
149
  *
137
- * Step names are unique within a Job. A stored result is keyed by its step's
150
+ * Step names are unique within a Pipeline. A stored result is keyed by its step's
138
151
  * name, in `StepContext.results` and in the journal's Step rows. The type
139
- * cannot refuse a repeated name, so the executor refuses the Job when it is
140
- * built (rule 7), as it refuses a bad Job name.
152
+ * cannot refuse a repeated name, so the executor refuses the Pipeline when it is
153
+ * built (rule 7), as it refuses a bad Pipeline name.
141
154
  */
142
155
  export type Step<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps, Name extends keyof Results & string> = {
143
156
  readonly name: Name;
144
157
  readonly retries: StepRetries;
145
158
  readonly timeoutSeconds: number;
146
- run(context: StepContext<Input, Results, Deps>): Promise<JobStepOutcome<Results[Name]>>;
159
+ run(context: StepContext<Input, Results, Deps>): Promise<PipelineStepOutcome<Results[Name]>>;
147
160
  };
148
- /** Any one step of a Job, with its result type tied to its name. */
149
- export type JobStep<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps> = {
161
+ /** Any one step of a Pipeline, with its result type tied to its name. */
162
+ export type PipelineStep<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps> = {
150
163
  [Name in keyof Results & string]: Step<Input, Results, Deps, Name>;
151
164
  }[keyof Results & string];
152
- /** Why a Job stopped before its last step. */
165
+ /** Why a Pipeline stopped before its last step. */
153
166
  export type Exhaustion = {
154
167
  readonly step: string;
155
168
  readonly cause: 'terminal';
@@ -181,47 +194,47 @@ export type ExhaustionContext<Input extends JsonValue, Results extends Record<st
181
194
  * Workflow name (docs/platform-facts.md: at most 64 characters, matching
182
195
  * `^[a-zA-Z0-9_][a-zA-Z0-9-_]*$`), with `-` removed. Without `-` in a name,
183
196
  * the first `-` in an instance id always separates the name from the key, so
184
- * two Jobs cannot derive the same id: `a` keyed `b-c` and `a-b` keyed `c`
197
+ * two Pipelines cannot derive the same id: `a` keyed `b-c` and `a-b` keyed `c`
185
198
  * would both give `a-b-c`, and `a-b` is not a valid name. Each name is checked
186
- * on its own, and an executor can find the Job for an id from its prefix.
199
+ * on its own, and an executor can find the Pipeline for an id from its prefix.
187
200
  *
188
- * The executor refuses a Job whose name breaks either rule, the characters or
201
+ * The executor refuses a Pipeline whose name breaks either rule, the characters or
189
202
  * the 64-character limit, when the executor is built (rule 7). It throws, and
190
- * no Job runs on it. A bad name is a defect in the definition, and it is found
203
+ * no Pipeline runs on it. A bad name is a defect in the definition, and it is found
191
204
  * when the app starts, not at the first `dispatch`.
192
205
  *
193
- * A JOB IS A PLAIN EXPORTED CONSTANT IN THE DOMAIN, NOT A FACTORY. Routes and
206
+ * A PIPELINE IS A PLAIN EXPORTED CONSTANT IN THE DOMAIN, NOT A FACTORY. Routes and
194
207
  * tests import it. Both executors also need it when they are built, not only
195
208
  * at `dispatch`: a step runs after a restart, when the only thing the
196
209
  * executor has is the instance id. So a step does not close over its
197
210
  * dependencies. It reads them from `context.deps`, which the executor builds
198
- * from the builder registered with the definition (`JobRegistration`). A Job
211
+ * from the builder registered with the definition (`PipelineRegistration`). A Pipeline
199
212
  * whose steps need nothing declares `Deps` as `undefined`, and registers the
200
213
  * builder `() => undefined`.
201
214
  */
202
- export type Job<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps> = {
215
+ export type PipelineDefinition<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps> = {
203
216
  readonly name: string;
204
217
  /**
205
218
  * The instance's unit, from its input. The executor sets the instance id to
206
219
  * `name + '-' + key(input)` and the unit key that the journal records steps
207
- * under to `key(input)`, so the Job's unit and the journal's unit are the
220
+ * under to `key(input)`, so the Pipeline's unit and the journal's unit are the
208
221
  * same value.
209
222
  *
210
223
  * It must be a pure function of the input: the same input gives the same
211
224
  * key, on every call and after a restart. A key read from anything else, a
212
- * random value or the time, turns a retried request into a second Job.
225
+ * random value or the time, turns a retried request into a second Pipeline.
213
226
  *
214
- * The id must fit Workflows' rule (see `JobInstanceId`), so a key is at
227
+ * The id must fit Workflows' rule (see `PipelineInstanceId`), so a key is at
215
228
  * least one character, uses only `a-z`, `A-Z`, `0-9`, `-` and `_`, and is at
216
229
  * most `99 - name.length` characters long. `dispatch` throws, and records
217
230
  * nothing, when the key breaks the rule (rule 7): a key that does not fit is
218
- * a defect in the Job, not an outcome.
231
+ * a defect in the Pipeline, not an outcome.
219
232
  */
220
233
  readonly key: (input: Input) => UnitKey;
221
- readonly steps: readonly JobStep<Input, Results, Deps>[];
234
+ readonly steps: readonly PipelineStep<Input, Results, Deps>[];
222
235
  /**
223
236
  * Runs when a step fails terminally, runs out of retries, or returns a
224
- * result that is too large. It does not run when the Job completes. The
237
+ * result that is too large. It does not run when the Pipeline completes. The
225
238
  * self sign-up slice uses it to dead-letter.
226
239
  *
227
240
  * IT RUNS AT LEAST ONCE, AND NEVER AFTER THE INSTANCE IS `failed`. It is
@@ -235,7 +248,7 @@ export type Job<Input extends JsonValue, Results extends Record<string, JsonValu
235
248
  readonly onExhausted?: (context: ExhaustionContext<Input, Results, Deps>) => Promise<void>;
236
249
  };
237
250
  /**
238
- * ONE JOB WITH THE BUILDER FOR ITS DEPS, IN THE SHAPE EVERY EXECUTOR FACTORY
251
+ * ONE PIPELINE WITH THE BUILDER FOR ITS DEPS, IN THE SHAPE EVERY EXECUTOR FACTORY
239
252
  * TAKES. The factories themselves are #69 to #71.
240
253
  *
241
254
  * A step runs in an invocation that has no request: the reference executor's
@@ -244,13 +257,13 @@ export type Job<Input extends JsonValue, Results extends Record<string, JsonValu
244
257
  * caller of `dispatch`. The executor builds them itself, with the builder
245
258
  * registered here when the executor was built:
246
259
  *
247
- * const registrations: readonly JobRegistration[] = [
260
+ * const registrations: readonly PipelineRegistration[] = [
248
261
  * (register) => register(selfSignUp, () => createSignUpDeps(env)),
249
262
  * ]
250
263
  *
251
264
  * A registration hands its definition and its builder to the executor's
252
265
  * `register` callback. That form lets the type check that the builder returns
253
- * the definition's `Deps`, while one list holds Jobs with different inputs,
266
+ * the definition's `Deps`, while one list holds Pipelines with different inputs,
254
267
  * results and deps, without `any`. The executor gets each definition back
255
268
  * with its builder's type tied to it.
256
269
  *
@@ -260,11 +273,11 @@ export type Job<Input extends JsonValue, Results extends Record<string, JsonValu
260
273
  * is synchronous: a dependency that needs I/O to start does that I/O inside
261
274
  * its own methods, which the step awaits.
262
275
  */
263
- export type JobRegistration = <Out>(register: <Input extends JsonValue, Results extends Record<string, JsonValue>, Deps>(definition: Job<Input, Results, Deps>, deps: () => NoInfer<Deps>) => Out) => Out;
276
+ export type PipelineRegistration = <Out>(register: <Input extends JsonValue, Results extends Record<string, JsonValue>, Deps>(definition: PipelineDefinition<Input, Results, Deps>, deps: () => NoInfer<Deps>) => Out) => Out;
264
277
  /**
265
278
  * The run comes from the caller, because it is the request's run in the
266
279
  * journal and nothing in the input says which run that is. The id and the
267
- * unit key come from `Job.key`.
280
+ * unit key come from `PipelineDefinition.key`.
268
281
  */
269
282
  export type DispatchOptions = {
270
283
  readonly runId: RunId;
@@ -293,7 +306,7 @@ export type DispatchResult = {
293
306
  * It is the same on both outcomes: on `already-started` it is the id of
294
307
  * the instance that already holds it. Pass it to `status`.
295
308
  */
296
- readonly id: JobInstanceId;
309
+ readonly id: PipelineInstanceId;
297
310
  };
298
311
  /**
299
312
  * The state of one instance, in the words both executors can say.
@@ -306,7 +319,7 @@ export type DispatchResult = {
306
319
  * `unknown` is a value, not a throw: the id was never started, or the instance
307
320
  * ended and its retention has passed.
308
321
  */
309
- export type JobStatus = {
322
+ export type PipelineStatus = {
310
323
  readonly status: 'unknown';
311
324
  } | {
312
325
  readonly status: 'running';
@@ -316,11 +329,11 @@ export type JobStatus = {
316
329
  readonly status: 'failed';
317
330
  };
318
331
  /**
319
- * Dispatch a Job and ask how it is doing. Nothing else, on purpose: every
332
+ * Dispatch a Pipeline and ask how it is doing. Nothing else, on purpose: every
320
333
  * method here has to be one that the reference executor and Workflows can
321
334
  * both implement.
322
335
  */
323
- export interface Jobs {
336
+ export interface Pipelines {
324
337
  /**
325
338
  * Records the instance and returns. It does not run a step before it
326
339
  * returns: the steps run later, in another invocation, and the caller does
@@ -329,7 +342,7 @@ export interface Jobs {
329
342
  * `input` is stored unredacted for the instance's lifetime, as is every step
330
343
  * result (docs/decisions/0006). Pass ids and references, not customer data.
331
344
  */
332
- dispatch<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps>(definition: Job<Input, Results, Deps>, input: Input, options: DispatchOptions): Promise<DispatchResult>;
345
+ dispatch<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps>(definition: PipelineDefinition<Input, Results, Deps>, input: Input, options: DispatchOptions): Promise<DispatchResult>;
333
346
  /** `id` is the one that `dispatch` returned. */
334
- status(id: JobInstanceId): Promise<JobStatus>;
347
+ status(id: PipelineInstanceId): Promise<PipelineStatus>;
335
348
  }
@@ -0,0 +1 @@
1
+ export { DEFAULT_STEP_OPTIONS, Pipeline, done, terminal, type StepOptions, type StepOverrides, type StepRun, type UseCaseStepWiring, } from './pipeline.js';
@@ -0,0 +1,2 @@
1
+ // The `@anatta.io/tva/pipelines` entry point.
2
+ export { DEFAULT_STEP_OPTIONS, Pipeline, done, terminal, } from './pipeline.js';
@@ -0,0 +1,142 @@
1
+ import type { DispatchOptions, DispatchResult, ExhaustionContext, JsonValue, PipelineRegistration, PipelineStep, PipelineStepOutcome, Pipelines, Step, StepContext, StepRetries, UnitKey } from '../contracts/index.js';
2
+ import { UseCase, type Decision } from '../use-cases/index.js';
3
+ /** A step's settings, complete. What an executor receives. */
4
+ export type StepOptions = {
5
+ readonly retries: StepRetries;
6
+ readonly timeoutSeconds: number;
7
+ };
8
+ /** Any part of a step's settings: what a Pipeline, or one step, changes. */
9
+ export type StepOverrides = {
10
+ readonly retries?: Partial<StepRetries>;
11
+ readonly timeoutSeconds?: number;
12
+ };
13
+ /**
14
+ * The library's step settings, under every Pipeline's own `stepDefaults`.
15
+ * Three retries, 10, 20 then 40 seconds apart (`limit` counts retries, not
16
+ * attempts: four attempts in all), and a minute per attempt.
17
+ */
18
+ export declare const DEFAULT_STEP_OPTIONS: StepOptions;
19
+ /** A step's body, with its result type tied to its name. */
20
+ export type StepRun<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps, Name extends keyof Results> = (context: StepContext<Input, Results, Deps>) => Promise<PipelineStepOutcome<Results[Name]>>;
21
+ /**
22
+ * How a use case run as a step gets its input and its deps from the step's
23
+ * context, when the Pipeline's own do not fit it. Its settings are the
24
+ * step's overrides.
25
+ */
26
+ export type UseCaseStepWiring<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps, UseCaseInput, UseCaseDeps> = StepOverrides & {
27
+ readonly input: (context: StepContext<Input, Results, Deps>) => UseCaseInput;
28
+ readonly deps: (context: StepContext<Input, Results, Deps>) => UseCaseDeps;
29
+ };
30
+ type StoresDecision<Result, Reason extends string> = [Result] extends [
31
+ Decision<Reason>
32
+ ] ? unknown : never;
33
+ type PassesThrough<Have, Need> = [Have] extends [Need] ? unknown : never;
34
+ /**
35
+ * A PIPELINE AS A CLASS. Extend it, name it, key it, and list its steps with
36
+ * `this.step`. Export one instance; routes, tests and the executor's
37
+ * registrations all use it.
38
+ *
39
+ * export class Demo extends Pipeline<DemoInput, DemoResults, DemoDeps> {
40
+ * static override stepDefaults: StepOverrides = { timeoutSeconds: 30 }
41
+ *
42
+ * readonly name = 'demo'
43
+ *
44
+ * key(input: DemoInput): UnitKey {
45
+ * return input.ref
46
+ * }
47
+ *
48
+ * readonly steps = [
49
+ * this.step('start', async ({ deps }) => done({ at: toIso(deps.clock.now()) })),
50
+ * this.step('finish', { retries: { limit: 5 } }, async ({ results }) => …),
51
+ * ]
52
+ * }
53
+ *
54
+ * export const demo = new Demo()
55
+ *
56
+ * The executors are unchanged: `register` and `dispatch` hand them the plain
57
+ * `PipelineDefinition` they already run, built once from the instance. Every
58
+ * rule of `PipelineDefinition` and `Step` holds, in particular: all I/O in a
59
+ * step, no code between steps, and a step safe when two attempts overlap.
60
+ *
61
+ * HOLD NO STATE ON `this`. One instance serves every dispatch, every attempt
62
+ * and every executor in the process, and a step that runs after a restart
63
+ * runs on a new instance. State lives in the input, the step results and the
64
+ * deps. (decision 0015)
65
+ */
66
+ export declare abstract class Pipeline<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps> {
67
+ #private;
68
+ /**
69
+ * This Pipeline's step settings, over `DEFAULT_STEP_OPTIONS`, under each
70
+ * step's own overrides. Each layer may be partial.
71
+ *
72
+ * STATIC, NOT AN INSTANCE FIELD. Class fields are set in the order they are
73
+ * written, after the base constructor, so an instance field written below
74
+ * `steps` is not set yet when `steps` calls `this.step`, and would be
75
+ * ignored without an error. A static field is set when the class is.
76
+ */
77
+ static stepDefaults: StepOverrides;
78
+ /** `A-Z`, `a-z`, `0-9` and `_` only, 1 to 64 characters. See `PipelineDefinition.name`. */
79
+ abstract readonly name: string;
80
+ /** The steps, in the order they run. Build each one with `this.step`. */
81
+ abstract readonly steps: readonly PipelineStep<Input, Results, Deps>[];
82
+ /** The instance's unit, from its input. A pure function. See `PipelineDefinition.key`. */
83
+ abstract key(input: Input): UnitKey;
84
+ /**
85
+ * Optional. Runs at least once when a step fails terminally, runs out of
86
+ * retries, or returns a result that is too large. See
87
+ * `PipelineDefinition.onExhausted`.
88
+ */
89
+ protected onExhausted?(context: ExhaustionContext<Input, Results, Deps>): Promise<void>;
90
+ /**
91
+ * One step. Its name must be a key of `Results`, and `run` must return that
92
+ * key's result type, so a step cannot store the wrong shape. `run`'s
93
+ * context is typed for you.
94
+ *
95
+ * Its settings come from, lowest first: `DEFAULT_STEP_OPTIONS`, the
96
+ * Pipeline's `stepDefaults`, then `overrides`.
97
+ *
98
+ * A plain object in `steps` compiles too, but TypeScript gives a class
99
+ * field no type from the base class, so its `run` loses its types. Use
100
+ * this.
101
+ *
102
+ * A USE CASE CAN BE A STEP. Pass it in place of `run`. The step calls its
103
+ * `execute`, which opens and records the use case's own journal run with
104
+ * `trigger: 'pipeline'` and `job: 'pipeline.<name>.<step>'`, using the
105
+ * step's `toolkit`. Its decision becomes the step's outcome: a retryable
106
+ * one retries the step, `failed` stops the Pipeline with its reason code,
107
+ * and any other is stored as the step's result. The step's `Results` entry
108
+ * must be that use case's `Decision`.
109
+ *
110
+ * With no wiring, the step passes the Pipeline's input and deps to the use
111
+ * case unchanged, and both must fit it. With wiring, `input` and `deps`
112
+ * build them from the step's context, for example from an earlier step's
113
+ * result.
114
+ *
115
+ * A use case written for a queue expects one redelivery at a time. As a
116
+ * step it must also be safe when two attempts overlap (`Step`).
117
+ */
118
+ protected step<Name extends keyof Results & string, UseCaseInput, Reason extends string, UseCaseDeps>(name: Name, useCase: UseCase<UseCaseInput, Reason, UseCaseDeps> & StoresDecision<Results[Name], Reason>, wiring: UseCaseStepWiring<Input, Results, Deps, UseCaseInput, UseCaseDeps>): Step<Input, Results, Deps, Name>;
119
+ protected step<Name extends keyof Results & string, UseCaseInput, Reason extends string, UseCaseDeps>(name: Name, useCase: UseCase<UseCaseInput, Reason, UseCaseDeps> & StoresDecision<Results[Name], Reason> & PassesThrough<Input, UseCaseInput> & PassesThrough<Deps, UseCaseDeps>, overrides?: StepOverrides): Step<Input, Results, Deps, Name>;
120
+ protected step<Name extends keyof Results & string>(name: Name, run: StepRun<Input, Results, Deps, Name>): Step<Input, Results, Deps, Name>;
121
+ protected step<Name extends keyof Results & string>(name: Name, overrides: StepOverrides, run: StepRun<Input, Results, Deps, Name>): Step<Input, Results, Deps, Name>;
122
+ /**
123
+ * This Pipeline with the builder for its deps, for the executor's
124
+ * registrations. Replaces `(register) => register(definition, deps)`.
125
+ */
126
+ register(deps: () => Deps): PipelineRegistration;
127
+ /**
128
+ * Starts an instance on `pipelines`. The same outcomes as
129
+ * `Pipelines.dispatch`, which it calls.
130
+ */
131
+ dispatch(input: Input, { pipelines, ...options }: DispatchOptions & {
132
+ readonly pipelines: Pipelines;
133
+ }): Promise<DispatchResult>;
134
+ }
135
+ /** A step's result: the step is done, and later steps read `result`. */
136
+ export declare const done: <Result extends JsonValue>(result: Result) => PipelineStepOutcome<Result>;
137
+ /**
138
+ * No retry can succeed. The Pipeline stops, and `onExhausted` runs with the
139
+ * reason code, from the domain's closed list.
140
+ */
141
+ export declare const terminal: (reasonCode: string) => PipelineStepOutcome<never>;
142
+ export {};