@anatta.io/tva 0.0.0-stage → 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 (190) hide show
  1. package/README.md +50 -2
  2. package/dist/adapters/cloudflare/bindings.d.ts +10 -0
  3. package/dist/adapters/cloudflare/bindings.js +1 -0
  4. package/dist/adapters/cloudflare/blob-store.d.ts +39 -0
  5. package/dist/adapters/cloudflare/blob-store.js +95 -0
  6. package/dist/adapters/cloudflare/cache.d.ts +14 -0
  7. package/dist/adapters/cloudflare/cache.js +48 -0
  8. package/dist/adapters/cloudflare/faults.d.ts +7 -0
  9. package/dist/adapters/cloudflare/faults.js +39 -0
  10. package/dist/adapters/cloudflare/index.d.ts +15 -0
  11. package/dist/adapters/cloudflare/index.js +16 -0
  12. package/dist/adapters/cloudflare/journal.d.ts +110 -0
  13. package/dist/adapters/cloudflare/journal.js +325 -0
  14. package/dist/adapters/cloudflare/ledger.d.ts +14 -0
  15. package/dist/adapters/cloudflare/ledger.js +108 -0
  16. package/dist/adapters/cloudflare/logger.d.ts +22 -0
  17. package/dist/adapters/cloudflare/logger.js +49 -0
  18. package/dist/adapters/cloudflare/manifest.d.ts +81 -0
  19. package/dist/adapters/cloudflare/manifest.js +81 -0
  20. package/dist/adapters/cloudflare/pipelines.d.ts +97 -0
  21. package/dist/adapters/cloudflare/pipelines.js +218 -0
  22. package/dist/adapters/cloudflare/queue.d.ts +80 -0
  23. package/dist/adapters/cloudflare/queue.js +177 -0
  24. package/dist/adapters/cloudflare/retention.d.ts +24 -0
  25. package/dist/adapters/cloudflare/retention.js +103 -0
  26. package/dist/adapters/cloudflare/session-storage.d.ts +27 -0
  27. package/dist/adapters/cloudflare/session-storage.js +78 -0
  28. package/dist/adapters/cloudflare/toolkit.d.ts +16 -0
  29. package/dist/adapters/cloudflare/toolkit.js +57 -0
  30. package/dist/adapters/cloudflare/workflow-pipelines.d.ts +66 -0
  31. package/dist/adapters/cloudflare/workflow-pipelines.js +323 -0
  32. package/dist/adapters/journal-records.d.ts +80 -0
  33. package/dist/adapters/journal-records.js +75 -0
  34. package/dist/adapters/memory/blob-store.d.ts +9 -0
  35. package/dist/adapters/memory/blob-store.js +19 -0
  36. package/dist/adapters/memory/cache.d.ts +13 -0
  37. package/dist/adapters/memory/cache.js +36 -0
  38. package/dist/adapters/memory/clock.d.ts +1 -0
  39. package/dist/adapters/memory/clock.js +4 -0
  40. package/dist/adapters/memory/index.d.ts +11 -0
  41. package/dist/adapters/memory/index.js +11 -0
  42. package/dist/adapters/memory/journal.d.ts +35 -0
  43. package/dist/adapters/memory/journal.js +154 -0
  44. package/dist/adapters/memory/ledger.d.ts +9 -0
  45. package/dist/adapters/memory/ledger.js +33 -0
  46. package/dist/adapters/memory/logger.d.ts +16 -0
  47. package/dist/adapters/memory/logger.js +21 -0
  48. package/dist/adapters/memory/manifest.d.ts +59 -0
  49. package/dist/adapters/memory/manifest.js +59 -0
  50. package/dist/adapters/memory/pipelines.d.ts +62 -0
  51. package/dist/adapters/memory/pipelines.js +219 -0
  52. package/dist/adapters/memory/queue.d.ts +20 -0
  53. package/dist/adapters/memory/queue.js +102 -0
  54. package/dist/adapters/memory/session-storage.d.ts +20 -0
  55. package/dist/adapters/memory/session-storage.js +33 -0
  56. package/dist/adapters/memory/toolkit.d.ts +8 -0
  57. package/dist/adapters/memory/toolkit.js +31 -0
  58. package/dist/adapters/postgres/cache.d.ts +17 -0
  59. package/dist/adapters/postgres/cache.js +69 -0
  60. package/dist/adapters/postgres/config.d.ts +27 -0
  61. package/dist/adapters/postgres/config.js +45 -0
  62. package/dist/adapters/postgres/faults.d.ts +14 -0
  63. package/dist/adapters/postgres/faults.js +47 -0
  64. package/dist/adapters/postgres/index.d.ts +12 -0
  65. package/dist/adapters/postgres/index.js +12 -0
  66. package/dist/adapters/postgres/journal.d.ts +86 -0
  67. package/dist/adapters/postgres/journal.js +337 -0
  68. package/dist/adapters/postgres/ledger.d.ts +16 -0
  69. package/dist/adapters/postgres/ledger.js +97 -0
  70. package/dist/adapters/postgres/logger.d.ts +19 -0
  71. package/dist/adapters/postgres/logger.js +37 -0
  72. package/dist/adapters/postgres/manifest.d.ts +52 -0
  73. package/dist/adapters/postgres/manifest.js +53 -0
  74. package/dist/adapters/postgres/migrate.d.ts +20 -0
  75. package/dist/adapters/postgres/migrate.js +96 -0
  76. package/dist/adapters/postgres/queue.d.ts +64 -0
  77. package/dist/adapters/postgres/queue.js +333 -0
  78. package/dist/adapters/postgres/retention.d.ts +18 -0
  79. package/dist/adapters/postgres/retention.js +104 -0
  80. package/dist/adapters/postgres/session-storage.d.ts +20 -0
  81. package/dist/adapters/postgres/session-storage.js +71 -0
  82. package/dist/adapters/postgres/toolkit.d.ts +25 -0
  83. package/dist/adapters/postgres/toolkit.js +58 -0
  84. package/dist/adapters/postgres/with-client.d.ts +11 -0
  85. package/dist/adapters/postgres/with-client.js +29 -0
  86. package/dist/adapters/reference-executor.d.ts +171 -0
  87. package/dist/adapters/reference-executor.js +569 -0
  88. package/dist/adapters/retention.d.ts +18 -0
  89. package/dist/adapters/retention.js +13 -0
  90. package/dist/adapters/s3/blob-store.d.ts +35 -0
  91. package/dist/adapters/s3/blob-store.js +92 -0
  92. package/dist/adapters/s3/faults.d.ts +8 -0
  93. package/dist/adapters/s3/faults.js +34 -0
  94. package/dist/adapters/s3/index.d.ts +2 -0
  95. package/dist/adapters/s3/index.js +2 -0
  96. package/dist/adapters/session-envelope.d.ts +21 -0
  97. package/dist/adapters/session-envelope.js +122 -0
  98. package/dist/adapters/system-clock.d.ts +8 -0
  99. package/dist/adapters/system-clock.js +8 -0
  100. package/dist/contracts/blob-store.d.ts +11 -0
  101. package/dist/contracts/blob-store.js +1 -0
  102. package/dist/contracts/cache.d.ts +27 -0
  103. package/dist/contracts/cache.js +1 -0
  104. package/dist/contracts/duration.d.ts +23 -0
  105. package/dist/contracts/duration.js +27 -0
  106. package/dist/contracts/faults.d.ts +28 -0
  107. package/dist/contracts/faults.js +29 -0
  108. package/dist/contracts/identity.d.ts +12 -0
  109. package/dist/contracts/identity.js +1 -0
  110. package/dist/contracts/index.d.ts +14 -0
  111. package/dist/contracts/index.js +15 -0
  112. package/dist/contracts/instant.d.ts +17 -0
  113. package/dist/contracts/instant.js +12 -0
  114. package/dist/contracts/journal.d.ts +196 -0
  115. package/dist/contracts/journal.js +10 -0
  116. package/dist/contracts/ledger.d.ts +34 -0
  117. package/dist/contracts/ledger.js +1 -0
  118. package/dist/contracts/logger.d.ts +11 -0
  119. package/dist/contracts/logger.js +1 -0
  120. package/dist/contracts/manifest.d.ts +37 -0
  121. package/dist/contracts/manifest.js +30 -0
  122. package/dist/contracts/pipelines.d.ts +348 -0
  123. package/dist/contracts/pipelines.js +1 -0
  124. package/dist/contracts/queue.d.ts +55 -0
  125. package/dist/contracts/queue.js +1 -0
  126. package/dist/contracts/session-storage.d.ts +18 -0
  127. package/dist/contracts/session-storage.js +1 -0
  128. package/dist/contracts/toolkit.d.ts +21 -0
  129. package/dist/contracts/toolkit.js +1 -0
  130. package/dist/pipelines/index.d.ts +1 -0
  131. package/dist/pipelines/index.js +2 -0
  132. package/dist/pipelines/pipeline.d.ts +142 -0
  133. package/dist/pipelines/pipeline.js +140 -0
  134. package/dist/pipelines/use-case-step.d.ts +24 -0
  135. package/dist/pipelines/use-case-step.js +34 -0
  136. package/dist/schedule/schedule.d.ts +40 -0
  137. package/dist/schedule/schedule.js +135 -0
  138. package/dist/use-cases/index.d.ts +3 -0
  139. package/dist/use-cases/index.js +3 -0
  140. package/dist/use-cases/run-use-case.d.ts +33 -0
  141. package/dist/use-cases/run-use-case.js +117 -0
  142. package/dist/use-cases/use-case-consumer.d.ts +44 -0
  143. package/dist/use-cases/use-case-consumer.js +98 -0
  144. package/dist/use-cases/use-case.d.ts +116 -0
  145. package/dist/use-cases/use-case.js +75 -0
  146. package/dist/webhooks/create-webhook-handler.d.ts +63 -0
  147. package/dist/webhooks/create-webhook-handler.js +253 -0
  148. package/dist/webhooks/dead-letter-consumer.d.ts +14 -0
  149. package/dist/webhooks/dead-letter-consumer.js +42 -0
  150. package/dist/webhooks/define-registry.d.ts +42 -0
  151. package/dist/webhooks/define-registry.js +56 -0
  152. package/dist/webhooks/once.d.ts +15 -0
  153. package/dist/webhooks/once.js +29 -0
  154. package/dist/webhooks/redact-customer-bodies.d.ts +29 -0
  155. package/dist/webhooks/redact-customer-bodies.js +45 -0
  156. package/dist/webhooks/replay-webhooks.d.ts +39 -0
  157. package/dist/webhooks/replay-webhooks.js +82 -0
  158. package/dist/webhooks/sign-shopify-webhook.d.ts +14 -0
  159. package/dist/webhooks/sign-shopify-webhook.js +31 -0
  160. package/dist/webhooks/sweep-stuck-tasks.d.ts +32 -0
  161. package/dist/webhooks/sweep-stuck-tasks.js +73 -0
  162. package/dist/webhooks/webhook-consumer.d.ts +52 -0
  163. package/dist/webhooks/webhook-consumer.js +132 -0
  164. package/migrations/0001_create_ledger_claims.sql +23 -0
  165. package/migrations/0002_create_journal.sql +76 -0
  166. package/migrations/0003_create_shopify_sessions.sql +30 -0
  167. package/migrations/0004_create_journal_steps.sql +34 -0
  168. package/migrations/0007_create_job_tables.sql +71 -0
  169. package/migrations/0008_add_ledger_completed_at.sql +7 -0
  170. package/migrations/0009_create_webhook_receipts.sql +34 -0
  171. package/migrations/0010_index_webhook_deliveries_received_at.sql +2 -0
  172. package/migrations/0011_add_webhook_task_reason_code.sql +4 -0
  173. package/migrations/0012_rename_webhook_task_action_to_use_case.sql +11 -0
  174. package/migrations/0013_rename_job_tables_to_pipeline.sql +24 -0
  175. package/migrations/0016_add_webhook_task_requeues.sql +3 -0
  176. package/migrations/postgres/0001_create_ledger_claims.sql +13 -0
  177. package/migrations/postgres/0002_create_journal.sql +48 -0
  178. package/migrations/postgres/0003_create_shopify_sessions.sql +12 -0
  179. package/migrations/postgres/0004_create_journal_steps.sql +19 -0
  180. package/migrations/postgres/0005_create_cache_entries.sql +14 -0
  181. package/migrations/postgres/0006_create_queue.sql +42 -0
  182. package/migrations/postgres/0007_create_job_tables.sql +40 -0
  183. package/migrations/postgres/0008_add_ledger_completed_at.sql +3 -0
  184. package/migrations/postgres/0009_create_webhook_receipts.sql +23 -0
  185. package/migrations/postgres/0010_index_webhook_deliveries_received_at.sql +2 -0
  186. package/migrations/postgres/0011_add_webhook_task_reason_code.sql +3 -0
  187. package/migrations/postgres/0012_rename_webhook_task_action_to_use_case.sql +5 -0
  188. package/migrations/postgres/0013_rename_job_tables_to_pipeline.sql +22 -0
  189. package/migrations/postgres/0016_add_webhook_task_requeues.sql +3 -0
  190. package/package.json +144 -4
