@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,564 @@
1
+ import { LimitExceeded, Misconfigured, fromEpochMs, } from '../contracts/index.js';
2
+ /**
3
+ * How long an ended instance is kept, so that `dispatch` with its id still
4
+ * says `already-started`. 30 days, the same as Workflows on Workers Paid
5
+ * (decision 0006 and its amendment). The contract has no field to change it.
6
+ */
7
+ export const RETENTION_MS = 30 * 24 * 3_600_000;
8
+ /**
9
+ * The exhaustion handler's lease. The contract gives the handler no timeout,
10
+ * so the executor chooses one: 15 minutes. A handler that runs longer can be
11
+ * started a second time beside itself, which its idempotency already covers.
12
+ */
13
+ export const HANDLER_LEASE_MS = 15 * 60_000;
14
+ /**
15
+ * The wait before a handler that threw runs again. The contract names none.
16
+ * The handler runs at least once and never gives up, because `failed` means
17
+ * the handler finished, so a fixed minute keeps a handler that always throws
18
+ * from spinning.
19
+ */
20
+ export const HANDLER_RETRY_MS = 60_000;
21
+ const NAME = /^[A-Za-z0-9_]{1,64}$/;
22
+ const KEY = /^[A-Za-z0-9_-]+$/;
23
+ const ID_MAX = 100;
24
+ /**
25
+ * Unpacks one registration. The generic callback is the only place the
26
+ * definition's own types are known, so each run closes over them there and
27
+ * builds the deps itself, in the invocation that runs the step.
28
+ */
29
+ function unpack(registration) {
30
+ return registration((definition, deps) => {
31
+ const typed = (base) => ({
32
+ ...base,
33
+ input: base.input,
34
+ results: base.results,
35
+ deps: deps(),
36
+ });
37
+ const handler = definition.onExhausted;
38
+ return {
39
+ name: definition.name,
40
+ key: (input) => definition.key(input),
41
+ steps: definition.steps.map((s) => ({
42
+ name: s.name,
43
+ retries: s.retries,
44
+ timeoutSeconds: s.timeoutSeconds,
45
+ run: async (base) => s.run(typed(base)),
46
+ })),
47
+ onExhausted: handler === undefined
48
+ ? undefined
49
+ : async (base, exhaustion) => handler({ ...typed(base), exhaustion }),
50
+ };
51
+ });
52
+ }
53
+ /** The delay before retry `n`, 1-based (`StepRetries`). */
54
+ function backoffMs(retries, n) {
55
+ const factor = retries.backoff === 'exponential' ? 2 ** (n - 1) : 1;
56
+ return retries.delaySeconds * factor * 1000;
57
+ }
58
+ /**
59
+ * Refuses, when the executor is built, a step the protocol cannot run (rule
60
+ * 7). A repeated name would shadow a result in `StepContext.results`. A
61
+ * delay that is not a finite number, or a backoff that overflows to
62
+ * `Infinity`, would set `next_wake_at` to a value no sweep ever reaches, and
63
+ * the instance would stay `running` for ever.
64
+ */
65
+ function checkSteps(job) {
66
+ const names = new Set();
67
+ for (const step of job.steps) {
68
+ const where = `Job ${job.name}, step ${JSON.stringify(step.name)}`;
69
+ if (names.has(step.name)) {
70
+ throw new Misconfigured('jobs', `${where}: the name is used twice`);
71
+ }
72
+ names.add(step.name);
73
+ const { limit, delaySeconds } = step.retries;
74
+ if (!Number.isInteger(limit) || limit < 0) {
75
+ throw new Misconfigured('jobs', `${where}: retries.limit must be an integer of 0 or more`);
76
+ }
77
+ if (!Number.isFinite(delaySeconds) || delaySeconds < 0) {
78
+ throw new Misconfigured('jobs', `${where}: retries.delaySeconds must be a finite number of 0 or more`);
79
+ }
80
+ if (limit > 0 && !Number.isFinite(backoffMs(step.retries, limit))) {
81
+ throw new Misconfigured('jobs', `${where}: the backoff before retry ${limit} is not a finite delay`);
82
+ }
83
+ if (!Number.isFinite(step.timeoutSeconds) || step.timeoutSeconds <= 0) {
84
+ throw new Misconfigured('jobs', `${where}: timeoutSeconds must be a finite number above 0`);
85
+ }
86
+ }
87
+ }
88
+ const bytes = (json) => new TextEncoder().encode(json).byteLength;
89
+ /**
90
+ * `Jobs` over a `ReferenceStore` and a queue of wake-ups, by the protocol of
91
+ * docs/decisions/0006. The adapter delivers the queue's batches to `consume`
92
+ * and calls `sweep` on a schedule.
93
+ */
94
+ export class ReferenceExecutor {
95
+ o;
96
+ #jobs = new Map();
97
+ constructor(o) {
98
+ this.o = o;
99
+ for (const registration of o.registrations) {
100
+ const job = unpack(registration);
101
+ // Refused when the executor is built, not at the first dispatch: a bad
102
+ // name is a defect in the definition (rule 7, `Job.name`).
103
+ if (!NAME.test(job.name)) {
104
+ throw new LimitExceeded('jobs', `Job name ${JSON.stringify(job.name)} must be 1 to 64 characters of [A-Za-z0-9_]`);
105
+ }
106
+ if (this.#jobs.has(job.name)) {
107
+ throw new Misconfigured('jobs', `Job name ${job.name} is registered twice`);
108
+ }
109
+ checkSteps(job);
110
+ this.#jobs.set(job.name, job);
111
+ }
112
+ }
113
+ async dispatch(definition, input, options) {
114
+ const job = this.#jobs.get(definition.name);
115
+ if (job === undefined) {
116
+ throw new Misconfigured('jobs', `Job ${definition.name} is not registered with this executor`);
117
+ }
118
+ const key = job.key(input);
119
+ const id = `${job.name}-${key}`;
120
+ if (!KEY.test(key) || id.length > ID_MAX) {
121
+ throw new LimitExceeded('jobs', `key ${JSON.stringify(key)} must be [A-Za-z0-9_-], at least one character, and fit an id of ${ID_MAX}`);
122
+ }
123
+ const now = this.o.clock.now();
124
+ const row = {
125
+ instanceId: id,
126
+ job: job.name,
127
+ input: JSON.stringify(input),
128
+ runId: options.runId,
129
+ unitKey: key,
130
+ status: 'running',
131
+ cause: null,
132
+ reasonCode: null,
133
+ currentStep: 0,
134
+ attempts: 0,
135
+ version: 0,
136
+ leaseExpiresAt: null,
137
+ nextWakeAt: now,
138
+ createdAt: now,
139
+ endedAt: null,
140
+ };
141
+ if ((await this.#insert(row)) === 'exists') {
142
+ return { status: 'already-started', id };
143
+ }
144
+ // A crash here leaves `next_wake_at` at now with no lease, so the sweeper
145
+ // sends the wake-up this would have.
146
+ await this.o.interrupt?.('after-dispatch-insert', {
147
+ instanceId: id,
148
+ stepIndex: 0,
149
+ });
150
+ await this.o.queue.send({ instanceId: id, stepIndex: 0 });
151
+ return { status: 'started', id };
152
+ }
153
+ async status(id) {
154
+ const row = await this.o.store.get(id);
155
+ if (row === undefined || this.#expired(row)) {
156
+ return { status: 'unknown' };
157
+ }
158
+ switch (row.status) {
159
+ case 'running':
160
+ case 'failing':
161
+ return { status: 'running' };
162
+ case 'completed':
163
+ return { status: 'completed' };
164
+ case 'failed':
165
+ return { status: 'failed' };
166
+ }
167
+ }
168
+ /**
169
+ * THE QUEUE CONSUMER. Each message is acknowledged or retried on its own.
170
+ * A message whose handling throws is neither, so the queue redelivers it:
171
+ * a store fault is the platform's, and the state tables are unchanged by a
172
+ * write that did not happen.
173
+ */
174
+ async consume(batch) {
175
+ for (const message of batch.messages) {
176
+ try {
177
+ const delaySeconds = await this.#handle(message);
178
+ if (delaySeconds === undefined) {
179
+ batch.ack(message.id);
180
+ }
181
+ else {
182
+ batch.retry(message.id, { delaySeconds });
183
+ }
184
+ }
185
+ catch (error) {
186
+ this.o.logger.error('jobs: wake-up failed, left for redelivery', {
187
+ instanceId: message.body.instanceId,
188
+ stepIndex: message.body.stepIndex,
189
+ error: String(error),
190
+ });
191
+ }
192
+ }
193
+ }
194
+ /**
195
+ * THE SWEEPER. Wakes every instance that is due and holds no live lease,
196
+ * and deletes ended instances whose retention has passed. A duplicate
197
+ * wake-up is harmless, so it coordinates with nothing.
198
+ */
199
+ async sweep() {
200
+ const now = this.o.clock.now();
201
+ for (const row of await this.o.store.due(now)) {
202
+ await this.o.queue.send({
203
+ instanceId: row.instanceId,
204
+ stepIndex: row.currentStep,
205
+ });
206
+ }
207
+ await this.o.store.removeEndedBefore(fromEpochMs(now - RETENTION_MS));
208
+ }
209
+ #expired(row) {
210
+ return (row.endedAt !== null && row.endedAt + RETENTION_MS <= this.o.clock.now());
211
+ }
212
+ /** The insert, after clearing a row whose retention has passed. */
213
+ async #insert(row) {
214
+ const first = await this.o.store.insert(row);
215
+ if (first === 'inserted') {
216
+ return first;
217
+ }
218
+ const existing = await this.o.store.get(row.instanceId);
219
+ if (existing === undefined || this.#expired(existing)) {
220
+ if (existing !== undefined) {
221
+ await this.o.store.remove(existing.instanceId, fromEpochMs(this.o.clock.now() - RETENTION_MS));
222
+ }
223
+ return this.o.store.insert(row);
224
+ }
225
+ return 'exists';
226
+ }
227
+ /** Undefined to acknowledge, or the delay to retry the message with. */
228
+ async #handle(message) {
229
+ const { instanceId, stepIndex } = message.body;
230
+ const row = await this.o.store.get(instanceId);
231
+ // Duplicate and reordered delivery are harmless.
232
+ if (row === undefined ||
233
+ (row.status !== 'running' && row.status !== 'failing') ||
234
+ row.currentStep !== stepIndex) {
235
+ return undefined;
236
+ }
237
+ const now = this.o.clock.now();
238
+ // An early message: a redelivery, or a retry sent before a longer backoff
239
+ // was stored. Past the queue's ceiling, the sweeper wakes it instead.
240
+ if (row.nextWakeAt !== null && row.nextWakeAt > now) {
241
+ const seconds = (row.nextWakeAt - now) / 1000;
242
+ return seconds <= this.o.manifest.queueDelayMaxSeconds
243
+ ? seconds
244
+ : undefined;
245
+ }
246
+ if (row.leaseExpiresAt !== null && row.leaseExpiresAt > now) {
247
+ return undefined;
248
+ }
249
+ const job = this.#jobs.get(row.job);
250
+ if (job === undefined) {
251
+ this.o.logger.error('jobs: no registration for an instance', {
252
+ instanceId,
253
+ job: row.job,
254
+ });
255
+ return undefined;
256
+ }
257
+ const step = job.steps[row.currentStep];
258
+ const leaseMs = row.status === 'failing' || step === undefined
259
+ ? HANDLER_LEASE_MS
260
+ : (step.timeoutSeconds + 60) * 1000;
261
+ const leased = {
262
+ ...row,
263
+ attempts: row.attempts + 1,
264
+ leaseExpiresAt: fromEpochMs(now + leaseMs),
265
+ version: row.version + 1,
266
+ };
267
+ if (!(await this.o.store.update(instanceId, row.version, {
268
+ attempts: leased.attempts,
269
+ leaseExpiresAt: leased.leaseExpiresAt,
270
+ }))) {
271
+ return undefined;
272
+ }
273
+ if (leased.status === 'failing') {
274
+ await this.#runHandler(job, leased);
275
+ }
276
+ else {
277
+ await this.#runStep(job, leased);
278
+ }
279
+ return undefined;
280
+ }
281
+ async #base(row, job) {
282
+ const stored = await this.o.store.results(row.instanceId);
283
+ const results = {};
284
+ for (const [index, json] of [...stored].sort(([a], [b]) => a - b)) {
285
+ const name = job.steps[index]?.name;
286
+ if (name !== undefined && index < row.currentStep) {
287
+ results[name] = JSON.parse(json);
288
+ }
289
+ }
290
+ return {
291
+ instanceId: row.instanceId,
292
+ runId: row.runId,
293
+ unitKey: row.unitKey,
294
+ input: JSON.parse(row.input),
295
+ results,
296
+ };
297
+ }
298
+ async #runStep(job, row) {
299
+ const index = row.currentStep;
300
+ const step = job.steps[index];
301
+ if (step === undefined) {
302
+ // A Job with no steps left completes. Only an empty Job gets here.
303
+ await this.#advance(job, row, undefined);
304
+ return;
305
+ }
306
+ // The step completed but the instance did not advance: a crash between
307
+ // the result write and the advance. Do not run it again.
308
+ const stored = (await this.o.store.results(row.instanceId)).get(index);
309
+ if (stored !== undefined) {
310
+ await this.#advance(job, row, undefined);
311
+ return;
312
+ }
313
+ const base = await this.#base(row, job);
314
+ const started = this.o.clock.now();
315
+ const attempt = await this.#attempt(step, base, started);
316
+ const durationMs = this.o.clock.now() - started;
317
+ const record = async (outcome, reasonCode) => this.#record(row, step.name, outcome, durationMs, reasonCode);
318
+ switch (attempt.kind) {
319
+ case 'done': {
320
+ const window = { instanceId: row.instanceId, stepIndex: index };
321
+ await this.o.interrupt?.('before-result-stored', window);
322
+ await this.o.store.storeResult(row.instanceId, index, attempt.result, this.o.clock.now());
323
+ await this.o.interrupt?.('after-result-stored', window);
324
+ await this.#advance(job, row, record);
325
+ return;
326
+ }
327
+ case 'fault': {
328
+ // `limit` counts retries: attempt n is retry n - 1.
329
+ if (row.attempts <= step.retries.limit) {
330
+ const delayMs = backoffMs(step.retries, row.attempts);
331
+ const won = await this.o.store.update(row.instanceId, row.version, {
332
+ leaseExpiresAt: null,
333
+ nextWakeAt: fromEpochMs(this.o.clock.now() + delayMs),
334
+ });
335
+ if (!won) {
336
+ await this.#superseded(row, step.name, record);
337
+ return;
338
+ }
339
+ await record('retry', attempt.reasonCode);
340
+ this.o.logger.warn('jobs: step faulted, retrying', {
341
+ instanceId: row.instanceId,
342
+ step: step.name,
343
+ attempt: row.attempts,
344
+ delayMs,
345
+ reasonCode: attempt.reasonCode,
346
+ });
347
+ // Past the queue's ceiling the sweeper wakes it at `next_wake_at`.
348
+ if (delayMs / 1000 <= this.o.manifest.queueDelayMaxSeconds) {
349
+ await this.o.queue.send({ instanceId: row.instanceId, stepIndex: index }, { delaySeconds: delayMs / 1000 });
350
+ }
351
+ return;
352
+ }
353
+ await this.#fail(row, step.name, record, {
354
+ step: step.name,
355
+ cause: 'retries-exhausted',
356
+ });
357
+ return;
358
+ }
359
+ case 'exhausted':
360
+ await this.#fail(row, step.name, record, attempt.exhaustion);
361
+ return;
362
+ }
363
+ }
364
+ /**
365
+ * Runs one attempt and says how it ended. A throw is a fault. An attempt
366
+ * that outlasted `timeoutSeconds` on the clock is a fault whatever it
367
+ * returned: the timeout fails the attempt, it does not stop the body.
368
+ */
369
+ async #attempt(step, base, started) {
370
+ let outcome;
371
+ try {
372
+ outcome = await step.run(base);
373
+ }
374
+ catch (error) {
375
+ outcome = { status: 'threw', error };
376
+ }
377
+ if (this.o.clock.now() - started > step.timeoutSeconds * 1000) {
378
+ return { kind: 'fault', reasonCode: 'timeout' };
379
+ }
380
+ if (outcome.status === 'threw') {
381
+ const { error } = outcome;
382
+ return {
383
+ kind: 'fault',
384
+ reasonCode: error instanceof Error ? error.name : 'fault',
385
+ };
386
+ }
387
+ if (outcome.status === 'terminal') {
388
+ return {
389
+ kind: 'exhausted',
390
+ exhaustion: {
391
+ step: step.name,
392
+ cause: 'terminal',
393
+ reasonCode: outcome.reasonCode,
394
+ },
395
+ };
396
+ }
397
+ const result = JSON.stringify(outcome.result);
398
+ const size = bytes(result);
399
+ if (size > this.o.manifest.stepResultMaxBytes) {
400
+ // Rule 7: the executor enforces the manifest. The same input gives the
401
+ // same result, so this is terminal, not a fault.
402
+ const error = new LimitExceeded('jobs', `step ${step.name} returned ${size} bytes, above stepResultMaxBytes ${this.o.manifest.stepResultMaxBytes}`);
403
+ this.o.logger.error(error.message, { instanceId: base.instanceId });
404
+ return {
405
+ kind: 'exhausted',
406
+ exhaustion: { step: step.name, cause: 'result-too-large' },
407
+ };
408
+ }
409
+ return { kind: 'done', result };
410
+ }
411
+ /**
412
+ * Write 2 of a success: advance, or complete on the last step. Then the
413
+ * next wake-up. `record` is set when this consumer ran the step.
414
+ */
415
+ async #advance(job, row, record) {
416
+ const index = row.currentStep;
417
+ const last = index + 1 >= job.steps.length;
418
+ const now = this.o.clock.now();
419
+ const won = await this.o.store.update(row.instanceId, row.version, last
420
+ ? {
421
+ status: 'completed',
422
+ endedAt: now,
423
+ nextWakeAt: null,
424
+ leaseExpiresAt: null,
425
+ }
426
+ : {
427
+ currentStep: index + 1,
428
+ attempts: 0,
429
+ leaseExpiresAt: null,
430
+ nextWakeAt: now,
431
+ });
432
+ if (!won) {
433
+ await this.#superseded(row, job.steps[index]?.name ?? '', record);
434
+ return;
435
+ }
436
+ await record?.('ok');
437
+ if (last) {
438
+ this.o.logger.info('jobs: instance completed', {
439
+ instanceId: row.instanceId,
440
+ });
441
+ return;
442
+ }
443
+ // A crash here leaves `next_wake_at` at now and no lease: the sweeper.
444
+ await this.o.interrupt?.('after-advance', {
445
+ instanceId: row.instanceId,
446
+ stepIndex: index,
447
+ });
448
+ await this.o.queue.send({
449
+ instanceId: row.instanceId,
450
+ stepIndex: index + 1,
451
+ });
452
+ }
453
+ async #fail(row, step, record, exhaustion) {
454
+ const won = await this.o.store.update(row.instanceId, row.version, {
455
+ status: 'failing',
456
+ cause: exhaustion.cause,
457
+ reasonCode: exhaustion.cause === 'terminal' ? exhaustion.reasonCode : null,
458
+ attempts: 0,
459
+ leaseExpiresAt: null,
460
+ nextWakeAt: this.o.clock.now(),
461
+ });
462
+ if (!won) {
463
+ await this.#superseded(row, step, record);
464
+ return;
465
+ }
466
+ const reasonCode = exhaustion.cause === 'terminal' ? exhaustion.reasonCode : exhaustion.cause;
467
+ await record('failed', reasonCode);
468
+ this.o.logger.error('jobs: step failed, running the exhaustion handler', {
469
+ instanceId: row.instanceId,
470
+ step,
471
+ cause: exhaustion.cause,
472
+ reasonCode,
473
+ });
474
+ await this.o.interrupt?.('after-failing-stored', {
475
+ instanceId: row.instanceId,
476
+ stepIndex: row.currentStep,
477
+ });
478
+ await this.o.queue.send({
479
+ instanceId: row.instanceId,
480
+ stepIndex: row.currentStep,
481
+ });
482
+ }
483
+ /**
484
+ * On a `failing` instance: run the handler, then mark the instance
485
+ * `failed`. A crash before that write runs the handler again, so it runs
486
+ * at least once and never after `failed`.
487
+ */
488
+ async #runHandler(job, row) {
489
+ const step = job.steps[row.currentStep]?.name ?? '';
490
+ const exhaustion = row.cause === 'terminal'
491
+ ? { step, cause: 'terminal', reasonCode: row.reasonCode ?? '' }
492
+ : { step, cause: row.cause ?? 'retries-exhausted' };
493
+ if (job.onExhausted !== undefined) {
494
+ try {
495
+ await job.onExhausted(await this.#base(row, job), exhaustion);
496
+ }
497
+ catch (error) {
498
+ const won = await this.o.store.update(row.instanceId, row.version, {
499
+ leaseExpiresAt: null,
500
+ nextWakeAt: fromEpochMs(this.o.clock.now() + HANDLER_RETRY_MS),
501
+ });
502
+ this.o.logger.error('jobs: exhaustion handler threw, running it again', {
503
+ instanceId: row.instanceId,
504
+ attempt: row.attempts,
505
+ error: String(error),
506
+ });
507
+ if (won) {
508
+ await this.o.queue.send({ instanceId: row.instanceId, stepIndex: row.currentStep }, { delaySeconds: HANDLER_RETRY_MS / 1000 });
509
+ }
510
+ return;
511
+ }
512
+ }
513
+ const won = await this.o.store.update(row.instanceId, row.version, {
514
+ status: 'failed',
515
+ endedAt: this.o.clock.now(),
516
+ nextWakeAt: null,
517
+ leaseExpiresAt: null,
518
+ });
519
+ if (won) {
520
+ this.o.logger.info('jobs: instance failed', {
521
+ instanceId: row.instanceId,
522
+ });
523
+ }
524
+ }
525
+ /**
526
+ * Another consumer committed first. Discard, acknowledge, record it, and
527
+ * do not throw, so the queue does not retry it (decision 0006).
528
+ */
529
+ async #superseded(row, step, record) {
530
+ await record?.('superseded', 'superseded');
531
+ this.o.logger.info('jobs: superseded by another consumer', {
532
+ instanceId: row.instanceId,
533
+ step,
534
+ });
535
+ }
536
+ /**
537
+ * The Step row (decision 0006, #77). A record, not state: it is written
538
+ * after the state, nothing reads it, and a failed write is logged and does
539
+ * not fail the step.
540
+ */
541
+ async #record(row, step, outcome, durationMs, reasonCode) {
542
+ // `recordStep` never rejects, by contract. The catch is for a journal
543
+ // that breaks it: a step that did its work is not failed to record it.
544
+ try {
545
+ await this.o.journal.recordStep({
546
+ runId: row.runId,
547
+ unitKey: row.unitKey,
548
+ step,
549
+ attempt: row.attempts,
550
+ outcome,
551
+ ...(reasonCode === undefined ? {} : { reasonCode }),
552
+ durationMs,
553
+ recordedAt: this.o.clock.now(),
554
+ });
555
+ }
556
+ catch (error) {
557
+ this.o.logger.warn('jobs: step row not written', {
558
+ instanceId: row.instanceId,
559
+ step,
560
+ error: String(error),
561
+ });
562
+ }
563
+ }
564
+ }
@@ -0,0 +1,18 @@
1
+ import type { Clock, Instant } from '../contracts/index.js';
2
+ /** Decision 0010: 30 days, which a client project may shorten. */
3
+ export declare const DEFAULT_RETENTION_SECONDS: number;
4
+ /**
5
+ * What one sweep call may be told. Each call deletes one bounded batch and
6
+ * returns how many it deleted; the caller runs it again while that equals
7
+ * `limit`.
8
+ */
9
+ export type SweepOptions = {
10
+ /** Default `DEFAULT_RETENTION_SECONDS`. */
11
+ readonly olderThanSeconds?: number;
12
+ readonly limit?: number;
13
+ };
14
+ /** The cutoff and the batch size, checked: a NaN cutoff would sweep nothing or everything. */
15
+ export declare function sweepBounds(tool: string, clock: Clock, options: SweepOptions, defaultLimit: number): {
16
+ cutoff: Instant;
17
+ limit: number;
18
+ };
@@ -0,0 +1,13 @@
1
+ import { checkDuration, plusSeconds } from '../contracts/index.js';
2
+ /** Decision 0010: 30 days, which a client project may shorten. */
3
+ export const DEFAULT_RETENTION_SECONDS = 30 * 24 * 60 * 60;
4
+ /** The cutoff and the batch size, checked: a NaN cutoff would sweep nothing or everything. */
5
+ export function sweepBounds(tool, clock, options, defaultLimit) {
6
+ const olderThanSeconds = options.olderThanSeconds ?? DEFAULT_RETENTION_SECONDS;
7
+ const limit = options.limit ?? defaultLimit;
8
+ checkDuration(tool, 'olderThanSeconds', olderThanSeconds);
9
+ if (!Number.isInteger(limit) || limit < 1) {
10
+ throw new TypeError(`${tool}: limit must be a positive integer, not ${String(limit)}`);
11
+ }
12
+ return { cutoff: plusSeconds(clock.now(), -olderThanSeconds), limit };
13
+ }
@@ -0,0 +1,35 @@
1
+ import { type S3Client } from '@aws-sdk/client-s3';
2
+ import type { BlobKey, BlobStore, PutOptions } from '../../contracts/index.js';
3
+ /**
4
+ * The largest single PUT S3 accepts. The adapter does no multipart upload, so
5
+ * this is the most it can honestly promise. docs/platform-facts.md, S3.
6
+ */
7
+ export declare const S3_MAX_PUT_BYTES = 5368709120;
8
+ export type S3BlobStoreOptions = {
9
+ /**
10
+ * The app builds the client, with its own endpoint, region, credentials and
11
+ * `forcePathStyle`, so nothing here is specific to AWS. MinIO, R2, GCS and
12
+ * the rest differ only in that configuration.
13
+ */
14
+ readonly client: S3Client;
15
+ readonly bucket: string;
16
+ readonly maxBytes: number;
17
+ };
18
+ /**
19
+ * BlobStore over any S3-compatible bucket.
20
+ *
21
+ * S3 gives away what the contract asks for: a prefix is a string prefix, and
22
+ * deleting a missing key succeeds. Only `list` needs work, because a page
23
+ * holds at most 1,000 keys.
24
+ */
25
+ export declare class S3BlobStore implements BlobStore {
26
+ #private;
27
+ private readonly o;
28
+ constructor(o: S3BlobStoreOptions);
29
+ put(key: BlobKey, body: Uint8Array | string, options?: PutOptions): Promise<void>;
30
+ get(key: BlobKey): Promise<Uint8Array | undefined>;
31
+ getText(key: BlobKey): Promise<string | undefined>;
32
+ delete(key: BlobKey): Promise<void>;
33
+ /** Pages to completion. One unpaged call would return 1,000 keys and no error. */
34
+ list(prefix: string): Promise<readonly BlobKey[]>;
35
+ }