@anatta.io/tva 0.0.0-stage → 0.1.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 (176) hide show
  1. package/README.md +50 -2
  2. package/dist/actions/action-consumer.d.ts +45 -0
  3. package/dist/actions/action-consumer.js +90 -0
  4. package/dist/actions/action.d.ts +67 -0
  5. package/dist/actions/action.js +12 -0
  6. package/dist/actions/index.d.ts +3 -0
  7. package/dist/actions/index.js +4 -0
  8. package/dist/actions/run-action.d.ts +31 -0
  9. package/dist/actions/run-action.js +113 -0
  10. package/dist/adapters/cloudflare/bindings.d.ts +10 -0
  11. package/dist/adapters/cloudflare/bindings.js +1 -0
  12. package/dist/adapters/cloudflare/blob-store.d.ts +39 -0
  13. package/dist/adapters/cloudflare/blob-store.js +95 -0
  14. package/dist/adapters/cloudflare/cache.d.ts +14 -0
  15. package/dist/adapters/cloudflare/cache.js +48 -0
  16. package/dist/adapters/cloudflare/faults.d.ts +7 -0
  17. package/dist/adapters/cloudflare/faults.js +39 -0
  18. package/dist/adapters/cloudflare/index.d.ts +15 -0
  19. package/dist/adapters/cloudflare/index.js +16 -0
  20. package/dist/adapters/cloudflare/jobs.d.ts +97 -0
  21. package/dist/adapters/cloudflare/jobs.js +218 -0
  22. package/dist/adapters/cloudflare/journal.d.ts +107 -0
  23. package/dist/adapters/cloudflare/journal.js +305 -0
  24. package/dist/adapters/cloudflare/ledger.d.ts +14 -0
  25. package/dist/adapters/cloudflare/ledger.js +108 -0
  26. package/dist/adapters/cloudflare/logger.d.ts +22 -0
  27. package/dist/adapters/cloudflare/logger.js +49 -0
  28. package/dist/adapters/cloudflare/manifest.d.ts +81 -0
  29. package/dist/adapters/cloudflare/manifest.js +81 -0
  30. package/dist/adapters/cloudflare/queue.d.ts +80 -0
  31. package/dist/adapters/cloudflare/queue.js +177 -0
  32. package/dist/adapters/cloudflare/retention.d.ts +24 -0
  33. package/dist/adapters/cloudflare/retention.js +103 -0
  34. package/dist/adapters/cloudflare/session-storage.d.ts +27 -0
  35. package/dist/adapters/cloudflare/session-storage.js +78 -0
  36. package/dist/adapters/cloudflare/toolkit.d.ts +16 -0
  37. package/dist/adapters/cloudflare/toolkit.js +57 -0
  38. package/dist/adapters/cloudflare/workflow-jobs.d.ts +57 -0
  39. package/dist/adapters/cloudflare/workflow-jobs.js +319 -0
  40. package/dist/adapters/journal-records.d.ts +79 -0
  41. package/dist/adapters/journal-records.js +74 -0
  42. package/dist/adapters/memory/blob-store.d.ts +9 -0
  43. package/dist/adapters/memory/blob-store.js +19 -0
  44. package/dist/adapters/memory/cache.d.ts +13 -0
  45. package/dist/adapters/memory/cache.js +36 -0
  46. package/dist/adapters/memory/clock.d.ts +1 -0
  47. package/dist/adapters/memory/clock.js +4 -0
  48. package/dist/adapters/memory/index.d.ts +11 -0
  49. package/dist/adapters/memory/index.js +11 -0
  50. package/dist/adapters/memory/jobs.d.ts +62 -0
  51. package/dist/adapters/memory/jobs.js +219 -0
  52. package/dist/adapters/memory/journal.d.ts +34 -0
  53. package/dist/adapters/memory/journal.js +135 -0
  54. package/dist/adapters/memory/ledger.d.ts +9 -0
  55. package/dist/adapters/memory/ledger.js +33 -0
  56. package/dist/adapters/memory/logger.d.ts +16 -0
  57. package/dist/adapters/memory/logger.js +21 -0
  58. package/dist/adapters/memory/manifest.d.ts +59 -0
  59. package/dist/adapters/memory/manifest.js +59 -0
  60. package/dist/adapters/memory/queue.d.ts +20 -0
  61. package/dist/adapters/memory/queue.js +102 -0
  62. package/dist/adapters/memory/session-storage.d.ts +20 -0
  63. package/dist/adapters/memory/session-storage.js +33 -0
  64. package/dist/adapters/memory/toolkit.d.ts +8 -0
  65. package/dist/adapters/memory/toolkit.js +31 -0
  66. package/dist/adapters/postgres/cache.d.ts +17 -0
  67. package/dist/adapters/postgres/cache.js +69 -0
  68. package/dist/adapters/postgres/config.d.ts +27 -0
  69. package/dist/adapters/postgres/config.js +45 -0
  70. package/dist/adapters/postgres/faults.d.ts +14 -0
  71. package/dist/adapters/postgres/faults.js +47 -0
  72. package/dist/adapters/postgres/index.d.ts +12 -0
  73. package/dist/adapters/postgres/index.js +12 -0
  74. package/dist/adapters/postgres/journal.d.ts +83 -0
  75. package/dist/adapters/postgres/journal.js +314 -0
  76. package/dist/adapters/postgres/ledger.d.ts +16 -0
  77. package/dist/adapters/postgres/ledger.js +97 -0
  78. package/dist/adapters/postgres/logger.d.ts +19 -0
  79. package/dist/adapters/postgres/logger.js +37 -0
  80. package/dist/adapters/postgres/manifest.d.ts +52 -0
  81. package/dist/adapters/postgres/manifest.js +53 -0
  82. package/dist/adapters/postgres/migrate.d.ts +20 -0
  83. package/dist/adapters/postgres/migrate.js +96 -0
  84. package/dist/adapters/postgres/queue.d.ts +64 -0
  85. package/dist/adapters/postgres/queue.js +333 -0
  86. package/dist/adapters/postgres/retention.d.ts +18 -0
  87. package/dist/adapters/postgres/retention.js +104 -0
  88. package/dist/adapters/postgres/session-storage.d.ts +20 -0
  89. package/dist/adapters/postgres/session-storage.js +71 -0
  90. package/dist/adapters/postgres/toolkit.d.ts +25 -0
  91. package/dist/adapters/postgres/toolkit.js +58 -0
  92. package/dist/adapters/postgres/with-client.d.ts +11 -0
  93. package/dist/adapters/postgres/with-client.js +29 -0
  94. package/dist/adapters/reference-executor.d.ts +171 -0
  95. package/dist/adapters/reference-executor.js +564 -0
  96. package/dist/adapters/retention.d.ts +18 -0
  97. package/dist/adapters/retention.js +13 -0
  98. package/dist/adapters/s3/blob-store.d.ts +35 -0
  99. package/dist/adapters/s3/blob-store.js +92 -0
  100. package/dist/adapters/s3/faults.d.ts +8 -0
  101. package/dist/adapters/s3/faults.js +34 -0
  102. package/dist/adapters/s3/index.d.ts +2 -0
  103. package/dist/adapters/s3/index.js +2 -0
  104. package/dist/adapters/session-envelope.d.ts +21 -0
  105. package/dist/adapters/session-envelope.js +122 -0
  106. package/dist/adapters/system-clock.d.ts +8 -0
  107. package/dist/adapters/system-clock.js +8 -0
  108. package/dist/contracts/blob-store.d.ts +11 -0
  109. package/dist/contracts/blob-store.js +1 -0
  110. package/dist/contracts/cache.d.ts +27 -0
  111. package/dist/contracts/cache.js +1 -0
  112. package/dist/contracts/duration.d.ts +23 -0
  113. package/dist/contracts/duration.js +27 -0
  114. package/dist/contracts/faults.d.ts +28 -0
  115. package/dist/contracts/faults.js +29 -0
  116. package/dist/contracts/identity.d.ts +12 -0
  117. package/dist/contracts/identity.js +1 -0
  118. package/dist/contracts/index.d.ts +14 -0
  119. package/dist/contracts/index.js +15 -0
  120. package/dist/contracts/instant.d.ts +17 -0
  121. package/dist/contracts/instant.js +12 -0
  122. package/dist/contracts/jobs.d.ts +335 -0
  123. package/dist/contracts/jobs.js +1 -0
  124. package/dist/contracts/journal.d.ts +186 -0
  125. package/dist/contracts/journal.js +10 -0
  126. package/dist/contracts/ledger.d.ts +34 -0
  127. package/dist/contracts/ledger.js +1 -0
  128. package/dist/contracts/logger.d.ts +11 -0
  129. package/dist/contracts/logger.js +1 -0
  130. package/dist/contracts/manifest.d.ts +37 -0
  131. package/dist/contracts/manifest.js +30 -0
  132. package/dist/contracts/queue.d.ts +55 -0
  133. package/dist/contracts/queue.js +1 -0
  134. package/dist/contracts/session-storage.d.ts +18 -0
  135. package/dist/contracts/session-storage.js +1 -0
  136. package/dist/contracts/toolkit.d.ts +21 -0
  137. package/dist/contracts/toolkit.js +1 -0
  138. package/dist/schedule/schedule.d.ts +40 -0
  139. package/dist/schedule/schedule.js +135 -0
  140. package/dist/webhooks/create-webhook-handler.d.ts +63 -0
  141. package/dist/webhooks/create-webhook-handler.js +246 -0
  142. package/dist/webhooks/dead-letter-consumer.d.ts +14 -0
  143. package/dist/webhooks/dead-letter-consumer.js +42 -0
  144. package/dist/webhooks/define-registry.d.ts +42 -0
  145. package/dist/webhooks/define-registry.js +56 -0
  146. package/dist/webhooks/once.d.ts +15 -0
  147. package/dist/webhooks/once.js +29 -0
  148. package/dist/webhooks/redact-customer-bodies.d.ts +29 -0
  149. package/dist/webhooks/redact-customer-bodies.js +45 -0
  150. package/dist/webhooks/replay-webhooks.d.ts +39 -0
  151. package/dist/webhooks/replay-webhooks.js +79 -0
  152. package/dist/webhooks/sign-shopify-webhook.d.ts +14 -0
  153. package/dist/webhooks/sign-shopify-webhook.js +31 -0
  154. package/dist/webhooks/webhook-consumer.d.ts +51 -0
  155. package/dist/webhooks/webhook-consumer.js +127 -0
  156. package/migrations/0001_create_ledger_claims.sql +23 -0
  157. package/migrations/0002_create_journal.sql +76 -0
  158. package/migrations/0003_create_shopify_sessions.sql +30 -0
  159. package/migrations/0004_create_journal_steps.sql +34 -0
  160. package/migrations/0007_create_job_tables.sql +71 -0
  161. package/migrations/0008_add_ledger_completed_at.sql +7 -0
  162. package/migrations/0009_create_webhook_receipts.sql +34 -0
  163. package/migrations/0010_index_webhook_deliveries_received_at.sql +2 -0
  164. package/migrations/0011_add_webhook_task_reason_code.sql +4 -0
  165. package/migrations/postgres/0001_create_ledger_claims.sql +13 -0
  166. package/migrations/postgres/0002_create_journal.sql +48 -0
  167. package/migrations/postgres/0003_create_shopify_sessions.sql +12 -0
  168. package/migrations/postgres/0004_create_journal_steps.sql +19 -0
  169. package/migrations/postgres/0005_create_cache_entries.sql +14 -0
  170. package/migrations/postgres/0006_create_queue.sql +42 -0
  171. package/migrations/postgres/0007_create_job_tables.sql +40 -0
  172. package/migrations/postgres/0008_add_ledger_completed_at.sql +3 -0
  173. package/migrations/postgres/0009_create_webhook_receipts.sql +23 -0
  174. package/migrations/postgres/0010_index_webhook_deliveries_received_at.sql +2 -0
  175. package/migrations/postgres/0011_add_webhook_task_reason_code.sql +3 -0
  176. package/package.json +137 -4