@@ -0,0 +1,348 @@
1
+ import type { RunId, UnitKey } from './journal.js';
2
+ import type { Toolkit } from './toolkit.js';
3
+ /**
4
+ * DURABLE PIPELINES. The definition is ours; the executor is the platform's.
5
+ *
6
+ * Two executors run the same `PipelineDefinition` value: Cloudflare Workflows when deployed,
7
+ * and the reference executor (docs/decisions/0006) locally, in tests and on
8
+ * Postgres. Nothing in this file may be something only one of them can do.
9
+ * That is why there is no sleep, no wait-for-event and no sub-pipeline here:
10
+ * Workflows has them, the reference executor does not yet, and no domain needs
11
+ * them yet.
12
+ */
13
+ /**
14
+ * What a step may return and a Pipeline may take as input. A step result is stored
15
+ * by the executor and handed to later steps, possibly after a restart, so it
16
+ * must survive serialisation. A `Date`, a `Map`, a class instance or
17
+ * `undefined` would not come back as itself, and the type refuses them.
18
+ *
19
+ * The type cannot refuse `NaN` or `Infinity`, which are numbers but are not
20
+ * JSON. Do not return them.
21
+ *
22
+ * Declare a result shape with `type`, not `interface`. An interface has no
23
+ * implicit index signature, so TypeScript does not accept it as a `JsonValue`
24
+ * even when every field is one.
25
+ */
26
+ export type JsonValue = null | boolean | number | string | readonly JsonValue[] | {
27
+ readonly [key: string]: JsonValue;
28
+ };
29
+ /**
30
+ * `name + '-' + key(input)`, derived by the executor from the Pipeline definition
31
+ * and the input. The caller never chooses it, so a caller that retries its own
32
+ * request with the same input gets `already-started` instead of a second Pipeline.
33
+ *
34
+ * Workflows' rule applies on every executor: at most 100 characters, matching
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.
37
+ *
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.
41
+ */
42
+ export type PipelineInstanceId = string;
43
+ /**
44
+ * WORKFLOWS' MEANING, ON EVERY EXECUTOR.
45
+ *
46
+ * `limit` COUNTS RETRIES, NOT ATTEMPTS. `limit: 3` is four attempts: the first
47
+ * one, then three retries. `limit: 0` is one attempt and no retry. The spike
48
+ * confirmed this against Workflows (docs/spikes/cloudflare-workflows.md, runs
49
+ * 1–3), and the reference executor counts the same way.
50
+ *
51
+ * The delay before retry `n` (1-based) is `delaySeconds` with `constant`
52
+ * backoff, and `delaySeconds * 2 ** (n - 1)` with `exponential`. A 1-second
53
+ * exponential delay waits 1, 2, then 4 seconds (spike, run 2).
54
+ *
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).
58
+ */
59
+ export type StepRetries = {
60
+ readonly limit: number;
61
+ readonly delaySeconds: number;
62
+ readonly backoff: 'constant' | 'exponential';
63
+ };
64
+ /**
65
+ * How a step attempt ends, when it does not throw. This is what a step
66
+ * returns to its executor. The journal's `StepOutcome` is a different thing:
67
+ * the record of how an attempt ended, written for an operator.
68
+ *
69
+ * TWO KINDS OF FAILURE, AND THE TYPE KEEPS THEM APART:
70
+ *
71
+ * - **A fault is a throw.** The target was unavailable, throttled us, timed
72
+ * out. The executor retries the step while `retries.limit` allows. A step
73
+ * that throws a `ToolFault` whose `retryable` is false is still retried:
74
+ * catch it and return `terminal` if retrying cannot help.
75
+ * - **A terminal failure is a value.** The step knows that no retry can
76
+ * succeed: Shopify rejected the input, the record is in a state that forbids
77
+ * the change. It returns `terminal` with a reason code from the domain's
78
+ * closed list, and the executor does not retry it.
79
+ *
80
+ * Terminal is a value and not an error class because it is an expected
81
+ * outcome (rule 8), and because a value cannot be lost by a `catch` that
82
+ * wraps the real error.
83
+ */
84
+ export type PipelineStepOutcome<Result extends JsonValue> = {
85
+ readonly status: 'done';
86
+ readonly result: Result;
87
+ } | {
88
+ readonly status: 'terminal';
89
+ readonly reasonCode: string;
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'>;
97
+ /** What every step attempt, and the exhaustion handler, receives. */
98
+ export type StepContext<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps> = {
99
+ /** `name + '-' + key(input)`. */
100
+ readonly instanceId: PipelineInstanceId;
101
+ /**
102
+ * From `dispatch`. The journal records each step under this run and unit.
103
+ */
104
+ readonly runId: RunId;
105
+ /** `key(input)`. */
106
+ readonly unitKey: UnitKey;
107
+ readonly input: Input;
108
+ /**
109
+ * The stored result of every step before this one, by step name. A later
110
+ * step's result is absent. A result read here is the one the step returned
111
+ * on its successful attempt, read back from storage: after a restart, the
112
+ * step is not run again to recompute it.
113
+ */
114
+ readonly results: Partial<Results>;
115
+ /**
116
+ * What the steps call: the Shopify client, the ledger, the logger. The
117
+ * executor builds it, from the builder registered with this Pipeline's
118
+ * definition (`PipelineRegistration`), in the invocation that runs the step. It
119
+ * is not stored and does not survive a restart: a later attempt gets a
120
+ * newly built one.
121
+ */
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;
129
+ };
130
+ /**
131
+ * One step of a Pipeline. ALL I/O IN A PIPELINE HAPPENS INSIDE A STEP.
132
+ *
133
+ * **A step must be idempotent under concurrent execution, not only under a
134
+ * re-run.** Two attempts of one step can overlap. The reference executor's
135
+ * lease on an instance is advisory: a step that outlives its lease keeps
136
+ * running while the sweeper wakes a second consumer, and only one of them
137
+ * commits a result, but both perform the side effect (docs/decisions/0006).
138
+ * For a Shopify call this means a lookup-then-create keyed on something the
139
+ * step controls. A step that is only safe to re-run in sequence is not safe.
140
+ *
141
+ * A step is also run again from the start when the process dies mid-attempt,
142
+ * on both executors (spike, run 10). A result is stored only when an attempt
143
+ * returns `done`.
144
+ *
145
+ * `timeoutSeconds` FAILS THE ATTEMPT; IT DOES NOT STOP THE BODY. The spike
146
+ * measured that an attempt that times out keeps running and its writes still
147
+ * land (run 5). A timeout is a fault, so the step is retried, and the timed-out
148
+ * attempt may still finish its side effect alongside the retry.
149
+ *
150
+ * Step names are unique within a Pipeline. A stored result is keyed by its step's
151
+ * name, in `StepContext.results` and in the journal's Step rows. The type
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.
154
+ */
155
+ export type Step<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps, Name extends keyof Results & string> = {
156
+ readonly name: Name;
157
+ readonly retries: StepRetries;
158
+ readonly timeoutSeconds: number;
159
+ run(context: StepContext<Input, Results, Deps>): Promise<PipelineStepOutcome<Results[Name]>>;
160
+ };
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> = {
163
+ [Name in keyof Results & string]: Step<Input, Results, Deps, Name>;
164
+ }[keyof Results & string];
165
+ /** Why a Pipeline stopped before its last step. */
166
+ export type Exhaustion = {
167
+ readonly step: string;
168
+ readonly cause: 'terminal';
169
+ readonly reasonCode: string;
170
+ } | {
171
+ readonly step: string;
172
+ readonly cause: 'retries-exhausted';
173
+ }
174
+ /** The step returned a result above the manifest's `stepResultMaxBytes`. */
175
+ | {
176
+ readonly step: string;
177
+ readonly cause: 'result-too-large';
178
+ };
179
+ export type ExhaustionContext<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps> = StepContext<Input, Results, Deps> & {
180
+ readonly exhaustion: Exhaustion;
181
+ };
182
+ /**
183
+ * A LINEAR LIST OF STEPS. Not a graph and not a language (docs/design.md §9).
184
+ *
185
+ * The executor runs the steps in array order, each once it has succeeded, and
186
+ * nothing else. There is no branching, no step chosen at run time and no code
187
+ * between steps: a step that has nothing to do for this input returns `done`
188
+ * at once. Workflows replays the code around its steps after a suspension, so
189
+ * code outside a step would run a different number of times on each executor
190
+ * (spike, "Three more findings").
191
+ *
192
+ * `name` USES `A-Z`, `a-z`, `0-9` AND `_` ONLY, AND NEVER `-`. It is 1 to 64
193
+ * characters long, for example `self_sign_up`. That is Workflows' rule for a
194
+ * Workflow name (docs/platform-facts.md: at most 64 characters, matching
195
+ * `^[a-zA-Z0-9_][a-zA-Z0-9-_]*$`), with `-` removed. Without `-` in a name,
196
+ * the first `-` in an instance id always separates the name from the key, so
197
+ * two Pipelines cannot derive the same id: `a` keyed `b-c` and `a-b` keyed `c`
198
+ * would both give `a-b-c`, and `a-b` is not a valid name. Each name is checked
199
+ * on its own, and an executor can find the Pipeline for an id from its prefix.
200
+ *
201
+ * The executor refuses a Pipeline whose name breaks either rule, the characters or
202
+ * the 64-character limit, when the executor is built (rule 7). It throws, and
203
+ * no Pipeline runs on it. A bad name is a defect in the definition, and it is found
204
+ * when the app starts, not at the first `dispatch`.
205
+ *
206
+ * A PIPELINE IS A PLAIN EXPORTED CONSTANT IN THE DOMAIN, NOT A FACTORY. Routes and
207
+ * tests import it. Both executors also need it when they are built, not only
208
+ * at `dispatch`: a step runs after a restart, when the only thing the
209
+ * executor has is the instance id. So a step does not close over its
210
+ * dependencies. It reads them from `context.deps`, which the executor builds
211
+ * from the builder registered with the definition (`PipelineRegistration`). A Pipeline
212
+ * whose steps need nothing declares `Deps` as `undefined`, and registers the
213
+ * builder `() => undefined`.
214
+ */
215
+ export type PipelineDefinition<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps> = {
216
+ readonly name: string;
217
+ /**
218
+ * The instance's unit, from its input. The executor sets the instance id to
219
+ * `name + '-' + key(input)` and the unit key that the journal records steps
220
+ * under to `key(input)`, so the Pipeline's unit and the journal's unit are the
221
+ * same value.
222
+ *
223
+ * It must be a pure function of the input: the same input gives the same
224
+ * key, on every call and after a restart. A key read from anything else, a
225
+ * random value or the time, turns a retried request into a second Pipeline.
226
+ *
227
+ * The id must fit Workflows' rule (see `PipelineInstanceId`), so a key is at
228
+ * least one character, uses only `a-z`, `A-Z`, `0-9`, `-` and `_`, and is at
229
+ * most `99 - name.length` characters long. `dispatch` throws, and records
230
+ * nothing, when the key breaks the rule (rule 7): a key that does not fit is
231
+ * a defect in the Pipeline, not an outcome.
232
+ */
233
+ readonly key: (input: Input) => UnitKey;
234
+ readonly steps: readonly PipelineStep<Input, Results, Deps>[];
235
+ /**
236
+ * Runs when a step fails terminally, runs out of retries, or returns a
237
+ * result that is too large. It does not run when the Pipeline completes. The
238
+ * self sign-up slice uses it to dead-letter.
239
+ *
240
+ * IT RUNS AT LEAST ONCE, AND NEVER AFTER THE INSTANCE IS `failed`. It is
241
+ * meant to run once, but a crash after it finishes and before the instance
242
+ * is marked `failed` runs it again, and "exactly once" is not achievable
243
+ * across a crash (docs/decisions/0006). So it must be idempotent: the self
244
+ * sign-up slice dead-letters with the reference as the message key.
245
+ *
246
+ * A throw is a fault, and the executor runs the handler again.
247
+ */
248
+ readonly onExhausted?: (context: ExhaustionContext<Input, Results, Deps>) => Promise<void>;
249
+ };
250
+ /**
251
+ * ONE PIPELINE WITH THE BUILDER FOR ITS DEPS, IN THE SHAPE EVERY EXECUTOR FACTORY
252
+ * TAKES. The factories themselves are #69 to #71.
253
+ *
254
+ * A step runs in an invocation that has no request: the reference executor's
255
+ * queue consumer, or Workflows' `WorkflowEntrypoint.run()`. After a restart
256
+ * the executor has only the instance id. So the deps cannot come from the
257
+ * caller of `dispatch`. The executor builds them itself, with the builder
258
+ * registered here when the executor was built:
259
+ *
260
+ * const registrations: readonly PipelineRegistration[] = [
261
+ * (register) => register(selfSignUp, () => createSignUpDeps(env)),
262
+ * ]
263
+ *
264
+ * A registration hands its definition and its builder to the executor's
265
+ * `register` callback. That form lets the type check that the builder returns
266
+ * the definition's `Deps`, while one list holds Pipelines with different inputs,
267
+ * results and deps, without `any`. The executor gets each definition back
268
+ * with its builder's type tied to it.
269
+ *
270
+ * The executor calls the builder in the invocation that runs a step or the
271
+ * exhaustion handler, before it runs it. It may call it once per invocation or
272
+ * once per attempt, so the builder must be cheap and have no side effect. It
273
+ * is synchronous: a dependency that needs I/O to start does that I/O inside
274
+ * its own methods, which the step awaits.
275
+ */
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;
277
+ /**
278
+ * The run comes from the caller, because it is the request's run in the
279
+ * journal and nothing in the input says which run that is. The id and the
280
+ * unit key come from `PipelineDefinition.key`.
281
+ */
282
+ export type DispatchOptions = {
283
+ readonly runId: RunId;
284
+ };
285
+ /**
286
+ * The outcome and the instance's id. A caller never computes an id: it keeps
287
+ * the one returned here.
288
+ *
289
+ * `already-started` is an outcome, not an error (rule 8). Workflows' `create()`
290
+ * throws on an id it still retains, and its adapter turns that throw into this
291
+ * value.
292
+ *
293
+ * It holds only while the executor retains the instance after it ends. After
294
+ * that the same id starts a new instance. The period depends on the executor
295
+ * and, on Workflows, on the plan. Workflows keeps a completed instance for 30
296
+ * days by default on Workers Paid, and for 3 days on Workers Free
297
+ * (docs/platform-facts.md, "Retention of completed instance state"). The
298
+ * reference executor keeps an ended instance for 30 days by default
299
+ * (docs/decisions/0006). A caller that needs idempotency
300
+ * for longer claims in the `Ledger` before it calls `dispatch`.
301
+ */
302
+ export type DispatchResult = {
303
+ readonly status: 'started' | 'already-started';
304
+ /**
305
+ * The instance's id, `name + '-' + key(input)`, as the executor derived it.
306
+ * It is the same on both outcomes: on `already-started` it is the id of
307
+ * the instance that already holds it. Pass it to `status`.
308
+ */
309
+ readonly id: PipelineInstanceId;
310
+ };
311
+ /**
312
+ * The state of one instance, in the words both executors can say.
313
+ *
314
+ * `running` covers everything between `dispatch` and the end: queued, waiting
315
+ * for a retry, in a step, and running the exhaustion handler. Workflows does
316
+ * not distinguish the last of these from the others, so neither does this.
317
+ * `failed` means the exhaustion handler, if there is one, has finished.
318
+ *
319
+ * `unknown` is a value, not a throw: the id was never started, or the instance
320
+ * ended and its retention has passed.
321
+ */
322
+ export type PipelineStatus = {
323
+ readonly status: 'unknown';
324
+ } | {
325
+ readonly status: 'running';
326
+ } | {
327
+ readonly status: 'completed';
328
+ } | {
329
+ readonly status: 'failed';
330
+ };
331
+ /**
332
+ * Dispatch a Pipeline and ask how it is doing. Nothing else, on purpose: every
333
+ * method here has to be one that the reference executor and Workflows can
334
+ * both implement.
335
+ */
336
+ export interface Pipelines {
337
+ /**
338
+ * Records the instance and returns. It does not run a step before it
339
+ * returns: the steps run later, in another invocation, and the caller does
340
+ * not wait for them. Ask `status` for the outcome.
341
+ *
342
+ * `input` is stored unredacted for the instance's lifetime, as is every step
343
+ * result (docs/decisions/0006). Pass ids and references, not customer data.
344
+ */
345
+ dispatch<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps>(definition: PipelineDefinition<Input, Results, Deps>, input: Input, options: DispatchOptions): Promise<DispatchResult>;
346
+ /** `id` is the one that `dispatch` returned. */
347
+ status(id: PipelineInstanceId): Promise<PipelineStatus>;
348
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,55 @@
1
+ import type { DeploymentIdentity } from './identity.js';
2
+ export type MessageId = string & {
3
+ readonly __messageId: unique symbol;
4
+ };
5
+ export type QueueMessage<T> = {
6
+ readonly id: MessageId;
7
+ readonly body: T;
8
+ /** 1 on first delivery. */
9
+ readonly attempt: number;
10
+ readonly enqueuedAt: string;
11
+ readonly identity: DeploymentIdentity;
12
+ };
13
+ export type SendOptions = {
14
+ /**
15
+ * Rejected — never clamped — above the adapter's declared
16
+ * queueDelayMaxSeconds.
17
+ *
18
+ * Must be a finite, non-negative number. Anything else — `NaN`, `Infinity`,
19
+ * a negative — is a caller bug rather than a target condition, and is
20
+ * rejected with a **TypeError, not a ToolFault**, so it escapes the retry
21
+ * envelope. A `NaN` delay would otherwise pass the ceiling check and produce
22
+ * a message that is never visible and therefore never delivered, with no
23
+ * error anywhere. A rejected send leaves no message behind.
24
+ */
25
+ readonly delaySeconds?: number;
26
+ };
27
+ export type RetryOptions = {
28
+ readonly delaySeconds?: number;
29
+ };
30
+ /**
31
+ * At-least-once delivery. MAY reorder.
32
+ * A caller that depends on delivery order is incorrect; the conformance suite
33
+ * asserts that reordering is permitted.
34
+ */
35
+ export interface Queue<T> {
36
+ send(body: T, options?: SendOptions): Promise<MessageId>;
37
+ sendBatch(bodies: readonly T[], options?: SendOptions): Promise<readonly MessageId[]>;
38
+ }
39
+ /**
40
+ * Acknowledgement is PER MESSAGE.
41
+ *
42
+ * There is deliberately no ackAll()/retryAll(). A batch of ten where the fourth fails
43
+ * must leave nine acknowledged and one retried; a convenience that makes the wrong
44
+ * thing easy does not belong on the interface.
45
+ *
46
+ * A message neither acked nor retried by the time the consumer returns is
47
+ * redelivered, on every adapter. On Cloudflare that holds only through
48
+ * `consumeQueueBatch`, because the platform acks it otherwise.
49
+ */
50
+ export interface QueueBatch<T> {
51
+ readonly messages: readonly QueueMessage<T>[];
52
+ ack(id: MessageId): void;
53
+ retry(id: MessageId, options?: RetryOptions): void;
54
+ }
55
+ export type QueueConsumer<T> = (batch: QueueBatch<T>) => Promise<void>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Shopify's own five-method interface, re-exported as a TYPE ONLY.
3
+ *
4
+ * This is the one named exception to "src/contracts/ imports nothing" —
5
+ * docs/decisions/0005 says why. `export type` plus this project's
6
+ * `verbatimModuleSyntax` means the compiler erases this line entirely; no
7
+ * value, no class and no vendor code crosses into the emitted output. The
8
+ * adapters that implement this (src/adapters/memory/session-storage.ts,
9
+ * src/adapters/cloudflare/session-storage.ts) import `Session` — the real
10
+ * class, at runtime — because they have to construct one. That import
11
+ * belongs to them, and does not belong here.
12
+ *
13
+ * eslint.config.js bans every other non-relative import under
14
+ * src/contracts/**, with this file and conformance/session-storage.ts as the
15
+ * two overrides, so the exception stays this narrow mechanically rather than
16
+ * by memory.
17
+ */
18
+ export type { SessionStorage } from '@shopify/shopify-app-session-storage';
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,21 @@
1
+ import type { BlobStore } from './blob-store.js';
2
+ import type { Cache } from './cache.js';
3
+ import type { Clock } from './instant.js';
4
+ import type { Journal } from './journal.js';
5
+ import type { Ledger } from './ledger.js';
6
+ import type { Logger } from './logger.js';
7
+ import type { Queue } from './queue.js';
8
+ export type Toolkit<QueueBody = unknown, WebhookBody = unknown> = {
9
+ readonly cache: Cache;
10
+ readonly blobStore: BlobStore;
11
+ readonly ledger: Ledger;
12
+ readonly journal: Journal;
13
+ readonly logger: Logger;
14
+ readonly clock: Clock;
15
+ readonly queue: Queue<QueueBody>;
16
+ /**
17
+ * Webhook pointers, on a queue of their own rather than `queue`, so that
18
+ * their retries and dead letters are not the app's. docs/decisions/0011.
19
+ */
20
+ readonly webhookQueue: Queue<WebhookBody>;
21
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -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 {};