@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,305 @@
1
+ import { TASK_TRANSITIONS, } from '../../contracts/index.js';
2
+ import { DEFAULT_RUN_LIMIT, DEFAULT_UNIT_LIMIT, FIRST_TASK, toCallRow, toDeliveryRow, toTaskRow, toRunRow, toStepRow, toUnitRow, } from '../journal-records.js';
3
+ import { toFault } from './faults.js';
4
+ const TOOL = 'journal';
5
+ /** Always four: no state has more predecessors than that in TASK_TRANSITIONS. */
6
+ const fromStates = (to) => {
7
+ const from = TASK_TRANSITIONS[to];
8
+ if (from.length > 4) {
9
+ throw new TypeError(`journal: moveTask binds four states, ${to} has ${from.length}`);
10
+ }
11
+ return [0, 1, 2, 3].map((i) => from[i] ?? from[0]);
12
+ };
13
+ /**
14
+ * Every query this adapter can run, in one place.
15
+ *
16
+ * Named queries only. No method takes SQL, nothing here is assembled from a
17
+ * caller's value, and every parameter is bound. A new operator screen means a
18
+ * new entry in this object, which is a moment of review rather than an ad-hoc
19
+ * SELECT in a route.
20
+ *
21
+ * Which index serves which query — asserted by `journal.spec.ts` with EXPLAIN
22
+ * QUERY PLAN, so it stays true rather than staying written down:
23
+ *
24
+ * recentRuns journal_runs_started_at
25
+ * unitsForRun journal_units primary key (run_id, unit_key)
26
+ * unit journal_units primary key, journal_steps_unit,
27
+ * journal_calls primary key
28
+ * latestForUnit journal_units_unit_key
29
+ * failuresByReason journal_units_recorded_at
30
+ * delivery webhook_deliveries and webhook_tasks primary keys
31
+ * deadTasks webhook_tasks_state
32
+ * deadTasksByAction webhook_tasks_action_state
33
+ * stuckTasks webhook_tasks_state
34
+ */
35
+ const Q = {
36
+ startRun: `
37
+ INSERT INTO journal_runs
38
+ (run_id, job, trigger, mode, started_at, identity)
39
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)
40
+ ON CONFLICT(run_id) DO UPDATE SET
41
+ job = ?2, trigger = ?3, mode = ?4, started_at = ?5, identity = ?6
42
+ `,
43
+ // Affects no rows when the run was never started, which is not an error.
44
+ finishRun: `UPDATE journal_runs SET ended_at = ?2 WHERE run_id = ?1`,
45
+ recordUnit: `
46
+ INSERT INTO journal_units
47
+ (run_id, unit_key, unit_type, recorded_at, outcome,
48
+ reason_code, plan_hash, plan_ref, duration_ms, external_ids)
49
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
50
+ ON CONFLICT(run_id, unit_key) DO UPDATE SET
51
+ unit_type = ?3, recorded_at = ?4, outcome = ?5,
52
+ reason_code = ?6, plan_hash = ?7, plan_ref = ?8,
53
+ duration_ms = ?9, external_ids = ?10
54
+ `,
55
+ // Re-recording a unit is a correction, so its old calls go with the old row.
56
+ // Without this a corrected unit keeps whichever calls the first attempt wrote
57
+ // beyond the second attempt's count.
58
+ clearCalls: `DELETE FROM journal_calls WHERE run_id = ?1 AND unit_key = ?2`,
59
+ recordCall: `
60
+ INSERT INTO journal_calls
61
+ (run_id, unit_key, seq, system, operation,
62
+ status, http_status, idempotency_key, duration_ms)
63
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
64
+ `,
65
+ // Append-only. A step row is never a correction; see the migration.
66
+ recordStep: `
67
+ INSERT INTO journal_steps
68
+ (run_id, unit_key, step, attempt, outcome,
69
+ reason_code, duration_ms, recorded_at)
70
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
71
+ `,
72
+ unitsForRun: `
73
+ SELECT * FROM journal_units
74
+ WHERE run_id = ?1 ORDER BY unit_key LIMIT ?2
75
+ `,
76
+ unit: `SELECT * FROM journal_units WHERE run_id = ?1 AND unit_key = ?2`,
77
+ stepsForUnit: `
78
+ SELECT * FROM journal_steps
79
+ WHERE run_id = ?1 AND unit_key = ?2 ORDER BY recorded_at, seq
80
+ `,
81
+ callsForUnit: `
82
+ SELECT * FROM journal_calls
83
+ WHERE run_id = ?1 AND unit_key = ?2 ORDER BY seq
84
+ `,
85
+ latestForUnit: `
86
+ SELECT * FROM journal_units
87
+ WHERE unit_key = ?1 ORDER BY recorded_at DESC LIMIT 1
88
+ `,
89
+ // 'written' is the plain success and is never a failure, whatever else is on
90
+ // the row. A unit with no reasonCode cannot be grouped by one.
91
+ failuresByReason: `
92
+ SELECT reason_code AS reasonCode, COUNT(*) AS count
93
+ FROM journal_units
94
+ WHERE recorded_at >= ?1
95
+ AND reason_code IS NOT NULL
96
+ AND outcome != 'written'
97
+ GROUP BY reason_code
98
+ ORDER BY count DESC, reason_code ASC
99
+ `,
100
+ recentRuns: `SELECT * FROM journal_runs ORDER BY started_at DESC LIMIT ?1`,
101
+ // A retried delivery records again; neither statement touches a row already there.
102
+ recordDelivery: `
103
+ INSERT INTO webhook_deliveries
104
+ (delivery_id, source, topic, shop, webhook_id, body_key, received_at)
105
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
106
+ ON CONFLICT(delivery_id) DO NOTHING
107
+ `,
108
+ recordTask: `
109
+ INSERT INTO webhook_tasks (delivery_id, action, state, updated_at)
110
+ VALUES (?1, ?2, 'received', ?3)
111
+ ON CONFLICT(delivery_id, action) DO NOTHING
112
+ `,
113
+ // ?5 to ?8 are the states TASK_TRANSITIONS allows the move from, the
114
+ // list padded by repeating its first, so the statement never changes.
115
+ moveTask: `
116
+ UPDATE webhook_tasks SET state = ?3, updated_at = ?4, reason_code = ?9
117
+ WHERE delivery_id = ?1 AND action = ?2 AND state IN (?5, ?6, ?7, ?8)
118
+ `,
119
+ delivery: `SELECT * FROM webhook_deliveries WHERE delivery_id = ?1`,
120
+ tasksForDelivery: `
121
+ SELECT * FROM webhook_tasks WHERE delivery_id = ?1 ORDER BY action
122
+ `,
123
+ deadTasks: `
124
+ SELECT * FROM webhook_tasks
125
+ WHERE state = 'dead' AND (updated_at, delivery_id, action) > (?1, ?2, ?3)
126
+ ORDER BY updated_at, delivery_id, action LIMIT ?4
127
+ `,
128
+ deadTasksByAction: `
129
+ SELECT * FROM webhook_tasks
130
+ WHERE action = ?5 AND state = 'dead'
131
+ AND (updated_at, delivery_id, action) > (?1, ?2, ?3)
132
+ ORDER BY updated_at, delivery_id LIMIT ?4
133
+ `,
134
+ stuckTasks: `
135
+ SELECT * FROM webhook_tasks
136
+ WHERE state IN ('received', 'processing') AND updated_at < ?1
137
+ ORDER BY updated_at, delivery_id, action LIMIT ?2
138
+ `,
139
+ };
140
+ export class CloudflareJournal {
141
+ o;
142
+ constructor(o) {
143
+ this.o = o;
144
+ }
145
+ async startRun(row) {
146
+ await this.#call('startRun', async () => this.o.db
147
+ .prepare(Q.startRun)
148
+ .bind(row.runId, row.job, row.trigger, row.mode, row.startedAt, JSON.stringify(row.identity))
149
+ .run());
150
+ }
151
+ async finishRun(runId, endedAt) {
152
+ await this.#call('finishRun', async () => this.o.db.prepare(Q.finishRun).bind(runId, endedAt).run());
153
+ }
154
+ /**
155
+ * One write, not one per step.
156
+ *
157
+ * `D1.batch` sends the unit and every one of its calls in a single round trip
158
+ * and runs them in one implicit transaction, so a unit is never half
159
+ * recorded. A loop of awaits would be N round trips and N chances to leave a
160
+ * unit with some of its calls.
161
+ *
162
+ * One statement per call rather than one multi-row INSERT: D1 binds at most
163
+ * 100 parameters per query, and nine columns means a batch of twelve calls
164
+ * would already be over the limit.
165
+ */
166
+ async recordUnit(unit, calls) {
167
+ const statements = [
168
+ this.o.db
169
+ .prepare(Q.recordUnit)
170
+ .bind(unit.runId, unit.unitKey, unit.unitType, unit.recordedAt, unit.outcome, unit.reasonCode ?? null, unit.planHash ?? null, unit.planRef ?? null, unit.durationMs, unit.externalIds === undefined
171
+ ? null
172
+ : JSON.stringify(unit.externalIds)),
173
+ this.o.db.prepare(Q.clearCalls).bind(unit.runId, unit.unitKey),
174
+ ...calls.map((c, seq) => this.o.db
175
+ .prepare(Q.recordCall)
176
+ .bind(c.runId, c.unitKey, seq, c.system, c.operation, c.status, c.httpStatus ?? null, c.idempotencyKey ?? null, c.durationMs ?? null)),
177
+ ];
178
+ await this.#call('recordUnit', async () => this.o.db.batch(statements));
179
+ }
180
+ /**
181
+ * One statement, not batched with the unit: it is written after each
182
+ * attempt, while the unit row is written once at the end.
183
+ *
184
+ * Catches every failure and logs it, as the contract requires. The fault is
185
+ * mapped first, so the log line names the same tool, operation and fault
186
+ * kind a rejection would have, and the vendor message stays in `cause`.
187
+ */
188
+ async recordStep(step) {
189
+ try {
190
+ await this.#call('recordStep', async () => this.o.db
191
+ .prepare(Q.recordStep)
192
+ .bind(step.runId, step.unitKey, step.step, step.attempt, step.outcome, step.reasonCode ?? null, step.durationMs, step.recordedAt)
193
+ .run());
194
+ }
195
+ catch (e) {
196
+ this.o.logger.error('journal step row not recorded', {
197
+ tool: TOOL,
198
+ operation: 'recordStep',
199
+ fault: e instanceof Error ? e.name : 'unknown',
200
+ runId: step.runId,
201
+ unitKey: step.unitKey,
202
+ step: step.step,
203
+ attempt: step.attempt,
204
+ outcome: step.outcome,
205
+ });
206
+ }
207
+ }
208
+ async unitsForRun(runId, limit = DEFAULT_UNIT_LIMIT) {
209
+ const { results } = await this.#call('unitsForRun', async () => this.o.db.prepare(Q.unitsForRun).bind(runId, limit).all());
210
+ return results.map(toUnitRow);
211
+ }
212
+ async unit(runId, unitKey) {
213
+ const record = await this.#call('unit', async () => this.o.db.prepare(Q.unit).bind(runId, unitKey).first());
214
+ if (record === null) {
215
+ return undefined;
216
+ }
217
+ const [steps, calls] = await this.#call('unit', async () => Promise.all([
218
+ this.o.db
219
+ .prepare(Q.stepsForUnit)
220
+ .bind(runId, unitKey)
221
+ .all(),
222
+ this.o.db
223
+ .prepare(Q.callsForUnit)
224
+ .bind(runId, unitKey)
225
+ .all(),
226
+ ]));
227
+ return {
228
+ unit: toUnitRow(record),
229
+ steps: steps.results.map(toStepRow),
230
+ calls: calls.results.map(toCallRow),
231
+ };
232
+ }
233
+ async latestForUnit(unitKey) {
234
+ const record = await this.#call('latestForUnit', async () => this.o.db.prepare(Q.latestForUnit).bind(unitKey).first());
235
+ return record === null ? undefined : toUnitRow(record);
236
+ }
237
+ async failuresByReason(since) {
238
+ const { results } = await this.#call('failuresByReason', async () => this.o.db
239
+ .prepare(Q.failuresByReason)
240
+ .bind(since)
241
+ .all());
242
+ return results.map((r) => ({ reasonCode: r.reasonCode, count: r.count }));
243
+ }
244
+ async recentRuns(limit = DEFAULT_RUN_LIMIT) {
245
+ const { results } = await this.#call('recentRuns', async () => this.o.db.prepare(Q.recentRuns).bind(limit).all());
246
+ return results.map(toRunRow);
247
+ }
248
+ /** One `D1.batch`, so the delivery and its tasks land together or not at all. */
249
+ async recordDelivery(delivery, actions) {
250
+ await this.#call('recordDelivery', async () => this.o.db.batch([
251
+ this.o.db
252
+ .prepare(Q.recordDelivery)
253
+ .bind(delivery.deliveryId, delivery.source, delivery.topic, delivery.shop, delivery.webhookId, delivery.bodyKey, delivery.receivedAt),
254
+ ...actions.map((action) => this.o.db
255
+ .prepare(Q.recordTask)
256
+ .bind(delivery.deliveryId, action, delivery.receivedAt)),
257
+ ]));
258
+ }
259
+ async moveTask(deliveryId, action, to, at, reasonCode) {
260
+ const { meta } = await this.#call('moveTask', async () => this.o.db
261
+ .prepare(Q.moveTask)
262
+ .bind(deliveryId, action, to, at, ...fromStates(to), reasonCode ?? null)
263
+ .run());
264
+ return meta.changes === 1;
265
+ }
266
+ async delivery(deliveryId) {
267
+ const [delivery, tasks] = await this.#call('delivery', async () => this.o.db.batch([
268
+ this.o.db.prepare(Q.delivery).bind(deliveryId),
269
+ this.o.db.prepare(Q.tasksForDelivery).bind(deliveryId),
270
+ ]));
271
+ const record = delivery.results[0];
272
+ return record === undefined
273
+ ? undefined
274
+ : {
275
+ delivery: toDeliveryRow(record),
276
+ tasks: tasks.results.map(toTaskRow),
277
+ };
278
+ }
279
+ async deadTasks({ action, after = FIRST_TASK, limit = DEFAULT_UNIT_LIMIT, } = {}) {
280
+ const cursor = [after.updatedAt, after.deliveryId, after.action, limit];
281
+ const { results } = await this.#call('deadTasks', async () => action === undefined
282
+ ? this.o.db
283
+ .prepare(Q.deadTasks)
284
+ .bind(...cursor)
285
+ .all()
286
+ : this.o.db
287
+ .prepare(Q.deadTasksByAction)
288
+ .bind(...cursor, action)
289
+ .all());
290
+ return results.map(toTaskRow);
291
+ }
292
+ async stuckTasks(before, limit = DEFAULT_UNIT_LIMIT) {
293
+ const { results } = await this.#call('stuckTasks', async () => this.o.db.prepare(Q.stuckTasks).bind(before, limit).all());
294
+ return results.map(toTaskRow);
295
+ }
296
+ async #call(operation, f) {
297
+ try {
298
+ return await f();
299
+ }
300
+ catch (e) {
301
+ throw toFault(TOOL, operation, e);
302
+ }
303
+ }
304
+ }
305
+ export { Q as JOURNAL_QUERIES };
@@ -0,0 +1,14 @@
1
+ import type { ClaimResult, Clock, Ledger } from '../../contracts/index.js';
2
+ export type CloudflareLedgerOptions = {
3
+ readonly db: D1Database;
4
+ readonly clock: Clock;
5
+ };
6
+ export declare class CloudflareLedger implements Ledger {
7
+ #private;
8
+ private readonly o;
9
+ constructor(o: CloudflareLedgerOptions);
10
+ claim(key: string, leaseSeconds: number): Promise<ClaimResult>;
11
+ complete(key: string, ttlSeconds: number): Promise<void>;
12
+ /** Releasing a key that was never claimed deletes nothing and is not an error. */
13
+ release(key: string): Promise<void>;
14
+ }
@@ -0,0 +1,108 @@
1
+ import { Unavailable, fromEpochMs, toIso } from '../../contracts/index.js';
2
+ import { toFault } from './faults.js';
3
+ const TOOL = 'ledger';
4
+ /**
5
+ * One conditional write. The `ON CONFLICT` clause is what makes it conditional:
6
+ * an existing row is overwritten ONLY when its lease has already ended, and
7
+ * SQLite evaluates that against the row it is holding, under the write lock.
8
+ *
9
+ * A `SELECT` followed by an `INSERT` would pass the conformance suite — twenty
10
+ * claims on one key is twenty turns of a single event loop — and would lose a
11
+ * race between two isolates. The suite cannot tell the difference. The schema
12
+ * can: `key` is the PRIMARY KEY, so two concurrent inserts cannot both land.
13
+ *
14
+ * `RETURNING` reports the outcome without a second question. A row comes back
15
+ * when the insert happened or the update was allowed; nothing comes back when
16
+ * the `WHERE` refused, which means the key is in progress or completed.
17
+ *
18
+ * `?2` is the caller's `now`, read from the injected Clock. There is no
19
+ * `CURRENT_TIMESTAMP` here on purpose — the suite advances a test clock by 11
20
+ * seconds and expects a reclaim, and a schema-side clock cannot be advanced.
21
+ */
22
+ const CLAIM = `
23
+ INSERT INTO ledger_claims (key, claimed_at, expires_at)
24
+ VALUES (?1, ?2, ?3)
25
+ ON CONFLICT(key) DO UPDATE SET claimed_at = ?2, expires_at = ?3, completed_at = NULL
26
+ WHERE ledger_claims.expires_at <= ?2
27
+ RETURNING claimed_at
28
+ `;
29
+ /** Only ever asked after the write above has already decided we lost. */
30
+ const HOLDER = `SELECT claimed_at, completed_at FROM ledger_claims WHERE key = ?1`;
31
+ /**
32
+ * An upsert, not an update: there is no token to check the holder against, and
33
+ * a row that was released or swept still had its work done.
34
+ */
35
+ const COMPLETE = `
36
+ INSERT INTO ledger_claims (key, claimed_at, expires_at, completed_at)
37
+ VALUES (?1, ?2, ?3, ?2)
38
+ ON CONFLICT(key) DO UPDATE SET completed_at = ?2, expires_at = ?3
39
+ `;
40
+ const RELEASE = `DELETE FROM ledger_claims WHERE key = ?1`;
41
+ /**
42
+ * Losing the write and then finding no holder means the holder released between
43
+ * the two statements — the key is free, and the honest answer is to try again
44
+ * rather than invent a `claimedAt` for a row that is gone. Three consecutive
45
+ * times is not contention, it is something wrong.
46
+ */
47
+ const ATTEMPTS = 3;
48
+ export class CloudflareLedger {
49
+ o;
50
+ constructor(o) {
51
+ this.o = o;
52
+ }
53
+ async claim(key, leaseSeconds) {
54
+ for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
55
+ const now = this.o.clock.now();
56
+ const expiresAt = now + leaseSeconds * 1000;
57
+ const won = await this.#call('claim', async () => this.o.db
58
+ .prepare(CLAIM)
59
+ .bind(key, now, expiresAt)
60
+ .first());
61
+ if (won !== null) {
62
+ return { status: 'claimed' };
63
+ }
64
+ // The decision is already made. This read reports who holds the key, and
65
+ // cannot change the outcome — which is why it is not a read-then-write.
66
+ const holder = await this.#call('claim', async () => this.o.db
67
+ .prepare(HOLDER)
68
+ .bind(key)
69
+ .first());
70
+ if (holder !== null) {
71
+ return holder.completed_at === null
72
+ ? {
73
+ status: 'in-progress',
74
+ claimedAt: toIso(fromEpochMs(holder.claimed_at)),
75
+ }
76
+ : {
77
+ status: 'completed',
78
+ completedAt: toIso(fromEpochMs(holder.completed_at)),
79
+ };
80
+ }
81
+ }
82
+ throw new Unavailable(TOOL, `claim on '${key}' found neither a winner nor a holder in ${ATTEMPTS} attempts`);
83
+ }
84
+ async complete(key, ttlSeconds) {
85
+ const now = this.o.clock.now();
86
+ await this.#call('complete', async () => this.o.db
87
+ .prepare(COMPLETE)
88
+ .bind(key, now, now + ttlSeconds * 1000)
89
+ .run());
90
+ }
91
+ /** Releasing a key that was never claimed deletes nothing and is not an error. */
92
+ async release(key) {
93
+ await this.#call('release', async () => this.o.db.prepare(RELEASE).bind(key).run());
94
+ }
95
+ async #call(operation, f) {
96
+ try {
97
+ return await f();
98
+ }
99
+ catch (e) {
100
+ // A unique-constraint violation is deliberately absent from this mapping.
101
+ // `ON CONFLICT` HANDLES the collision rather than raising it, so losing a
102
+ // race arrives as an empty RETURNING — an outcome — and never as an
103
+ // error. If one ever reaches here it is a genuine fault and should look
104
+ // like one.
105
+ throw toFault(TOOL, operation, e);
106
+ }
107
+ }
108
+ }
@@ -0,0 +1,22 @@
1
+ import type { DeploymentIdentity, LogFields, Logger } from '../../contracts/index.js';
2
+ /**
3
+ * A Worker has no log sink but `console`, and Cloudflare's log stream
4
+ * separates `console.error` and `console.warn` from everything else, which is
5
+ * why an operator filtering on severity needs the level routed there rather
6
+ * than carried only inside the JSON.
7
+ *
8
+ * One JSON object per line: a log line is read by a machine during an
9
+ * incident before it is read by a person. `identity` and `correlationId` are
10
+ * written last, after `fields`, so a field a caller passes can never shadow
11
+ * the one thing every line must carry.
12
+ */
13
+ export declare class CloudflareLogger implements Logger {
14
+ #private;
15
+ readonly identity: DeploymentIdentity;
16
+ readonly correlationId: string;
17
+ constructor(identity: DeploymentIdentity, correlationId: string);
18
+ info(message: string, fields?: LogFields): void;
19
+ warn(message: string, fields?: LogFields): void;
20
+ error(message: string, fields?: LogFields): void;
21
+ child(correlationId: string): Logger;
22
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * A Worker has no log sink but `console`, and Cloudflare's log stream
3
+ * separates `console.error` and `console.warn` from everything else, which is
4
+ * why an operator filtering on severity needs the level routed there rather
5
+ * than carried only inside the JSON.
6
+ *
7
+ * One JSON object per line: a log line is read by a machine during an
8
+ * incident before it is read by a person. `identity` and `correlationId` are
9
+ * written last, after `fields`, so a field a caller passes can never shadow
10
+ * the one thing every line must carry.
11
+ */
12
+ export class CloudflareLogger {
13
+ identity;
14
+ correlationId;
15
+ constructor(identity, correlationId) {
16
+ this.identity = identity;
17
+ this.correlationId = correlationId;
18
+ }
19
+ info(message, fields = {}) {
20
+ this.#write('info', message, fields);
21
+ }
22
+ warn(message, fields = {}) {
23
+ this.#write('warn', message, fields);
24
+ }
25
+ error(message, fields = {}) {
26
+ this.#write('error', message, fields);
27
+ }
28
+ child(correlationId) {
29
+ return new CloudflareLogger(this.identity, correlationId);
30
+ }
31
+ #write(level, message, fields) {
32
+ const line = JSON.stringify({
33
+ ...fields,
34
+ level,
35
+ message,
36
+ identity: this.identity,
37
+ correlationId: this.correlationId,
38
+ });
39
+ if (level === 'error') {
40
+ console.error(line);
41
+ }
42
+ else if (level === 'warn') {
43
+ console.warn(line);
44
+ }
45
+ else {
46
+ console.log(line);
47
+ }
48
+ }
49
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * WHAT CLOUDFLARE ACTUALLY PROVIDES.
3
+ *
4
+ * Every value here has a row in `docs/platform-facts.md` carrying its source
5
+ * and the date it was checked, and that file opens with a table mapping each of
6
+ * these ten fields to its row. A number that cannot be traced to a row does
7
+ * not belong here, even when it is right.
8
+ *
9
+ * A MANIFEST THAT LIES IS WORSE THAN NO MANIFEST. With no manifest a
10
+ * requirement is checked by a person; with a manifest that overstates the
11
+ * target, `satisfies()` certifies a guarantee nothing implements and the check
12
+ * that exists to stop an incident becomes the thing that causes one.
13
+ *
14
+ * Eight of the ten came from a vendor limits page or a measurement. Two —
15
+ * `lock` and `lockFencing` — could not, and the comments on them say what their
16
+ * claim is true of.
17
+ */
18
+ export declare const CLOUDFLARE_MANIFEST: {
19
+ /**
20
+ * `advisory`, not `strict`, and the distinction is the one `docs/design.md`
21
+ * §6.1 draws: "a strict lock and a lease with a TTL are not the same thing,
22
+ * and a design correct under the first is a race under the second".
23
+ *
24
+ * TRUE OF: acquisition. D1 decides a claim exactly once, with a primary key,
25
+ * under the write lock. NOT true of the lease's lifetime — a holder that
26
+ * stalls past its TTL is still working while a second claim succeeds, and
27
+ * nothing stops the first one's write landing.
28
+ *
29
+ * §8.2 says Cloudflare's strict lock is `KeyedLock` over a Durable Object.
30
+ * That interface does not exist yet; when it does, this becomes a manifest
31
+ * change with its own issue. docs/decisions/0002.
32
+ */
33
+ readonly lock: "advisory";
34
+ /**
35
+ * `false`, and not because of anything Cloudflare does. `Ledger.claim`
36
+ * returns `{ status: 'claimed' }` and no token, so NO adapter can honestly
37
+ * declare fencing — `LOCAL_MANIFEST` declares `true` and is wrong by the same
38
+ * argument, which is recorded there rather than copied here.
39
+ *
40
+ * Declaring `true` to match it would put a lie in the one file the whole
41
+ * pre-deploy check depends on. docs/decisions/0002.
42
+ */
43
+ readonly lockFencing: false;
44
+ /** 24 hours, Cloudflare's documented delaySeconds ceiling. */
45
+ readonly queueDelayMaxSeconds: 86400;
46
+ /**
47
+ * Documented as "128 KB", which does not say whether KB is 1,000 or 1,024
48
+ * bytes. The smaller reading is taken deliberately: rejecting a message the
49
+ * platform would have accepted costs a caller a smaller payload, while
50
+ * accepting one it refuses is the incident this file exists to prevent.
51
+ */
52
+ readonly messageMaxBytes: 128000;
53
+ /**
54
+ * R2's single-part upload ceiling, 5 GiB. NOT the 5 TiB object ceiling:
55
+ * reaching that needs multipart upload, which this adapter does not do, so
56
+ * 5 TiB would be a promise the code cannot keep.
57
+ */
58
+ readonly blobMaxBytes: 5368709120;
59
+ /** KV rejects an expirationTtl below 60 with `400 Invalid expiration_ttl`. */
60
+ readonly cacheMinTtlSeconds: 60;
61
+ /**
62
+ * Workflows' limit on a non-stream `step.do` return value, 1 MiB. A larger
63
+ * result fails the step at the platform. The executor checks it first, so
64
+ * the failure is a `LimitExceeded` it can report rather than a platform
65
+ * error it has to interpret.
66
+ */
67
+ readonly stepResultMaxBytes: 1048576;
68
+ /** D1 is SQLite. The journal adapter writes SQLite, and says so. */
69
+ readonly journalDialect: "sqlite";
70
+ /**
71
+ * Cron Triggers execute on UTC time and take no timezone. An application that
72
+ * owes somebody 09:00 local resolves that itself, which is what this value
73
+ * says.
74
+ */
75
+ readonly scheduleTimezone: "resolved-in-code";
76
+ /**
77
+ * A cron expression's finest field is the minute, so `* * * * *` is the
78
+ * most often a Cron Trigger fires and a slot shorter than that is skipped.
79
+ */
80
+ readonly scheduleMinIntervalSeconds: 60;
81
+ };
@@ -0,0 +1,81 @@
1
+ /**
2
+ * WHAT CLOUDFLARE ACTUALLY PROVIDES.
3
+ *
4
+ * Every value here has a row in `docs/platform-facts.md` carrying its source
5
+ * and the date it was checked, and that file opens with a table mapping each of
6
+ * these ten fields to its row. A number that cannot be traced to a row does
7
+ * not belong here, even when it is right.
8
+ *
9
+ * A MANIFEST THAT LIES IS WORSE THAN NO MANIFEST. With no manifest a
10
+ * requirement is checked by a person; with a manifest that overstates the
11
+ * target, `satisfies()` certifies a guarantee nothing implements and the check
12
+ * that exists to stop an incident becomes the thing that causes one.
13
+ *
14
+ * Eight of the ten came from a vendor limits page or a measurement. Two —
15
+ * `lock` and `lockFencing` — could not, and the comments on them say what their
16
+ * claim is true of.
17
+ */
18
+ export const CLOUDFLARE_MANIFEST = {
19
+ /**
20
+ * `advisory`, not `strict`, and the distinction is the one `docs/design.md`
21
+ * §6.1 draws: "a strict lock and a lease with a TTL are not the same thing,
22
+ * and a design correct under the first is a race under the second".
23
+ *
24
+ * TRUE OF: acquisition. D1 decides a claim exactly once, with a primary key,
25
+ * under the write lock. NOT true of the lease's lifetime — a holder that
26
+ * stalls past its TTL is still working while a second claim succeeds, and
27
+ * nothing stops the first one's write landing.
28
+ *
29
+ * §8.2 says Cloudflare's strict lock is `KeyedLock` over a Durable Object.
30
+ * That interface does not exist yet; when it does, this becomes a manifest
31
+ * change with its own issue. docs/decisions/0002.
32
+ */
33
+ lock: 'advisory',
34
+ /**
35
+ * `false`, and not because of anything Cloudflare does. `Ledger.claim`
36
+ * returns `{ status: 'claimed' }` and no token, so NO adapter can honestly
37
+ * declare fencing — `LOCAL_MANIFEST` declares `true` and is wrong by the same
38
+ * argument, which is recorded there rather than copied here.
39
+ *
40
+ * Declaring `true` to match it would put a lie in the one file the whole
41
+ * pre-deploy check depends on. docs/decisions/0002.
42
+ */
43
+ lockFencing: false,
44
+ /** 24 hours, Cloudflare's documented delaySeconds ceiling. */
45
+ queueDelayMaxSeconds: 86_400,
46
+ /**
47
+ * Documented as "128 KB", which does not say whether KB is 1,000 or 1,024
48
+ * bytes. The smaller reading is taken deliberately: rejecting a message the
49
+ * platform would have accepted costs a caller a smaller payload, while
50
+ * accepting one it refuses is the incident this file exists to prevent.
51
+ */
52
+ messageMaxBytes: 128_000,
53
+ /**
54
+ * R2's single-part upload ceiling, 5 GiB. NOT the 5 TiB object ceiling:
55
+ * reaching that needs multipart upload, which this adapter does not do, so
56
+ * 5 TiB would be a promise the code cannot keep.
57
+ */
58
+ blobMaxBytes: 5_368_709_120,
59
+ /** KV rejects an expirationTtl below 60 with `400 Invalid expiration_ttl`. */
60
+ cacheMinTtlSeconds: 60,
61
+ /**
62
+ * Workflows' limit on a non-stream `step.do` return value, 1 MiB. A larger
63
+ * result fails the step at the platform. The executor checks it first, so
64
+ * the failure is a `LimitExceeded` it can report rather than a platform
65
+ * error it has to interpret.
66
+ */
67
+ stepResultMaxBytes: 1_048_576,
68
+ /** D1 is SQLite. The journal adapter writes SQLite, and says so. */
69
+ journalDialect: 'sqlite',
70
+ /**
71
+ * Cron Triggers execute on UTC time and take no timezone. An application that
72
+ * owes somebody 09:00 local resolves that itself, which is what this value
73
+ * says.
74
+ */
75
+ scheduleTimezone: 'resolved-in-code',
76
+ /**
77
+ * A cron expression's finest field is the minute, so `* * * * *` is the
78
+ * most often a Cron Trigger fires and a slot shorter than that is skipped.
79
+ */
80
+ scheduleMinIntervalSeconds: 60,
81
+ };