@@ -0,0 +1,335 @@
1
+ import type { RunId, UnitKey } from './journal.js';
2
+ /**
3
+ * DURABLE JOBS. The definition is ours; the executor is the platform's.
4
+ *
5
+ * Two executors run the same `Job` value: Cloudflare Workflows when deployed,
6
+ * and the reference executor (docs/decisions/0006) locally, in tests and on
7
+ * 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
+ * Workflows has them, the reference executor does not yet, and no domain needs
10
+ * them yet.
11
+ */
12
+ /**
13
+ * What a step may return and a Job may take as input. A step result is stored
14
+ * by the executor and handed to later steps, possibly after a restart, so it
15
+ * must survive serialisation. A `Date`, a `Map`, a class instance or
16
+ * `undefined` would not come back as itself, and the type refuses them.
17
+ *
18
+ * The type cannot refuse `NaN` or `Infinity`, which are numbers but are not
19
+ * JSON. Do not return them.
20
+ *
21
+ * Declare a result shape with `type`, not `interface`. An interface has no
22
+ * implicit index signature, so TypeScript does not accept it as a `JsonValue`
23
+ * even when every field is one.
24
+ */
25
+ export type JsonValue = null | boolean | number | string | readonly JsonValue[] | {
26
+ readonly [key: string]: JsonValue;
27
+ };
28
+ /**
29
+ * `name + '-' + key(input)`, derived by the executor from the Job definition
30
+ * 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
+ *
33
+ * 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.
36
+ *
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.
40
+ */
41
+ export type JobInstanceId = string;
42
+ /**
43
+ * WORKFLOWS' MEANING, ON EVERY EXECUTOR.
44
+ *
45
+ * `limit` COUNTS RETRIES, NOT ATTEMPTS. `limit: 3` is four attempts: the first
46
+ * one, then three retries. `limit: 0` is one attempt and no retry. The spike
47
+ * confirmed this against Workflows (docs/spikes/cloudflare-workflows.md, runs
48
+ * 1–3), and the reference executor counts the same way.
49
+ *
50
+ * The delay before retry `n` (1-based) is `delaySeconds` with `constant`
51
+ * backoff, and `delaySeconds * 2 ** (n - 1)` with `exponential`. A 1-second
52
+ * exponential delay waits 1, 2, then 4 seconds (spike, run 2).
53
+ *
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.
57
+ */
58
+ export type StepRetries = {
59
+ readonly limit: number;
60
+ readonly delaySeconds: number;
61
+ readonly backoff: 'constant' | 'exponential';
62
+ };
63
+ /**
64
+ * How a step attempt ends, when it does not throw. This is what a step
65
+ * returns to its executor. The journal's `StepOutcome` is a different thing:
66
+ * the record of how an attempt ended, written for an operator.
67
+ *
68
+ * TWO KINDS OF FAILURE, AND THE TYPE KEEPS THEM APART:
69
+ *
70
+ * - **A fault is a throw.** The target was unavailable, throttled us, timed
71
+ * out. The executor retries the step while `retries.limit` allows. A step
72
+ * that throws a `ToolFault` whose `retryable` is false is still retried:
73
+ * catch it and return `terminal` if retrying cannot help.
74
+ * - **A terminal failure is a value.** The step knows that no retry can
75
+ * succeed: Shopify rejected the input, the record is in a state that forbids
76
+ * the change. It returns `terminal` with a reason code from the domain's
77
+ * closed list, and the executor does not retry it.
78
+ *
79
+ * Terminal is a value and not an error class because it is an expected
80
+ * outcome (rule 8), and because a value cannot be lost by a `catch` that
81
+ * wraps the real error.
82
+ */
83
+ export type JobStepOutcome<Result extends JsonValue> = {
84
+ readonly status: 'done';
85
+ readonly result: Result;
86
+ } | {
87
+ readonly status: 'terminal';
88
+ readonly reasonCode: string;
89
+ };
90
+ /** What every step attempt, and the exhaustion handler, receives. */
91
+ export type StepContext<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps> = {
92
+ /** `name + '-' + key(input)`. */
93
+ readonly instanceId: JobInstanceId;
94
+ /**
95
+ * From `dispatch`. The journal records each step under this run and unit.
96
+ */
97
+ readonly runId: RunId;
98
+ /** `key(input)`. */
99
+ readonly unitKey: UnitKey;
100
+ readonly input: Input;
101
+ /**
102
+ * The stored result of every step before this one, by step name. A later
103
+ * step's result is absent. A result read here is the one the step returned
104
+ * on its successful attempt, read back from storage: after a restart, the
105
+ * step is not run again to recompute it.
106
+ */
107
+ readonly results: Partial<Results>;
108
+ /**
109
+ * 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
112
+ * is not stored and does not survive a restart: a later attempt gets a
113
+ * newly built one.
114
+ */
115
+ readonly deps: Deps;
116
+ };
117
+ /**
118
+ * One step of a Job. ALL I/O IN A JOB HAPPENS INSIDE A STEP.
119
+ *
120
+ * **A step must be idempotent under concurrent execution, not only under a
121
+ * re-run.** Two attempts of one step can overlap. The reference executor's
122
+ * lease on an instance is advisory: a step that outlives its lease keeps
123
+ * running while the sweeper wakes a second consumer, and only one of them
124
+ * commits a result, but both perform the side effect (docs/decisions/0006).
125
+ * For a Shopify call this means a lookup-then-create keyed on something the
126
+ * step controls. A step that is only safe to re-run in sequence is not safe.
127
+ *
128
+ * A step is also run again from the start when the process dies mid-attempt,
129
+ * on both executors (spike, run 10). A result is stored only when an attempt
130
+ * returns `done`.
131
+ *
132
+ * `timeoutSeconds` FAILS THE ATTEMPT; IT DOES NOT STOP THE BODY. The spike
133
+ * measured that an attempt that times out keeps running and its writes still
134
+ * land (run 5). A timeout is a fault, so the step is retried, and the timed-out
135
+ * attempt may still finish its side effect alongside the retry.
136
+ *
137
+ * Step names are unique within a Job. A stored result is keyed by its step's
138
+ * 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.
141
+ */
142
+ export type Step<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps, Name extends keyof Results & string> = {
143
+ readonly name: Name;
144
+ readonly retries: StepRetries;
145
+ readonly timeoutSeconds: number;
146
+ run(context: StepContext<Input, Results, Deps>): Promise<JobStepOutcome<Results[Name]>>;
147
+ };
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> = {
150
+ [Name in keyof Results & string]: Step<Input, Results, Deps, Name>;
151
+ }[keyof Results & string];
152
+ /** Why a Job stopped before its last step. */
153
+ export type Exhaustion = {
154
+ readonly step: string;
155
+ readonly cause: 'terminal';
156
+ readonly reasonCode: string;
157
+ } | {
158
+ readonly step: string;
159
+ readonly cause: 'retries-exhausted';
160
+ }
161
+ /** The step returned a result above the manifest's `stepResultMaxBytes`. */
162
+ | {
163
+ readonly step: string;
164
+ readonly cause: 'result-too-large';
165
+ };
166
+ export type ExhaustionContext<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps> = StepContext<Input, Results, Deps> & {
167
+ readonly exhaustion: Exhaustion;
168
+ };
169
+ /**
170
+ * A LINEAR LIST OF STEPS. Not a graph and not a language (docs/design.md §9).
171
+ *
172
+ * The executor runs the steps in array order, each once it has succeeded, and
173
+ * nothing else. There is no branching, no step chosen at run time and no code
174
+ * between steps: a step that has nothing to do for this input returns `done`
175
+ * at once. Workflows replays the code around its steps after a suspension, so
176
+ * code outside a step would run a different number of times on each executor
177
+ * (spike, "Three more findings").
178
+ *
179
+ * `name` USES `A-Z`, `a-z`, `0-9` AND `_` ONLY, AND NEVER `-`. It is 1 to 64
180
+ * characters long, for example `self_sign_up`. That is Workflows' rule for a
181
+ * Workflow name (docs/platform-facts.md: at most 64 characters, matching
182
+ * `^[a-zA-Z0-9_][a-zA-Z0-9-_]*$`), with `-` removed. Without `-` in a name,
183
+ * 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`
185
+ * 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.
187
+ *
188
+ * The executor refuses a Job whose name breaks either rule, the characters or
189
+ * 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
191
+ * when the app starts, not at the first `dispatch`.
192
+ *
193
+ * A JOB IS A PLAIN EXPORTED CONSTANT IN THE DOMAIN, NOT A FACTORY. Routes and
194
+ * tests import it. Both executors also need it when they are built, not only
195
+ * at `dispatch`: a step runs after a restart, when the only thing the
196
+ * executor has is the instance id. So a step does not close over its
197
+ * dependencies. It reads them from `context.deps`, which the executor builds
198
+ * from the builder registered with the definition (`JobRegistration`). A Job
199
+ * whose steps need nothing declares `Deps` as `undefined`, and registers the
200
+ * builder `() => undefined`.
201
+ */
202
+ export type Job<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps> = {
203
+ readonly name: string;
204
+ /**
205
+ * The instance's unit, from its input. The executor sets the instance id to
206
+ * `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
208
+ * same value.
209
+ *
210
+ * It must be a pure function of the input: the same input gives the same
211
+ * 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.
213
+ *
214
+ * The id must fit Workflows' rule (see `JobInstanceId`), so a key is at
215
+ * least one character, uses only `a-z`, `A-Z`, `0-9`, `-` and `_`, and is at
216
+ * most `99 - name.length` characters long. `dispatch` throws, and records
217
+ * 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.
219
+ */
220
+ readonly key: (input: Input) => UnitKey;
221
+ readonly steps: readonly JobStep<Input, Results, Deps>[];
222
+ /**
223
+ * 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
225
+ * self sign-up slice uses it to dead-letter.
226
+ *
227
+ * IT RUNS AT LEAST ONCE, AND NEVER AFTER THE INSTANCE IS `failed`. It is
228
+ * meant to run once, but a crash after it finishes and before the instance
229
+ * is marked `failed` runs it again, and "exactly once" is not achievable
230
+ * across a crash (docs/decisions/0006). So it must be idempotent: the self
231
+ * sign-up slice dead-letters with the reference as the message key.
232
+ *
233
+ * A throw is a fault, and the executor runs the handler again.
234
+ */
235
+ readonly onExhausted?: (context: ExhaustionContext<Input, Results, Deps>) => Promise<void>;
236
+ };
237
+ /**
238
+ * ONE JOB WITH THE BUILDER FOR ITS DEPS, IN THE SHAPE EVERY EXECUTOR FACTORY
239
+ * TAKES. The factories themselves are #69 to #71.
240
+ *
241
+ * A step runs in an invocation that has no request: the reference executor's
242
+ * queue consumer, or Workflows' `WorkflowEntrypoint.run()`. After a restart
243
+ * the executor has only the instance id. So the deps cannot come from the
244
+ * caller of `dispatch`. The executor builds them itself, with the builder
245
+ * registered here when the executor was built:
246
+ *
247
+ * const registrations: readonly JobRegistration[] = [
248
+ * (register) => register(selfSignUp, () => createSignUpDeps(env)),
249
+ * ]
250
+ *
251
+ * A registration hands its definition and its builder to the executor's
252
+ * `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,
254
+ * results and deps, without `any`. The executor gets each definition back
255
+ * with its builder's type tied to it.
256
+ *
257
+ * The executor calls the builder in the invocation that runs a step or the
258
+ * exhaustion handler, before it runs it. It may call it once per invocation or
259
+ * once per attempt, so the builder must be cheap and have no side effect. It
260
+ * is synchronous: a dependency that needs I/O to start does that I/O inside
261
+ * its own methods, which the step awaits.
262
+ */
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;
264
+ /**
265
+ * The run comes from the caller, because it is the request's run in the
266
+ * journal and nothing in the input says which run that is. The id and the
267
+ * unit key come from `Job.key`.
268
+ */
269
+ export type DispatchOptions = {
270
+ readonly runId: RunId;
271
+ };
272
+ /**
273
+ * The outcome and the instance's id. A caller never computes an id: it keeps
274
+ * the one returned here.
275
+ *
276
+ * `already-started` is an outcome, not an error (rule 8). Workflows' `create()`
277
+ * throws on an id it still retains, and its adapter turns that throw into this
278
+ * value.
279
+ *
280
+ * It holds only while the executor retains the instance after it ends. After
281
+ * that the same id starts a new instance. The period depends on the executor
282
+ * and, on Workflows, on the plan. Workflows keeps a completed instance for 30
283
+ * days by default on Workers Paid, and for 3 days on Workers Free
284
+ * (docs/platform-facts.md, "Retention of completed instance state"). The
285
+ * reference executor keeps an ended instance for 30 days by default
286
+ * (docs/decisions/0006). A caller that needs idempotency
287
+ * for longer claims in the `Ledger` before it calls `dispatch`.
288
+ */
289
+ export type DispatchResult = {
290
+ readonly status: 'started' | 'already-started';
291
+ /**
292
+ * The instance's id, `name + '-' + key(input)`, as the executor derived it.
293
+ * It is the same on both outcomes: on `already-started` it is the id of
294
+ * the instance that already holds it. Pass it to `status`.
295
+ */
296
+ readonly id: JobInstanceId;
297
+ };
298
+ /**
299
+ * The state of one instance, in the words both executors can say.
300
+ *
301
+ * `running` covers everything between `dispatch` and the end: queued, waiting
302
+ * for a retry, in a step, and running the exhaustion handler. Workflows does
303
+ * not distinguish the last of these from the others, so neither does this.
304
+ * `failed` means the exhaustion handler, if there is one, has finished.
305
+ *
306
+ * `unknown` is a value, not a throw: the id was never started, or the instance
307
+ * ended and its retention has passed.
308
+ */
309
+ export type JobStatus = {
310
+ readonly status: 'unknown';
311
+ } | {
312
+ readonly status: 'running';
313
+ } | {
314
+ readonly status: 'completed';
315
+ } | {
316
+ readonly status: 'failed';
317
+ };
318
+ /**
319
+ * Dispatch a Job and ask how it is doing. Nothing else, on purpose: every
320
+ * method here has to be one that the reference executor and Workflows can
321
+ * both implement.
322
+ */
323
+ export interface Jobs {
324
+ /**
325
+ * Records the instance and returns. It does not run a step before it
326
+ * returns: the steps run later, in another invocation, and the caller does
327
+ * not wait for them. Ask `status` for the outcome.
328
+ *
329
+ * `input` is stored unredacted for the instance's lifetime, as is every step
330
+ * result (docs/decisions/0006). Pass ids and references, not customer data.
331
+ */
332
+ dispatch<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps>(definition: Job<Input, Results, Deps>, input: Input, options: DispatchOptions): Promise<DispatchResult>;
333
+ /** `id` is the one that `dispatch` returned. */
334
+ status(id: JobInstanceId): Promise<JobStatus>;
335
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,186 @@
1
+ import type { DeploymentIdentity } from './identity.js';
2
+ import type { Instant } from './instant.js';
3
+ /**
4
+ * The RUN JOURNAL. Distinct from the Ledger: this one is queryable, it is not on the
5
+ * correctness path, and it may be lossy under pressure without breaking anything.
6
+ * The one exception is webhook receipts, which are required writes: see below.
7
+ *
8
+ * Four grains. The UNIT is the grain an operator thinks in — they have an identifier
9
+ * and one question about it. A surface that makes them start from a run has failed.
10
+ */
11
+ export type RunId = string;
12
+ export type UnitKey = string;
13
+ export type UnitOutcome = 'written' | 'skipped' | 'failed' | 'unchanged' | 'would-write';
14
+ export type RunRow = {
15
+ readonly runId: RunId;
16
+ readonly job: string;
17
+ readonly trigger: 'schedule' | 'http' | 'queue' | 'admin' | 'replay';
18
+ readonly mode: 'live' | 'dry-run';
19
+ readonly startedAt: Instant;
20
+ readonly identity: DeploymentIdentity;
21
+ };
22
+ export type UnitRow = {
23
+ readonly runId: RunId;
24
+ readonly unitKey: UnitKey;
25
+ readonly unitType: string;
26
+ /** When this unit reached its outcome. Every time-windowed query needs it. */
27
+ readonly recordedAt: Instant;
28
+ readonly outcome: UnitOutcome;
29
+ /** From the domain's closed list. Required on anything that is not a plain success. */
30
+ readonly reasonCode?: string;
31
+ /** Hash of the composed plan. Two runs, same hash, no work to do. */
32
+ readonly planHash?: string;
33
+ readonly planRef?: string;
34
+ readonly durationMs: number;
35
+ readonly externalIds?: Readonly<Record<string, string>>;
36
+ };
37
+ export type StepOutcome = 'ok' | 'retry' | 'failed' | 'superseded';
38
+ /**
39
+ * One attempt of one Job step on one unit. The Step grain of plan §9.2.
40
+ *
41
+ * **A record, not state.** Nothing reads a step row to decide what runs next:
42
+ * the reference executor keeps its own step state, and Workflows keeps its
43
+ * own. This row may be lossy, like every journal row, and a missing one costs
44
+ * visibility, never correctness. `docs/decisions/0006`.
45
+ *
46
+ * It holds an outcome, never a step result. There is no field for one, so there
47
+ * is nothing to redact on the way in beyond what the caller puts in `step` and
48
+ * `reasonCode`, which come from code, not from a customer.
49
+ */
50
+ export type StepRow = {
51
+ readonly runId: RunId;
52
+ readonly unitKey: UnitKey;
53
+ /** The step's name in its Job definition. */
54
+ readonly step: string;
55
+ /** 1 for the first attempt. A retry writes a new row with the next number. */
56
+ readonly attempt: number;
57
+ /**
58
+ * `superseded`: another consumer committed this step first, so this
59
+ * attempt's result was discarded. Not a failure.
60
+ */
61
+ readonly outcome: StepOutcome;
62
+ /** From the domain's closed list. Required on anything that is not `ok`. */
63
+ readonly reasonCode?: string;
64
+ readonly durationMs: number;
65
+ /** When this attempt ended. `unit` orders steps by it, then by write order. */
66
+ readonly recordedAt: Instant;
67
+ };
68
+ export type CallRow = {
69
+ readonly runId: RunId;
70
+ readonly unitKey: UnitKey;
71
+ readonly system: string;
72
+ /** Our name for the operation, never a URL. */
73
+ readonly operation: string;
74
+ readonly status: 'intent' | 'ok' | 'failed' | 'ambiguous';
75
+ readonly httpStatus?: number;
76
+ readonly idempotencyKey?: string;
77
+ readonly durationMs?: number;
78
+ };
79
+ export type ReasonCount = {
80
+ readonly reasonCode: string;
81
+ readonly count: number;
82
+ };
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
86
+ * failure is `done`, and its unit row says why.
87
+ */
88
+ export type TaskState = 'received' | 'processing' | 'done' | 'failed' | 'dead' | 'replayed';
89
+ /** The state a task moves to, and the states it may move from. `received` is only ever the first. */
90
+ export declare const TASK_TRANSITIONS: Readonly<Record<Exclude<TaskState, 'received'>, readonly TaskState[]>>;
91
+ /** One webhook delivery, as the edge accepted it. */
92
+ export type DeliveryRow = {
93
+ /** The edge's dedup key, `source:shop:topic:webhookId`. */
94
+ readonly deliveryId: string;
95
+ readonly source: string;
96
+ readonly topic: string;
97
+ readonly shop: string;
98
+ readonly webhookId: string;
99
+ /** The raw body's key in the blob store. */
100
+ readonly bodyKey: string;
101
+ readonly receivedAt: Instant;
102
+ };
103
+ export type TaskRow = {
104
+ readonly deliveryId: string;
105
+ /** The Action's name. */
106
+ readonly action: string;
107
+ readonly state: TaskState;
108
+ /** When the task last moved. */
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. */
111
+ readonly reasonCode?: string;
112
+ };
113
+ /** Where `deadTasks` resumes: the last row of the previous page. */
114
+ export type TaskCursor = Pick<TaskRow, 'updatedAt' | 'deliveryId' | 'action'>;
115
+ /**
116
+ * Named queries only. No method takes SQL.
117
+ *
118
+ * One method per question the operator surface asks. A new screen means a new named
119
+ * query, which is a moment of review rather than an ad-hoc SELECT in a route.
120
+ */
121
+ export interface Journal {
122
+ startRun(row: RunRow): Promise<void>;
123
+ finishRun(runId: RunId, endedAt: Instant): Promise<void>;
124
+ /** Batched per unit: one write, not one per step. */
125
+ recordUnit(unit: UnitRow, calls: readonly CallRow[]): Promise<void>;
126
+ /**
127
+ * One step row, written after each attempt. Deliberately not batched per
128
+ * unit: the step has already done its work, and a row held back for a batch
129
+ * is lost with the process that held it.
130
+ *
131
+ * **Never rejects.** A failed write is logged through `Logger` and the call
132
+ * resolves, because failing a step that already did its work would repeat the
133
+ * work to record it. This is the one journal write that does not fail the
134
+ * unit (plan §9.3, `docs/decisions/0006`).
135
+ *
136
+ * Append-only. A step row is never a correction, so writing the same row
137
+ * twice records it twice rather than merging it.
138
+ *
139
+ * There is no query that reads step rows back by Job instance, and there must
140
+ * not be one: that would make the journal the executor's state store, which
141
+ * decision 0006 rejected. Step rows are read only through `unit`.
142
+ */
143
+ recordStep(step: StepRow): Promise<void>;
144
+ unitsForRun(runId: RunId, limit?: number): Promise<readonly UnitRow[]>;
145
+ /**
146
+ * The unit with its steps, oldest attempt first, and its calls.
147
+ *
148
+ * Undefined until the unit row is recorded, even when step rows exist: the
149
+ * unit row is what says a unit exists. Re-recording a unit replaces its calls
150
+ * and leaves its steps alone, because they were written by other attempts.
151
+ */
152
+ unit(runId: RunId, unitKey: UnitKey): Promise<{
153
+ unit: UnitRow;
154
+ steps: readonly StepRow[];
155
+ calls: readonly CallRow[];
156
+ } | undefined>;
157
+ latestForUnit(unitKey: UnitKey): Promise<UnitRow | undefined>;
158
+ failuresByReason(since: Instant): Promise<readonly ReasonCount[]>;
159
+ recentRuns(limit?: number): Promise<readonly RunRow[]>;
160
+ /**
161
+ * The delivery and one `received` task per Action, in one atomic write.
162
+ * Recording it again, as a retried delivery does, changes no row already
163
+ * there: it adds only the tasks it lacks.
164
+ */
165
+ recordDelivery(delivery: DeliveryRow, actions: readonly string[]): Promise<void>;
166
+ /**
167
+ * Moves a task to `to` only from a state `TASK_TRANSITIONS` allows, in one
168
+ * conditional update. False when the task is in another state or missing.
169
+ * Writes `reasonCode`, or clears it when absent: a reason describes the
170
+ * state it came with.
171
+ */
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
+ delivery(deliveryId: string): Promise<{
175
+ delivery: DeliveryRow;
176
+ tasks: readonly TaskRow[];
177
+ } | undefined>;
178
+ /** Dead tasks, oldest first, keyset-paged by `after`. */
179
+ deadTasks(options?: {
180
+ readonly action?: string;
181
+ readonly after?: TaskCursor;
182
+ readonly limit?: number;
183
+ }): Promise<readonly TaskRow[]>;
184
+ /** Tasks still `received` or `processing` that last moved before `before`, oldest first. */
185
+ stuckTasks(before: Instant, limit?: number): Promise<readonly TaskRow[]>;
186
+ }
@@ -0,0 +1,10 @@
1
+ /** The state a task moves to, and the states it may move from. `received` is only ever the first. */
2
+ export const TASK_TRANSITIONS = {
3
+ // From `processing` too: a queue redelivers after a consumer crashed mid-run.
4
+ // From `replayed`: a replay sends the message again, and it runs as any other.
5
+ processing: ['received', 'failed', 'processing', 'replayed'],
6
+ done: ['processing'],
7
+ failed: ['processing'],
8
+ dead: ['processing'],
9
+ replayed: ['dead'],
10
+ };
@@ -0,0 +1,34 @@
1
+ export type ClaimResult = {
2
+ readonly status: 'claimed';
3
+ }
4
+ /** Another holder's lease is live and it has not completed. */
5
+ | {
6
+ readonly status: 'in-progress';
7
+ readonly claimedAt: string;
8
+ } | {
9
+ readonly status: 'completed';
10
+ readonly completedAt: string;
11
+ };
12
+ /**
13
+ * Idempotency. Key plus conditional write, and NOTHING else.
14
+ *
15
+ * There is no get(), no list(), no query. Adding one turns this into the run journal,
16
+ * which is a different store with a different access pattern and a different
17
+ * portability story. Use Journal for that.
18
+ *
19
+ * Claim, act, complete. A claim is a short lease; a holder that dies before
20
+ * `complete` lets the key be claimed again once the lease ends, instead of
21
+ * holding it for the long TTL with the work never done.
22
+ */
23
+ export interface Ledger {
24
+ claim(key: string, leaseSeconds: number): Promise<ClaimResult>;
25
+ /** Marks the work done. The key stays claimed for `ttlSeconds` from now. */
26
+ complete(key: string, ttlSeconds: number): Promise<void>;
27
+ /**
28
+ * Frees the key now, instead of when the lease ends. Throws on a fault like
29
+ * every other method. A failed release needs no recovery: the key frees
30
+ * itself when the lease ends. A caller already handling an error should not
31
+ * let a release fault replace it.
32
+ */
33
+ release(key: string): Promise<void>;
34
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
1
+ import type { DeploymentIdentity } from './identity.js';
2
+ export type LogFields = Readonly<Record<string, string | number | boolean | null>>;
3
+ /** Structured only. A correlation id and the deployment identity are required, by type. */
4
+ export interface Logger {
5
+ readonly identity: DeploymentIdentity;
6
+ readonly correlationId: string;
7
+ info(message: string, fields?: LogFields): void;
8
+ warn(message: string, fields?: LogFields): void;
9
+ error(message: string, fields?: LogFields): void;
10
+ child(correlationId: string): Logger;
11
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,37 @@
1
+ /** Weakest to strongest. The array order IS the ranking. */
2
+ export declare const LOCK_GUARANTEES: readonly ["none", "advisory", "strict-partitioned", "strict"];
3
+ export type LockGuarantee = (typeof LOCK_GUARANTEES)[number];
4
+ /** What a target provides. Every adapter exports one. */
5
+ export type ToolManifest = {
6
+ readonly lock: LockGuarantee;
7
+ readonly lockFencing: boolean;
8
+ readonly queueDelayMaxSeconds: number;
9
+ readonly messageMaxBytes: number;
10
+ readonly blobMaxBytes: number;
11
+ readonly cacheMinTtlSeconds: number;
12
+ /**
13
+ * The largest step result a Jobs executor stores, in bytes of the result's
14
+ * JSON encoding as UTF-8. The executor checks it when a step returns, before
15
+ * the result is stored or handed to the platform, and rejects a larger one
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
18
+ * handler sees the cause `result-too-large`.
19
+ */
20
+ readonly stepResultMaxBytes: number;
21
+ readonly journalDialect: 'sqlite' | 'postgres';
22
+ readonly scheduleTimezone: 'native' | 'resolved-in-code';
23
+ /** The shortest interval `defineSchedule` accepts on this target, in seconds. */
24
+ readonly scheduleMinIntervalSeconds: number;
25
+ };
26
+ /** What a trigger, a topic or a job needs. Checked against the manifest before deploy. */
27
+ export type Requirements = Partial<{
28
+ readonly lock: LockGuarantee;
29
+ readonly lockFencing: true;
30
+ readonly queueDelayMaxSeconds: number;
31
+ }>;
32
+ export type Unmet = {
33
+ readonly requirement: keyof Requirements;
34
+ readonly required: string;
35
+ readonly provided: string;
36
+ };
37
+ export declare function satisfies(m: ToolManifest, r: Requirements): readonly Unmet[];
@@ -0,0 +1,30 @@
1
+ /** Weakest to strongest. The array order IS the ranking. */
2
+ export const LOCK_GUARANTEES = [
3
+ 'none',
4
+ 'advisory',
5
+ 'strict-partitioned',
6
+ 'strict',
7
+ ];
8
+ const lockRank = (g) => LOCK_GUARANTEES.indexOf(g);
9
+ export function satisfies(m, r) {
10
+ const unmet = [];
11
+ if (r.lock !== undefined && lockRank(m.lock) < lockRank(r.lock)) {
12
+ unmet.push({ requirement: 'lock', required: r.lock, provided: m.lock });
13
+ }
14
+ if (r.lockFencing === true && !m.lockFencing) {
15
+ unmet.push({
16
+ requirement: 'lockFencing',
17
+ required: 'true',
18
+ provided: 'false',
19
+ });
20
+ }
21
+ if (r.queueDelayMaxSeconds !== undefined &&
22
+ m.queueDelayMaxSeconds < r.queueDelayMaxSeconds) {
23
+ unmet.push({
24
+ requirement: 'queueDelayMaxSeconds',
25
+ required: String(r.queueDelayMaxSeconds),
26
+ provided: String(m.queueDelayMaxSeconds),
27
+ });
28
+ }
29
+ return unmet;
30
+ }