@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,314 @@
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
+ import { withClient } from './with-client.js';
5
+ const TOOL = 'journal';
6
+ /**
7
+ * Every query this adapter can run, in one place. The D1 journal's queries
8
+ * with `$n` placeholders; its comments say why each one is shaped as it is.
9
+ *
10
+ * Which index serves which read, asserted by `journal.spec.ts` with EXPLAIN:
11
+ *
12
+ * recentRuns journal_runs_started_at
13
+ * unitsForRun journal_units_pkey
14
+ * unit journal_units_pkey, journal_steps_unit,
15
+ * journal_calls_pkey
16
+ * latestForUnit journal_units_unit_key
17
+ * failuresByReason journal_units_recorded_at
18
+ * delivery webhook_deliveries_pkey, webhook_tasks_pkey
19
+ * deadTasks webhook_tasks_state
20
+ * deadTasksByAction webhook_tasks_action_state
21
+ * stuckTasks webhook_tasks_state
22
+ */
23
+ const Q = {
24
+ startRun: `
25
+ INSERT INTO journal_runs
26
+ (run_id, job, trigger, mode, started_at, identity)
27
+ VALUES ($1, $2, $3, $4, $5, $6)
28
+ ON CONFLICT (run_id) DO UPDATE SET
29
+ job = $2, trigger = $3, mode = $4, started_at = $5, identity = $6
30
+ `,
31
+ finishRun: `UPDATE journal_runs SET ended_at = $2 WHERE run_id = $1`,
32
+ recordUnit: `
33
+ INSERT INTO journal_units
34
+ (run_id, unit_key, unit_type, recorded_at, outcome,
35
+ reason_code, plan_hash, plan_ref, duration_ms, external_ids)
36
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
37
+ ON CONFLICT (run_id, unit_key) DO UPDATE SET
38
+ unit_type = $3, recorded_at = $4, outcome = $5,
39
+ reason_code = $6, plan_hash = $7, plan_ref = $8,
40
+ duration_ms = $9, external_ids = $10
41
+ `,
42
+ clearCalls: `DELETE FROM journal_calls WHERE run_id = $1 AND unit_key = $2`,
43
+ // Every call of a unit in one statement, one array per column, so a unit
44
+ // with fifty calls is still one round trip. `seq` is the array position.
45
+ // Each call keeps its own run and unit keys, as on D1 and in memory.
46
+ recordCalls: `
47
+ INSERT INTO journal_calls
48
+ (run_id, unit_key, seq, system, operation,
49
+ status, http_status, idempotency_key, duration_ms)
50
+ SELECT c.run_id, c.unit_key, c.ord - 1, c.system, c.operation,
51
+ c.status, c.http_status, c.idempotency_key, c.duration_ms
52
+ FROM unnest(
53
+ $1::text[], $2::text[], $3::text[], $4::text[], $5::text[],
54
+ $6::integer[], $7::text[], $8::bigint[]
55
+ ) WITH ORDINALITY
56
+ AS c (run_id, unit_key, system, operation, status,
57
+ http_status, idempotency_key, duration_ms, ord)
58
+ `,
59
+ recordStep: `
60
+ INSERT INTO journal_steps
61
+ (run_id, unit_key, step, attempt, outcome,
62
+ reason_code, duration_ms, recorded_at)
63
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
64
+ `,
65
+ unitsForRun: `
66
+ SELECT * FROM journal_units
67
+ WHERE run_id = $1 ORDER BY unit_key LIMIT $2
68
+ `,
69
+ unit: `SELECT * FROM journal_units WHERE run_id = $1 AND unit_key = $2`,
70
+ stepsForUnit: `
71
+ SELECT * FROM journal_steps
72
+ WHERE run_id = $1 AND unit_key = $2 ORDER BY recorded_at, seq
73
+ `,
74
+ callsForUnit: `
75
+ SELECT * FROM journal_calls
76
+ WHERE run_id = $1 AND unit_key = $2 ORDER BY seq
77
+ `,
78
+ latestForUnit: `
79
+ SELECT * FROM journal_units
80
+ WHERE unit_key = $1 ORDER BY recorded_at DESC LIMIT 1
81
+ `,
82
+ // Unquoted aliases fold to lower case in Postgres, so the row keys stay
83
+ // snake_case and are renamed in code.
84
+ failuresByReason: `
85
+ SELECT reason_code, COUNT(*) AS count
86
+ FROM journal_units
87
+ WHERE recorded_at >= $1
88
+ AND reason_code IS NOT NULL
89
+ AND outcome != 'written'
90
+ GROUP BY reason_code
91
+ ORDER BY count DESC, reason_code ASC
92
+ `,
93
+ recentRuns: `SELECT * FROM journal_runs ORDER BY started_at DESC LIMIT $1`,
94
+ // One statement, so the delivery and its tasks land together or not at
95
+ // all. A retried delivery records again and touches no row already there.
96
+ recordDelivery: `
97
+ WITH delivery AS (
98
+ INSERT INTO webhook_deliveries
99
+ (delivery_id, source, topic, shop, webhook_id, body_key, received_at)
100
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
101
+ ON CONFLICT (delivery_id) DO NOTHING
102
+ )
103
+ INSERT INTO webhook_tasks (delivery_id, action, state, updated_at)
104
+ SELECT $1, action, 'received', $7 FROM unnest($8::text[]) AS action
105
+ ON CONFLICT (delivery_id, action) DO NOTHING
106
+ `,
107
+ // $5 is the states TASK_TRANSITIONS allows the move from.
108
+ moveTask: `
109
+ UPDATE webhook_tasks SET state = $3, updated_at = $4, reason_code = $6
110
+ WHERE delivery_id = $1 AND action = $2 AND state = ANY($5::text[])
111
+ `,
112
+ delivery: `SELECT * FROM webhook_deliveries WHERE delivery_id = $1`,
113
+ tasksForDelivery: `
114
+ SELECT * FROM webhook_tasks WHERE delivery_id = $1 ORDER BY action
115
+ `,
116
+ deadTasks: `
117
+ SELECT * FROM webhook_tasks
118
+ WHERE state = 'dead' AND (updated_at, delivery_id, action) > ($1, $2, $3)
119
+ ORDER BY updated_at, delivery_id, action LIMIT $4
120
+ `,
121
+ deadTasksByAction: `
122
+ SELECT * FROM webhook_tasks
123
+ WHERE action = $5 AND state = 'dead'
124
+ AND (updated_at, delivery_id, action) > ($1, $2, $3)
125
+ ORDER BY updated_at, delivery_id LIMIT $4
126
+ `,
127
+ stuckTasks: `
128
+ SELECT * FROM webhook_tasks
129
+ WHERE state IN ('received', 'processing') AND updated_at < $1
130
+ ORDER BY updated_at, delivery_id, action LIMIT $2
131
+ `,
132
+ };
133
+ export class PostgresJournal {
134
+ o;
135
+ constructor(o) {
136
+ this.o = o;
137
+ }
138
+ async startRun(row) {
139
+ await this.#call('startRun', async () => this.o.pool.query(Q.startRun, [
140
+ row.runId,
141
+ row.job,
142
+ row.trigger,
143
+ row.mode,
144
+ row.startedAt,
145
+ JSON.stringify(row.identity),
146
+ ]));
147
+ }
148
+ async finishRun(runId, endedAt) {
149
+ await this.#call('finishRun', async () => this.o.pool.query(Q.finishRun, [runId, endedAt]));
150
+ }
151
+ /**
152
+ * One transaction, so a unit is never half recorded: the unit row, the
153
+ * clear of its previous calls, and all its calls in one INSERT.
154
+ */
155
+ async recordUnit(unit, calls) {
156
+ await this.#call('recordUnit', async () => withClient(this.o.pool, async (client) => {
157
+ try {
158
+ await client.query('BEGIN');
159
+ await client.query(Q.recordUnit, [
160
+ unit.runId,
161
+ unit.unitKey,
162
+ unit.unitType,
163
+ unit.recordedAt,
164
+ unit.outcome,
165
+ unit.reasonCode ?? null,
166
+ unit.planHash ?? null,
167
+ unit.planRef ?? null,
168
+ unit.durationMs,
169
+ unit.externalIds === undefined
170
+ ? null
171
+ : JSON.stringify(unit.externalIds),
172
+ ]);
173
+ await client.query(Q.clearCalls, [unit.runId, unit.unitKey]);
174
+ if (calls.length > 0) {
175
+ await client.query(Q.recordCalls, [
176
+ calls.map((c) => c.runId),
177
+ calls.map((c) => c.unitKey),
178
+ calls.map((c) => c.system),
179
+ calls.map((c) => c.operation),
180
+ calls.map((c) => c.status),
181
+ calls.map((c) => c.httpStatus ?? null),
182
+ calls.map((c) => c.idempotencyKey ?? null),
183
+ calls.map((c) => c.durationMs ?? null),
184
+ ]);
185
+ }
186
+ await client.query('COMMIT');
187
+ }
188
+ catch (error) {
189
+ await client.query('ROLLBACK').catch(() => { });
190
+ throw error;
191
+ }
192
+ }));
193
+ }
194
+ /** Catches every failure and logs it, as the contract requires. */
195
+ async recordStep(step) {
196
+ try {
197
+ await this.#call('recordStep', async () => this.o.pool.query(Q.recordStep, [
198
+ step.runId,
199
+ step.unitKey,
200
+ step.step,
201
+ step.attempt,
202
+ step.outcome,
203
+ step.reasonCode ?? null,
204
+ step.durationMs,
205
+ step.recordedAt,
206
+ ]));
207
+ }
208
+ catch (e) {
209
+ this.o.logger.error('journal step row not recorded', {
210
+ tool: TOOL,
211
+ operation: 'recordStep',
212
+ fault: e instanceof Error ? e.name : 'unknown',
213
+ runId: step.runId,
214
+ unitKey: step.unitKey,
215
+ step: step.step,
216
+ attempt: step.attempt,
217
+ outcome: step.outcome,
218
+ });
219
+ }
220
+ }
221
+ async unitsForRun(runId, limit = DEFAULT_UNIT_LIMIT) {
222
+ const { rows } = await this.#call('unitsForRun', async () => this.o.pool.query(Q.unitsForRun, [runId, limit]));
223
+ return rows.map(toUnitRow);
224
+ }
225
+ async unit(runId, unitKey) {
226
+ const [units, steps, calls] = await this.#call('unit', async () => Promise.all([
227
+ this.o.pool.query(Q.unit, [runId, unitKey]),
228
+ this.o.pool.query(Q.stepsForUnit, [runId, unitKey]),
229
+ this.o.pool.query(Q.callsForUnit, [runId, unitKey]),
230
+ ]));
231
+ const record = units.rows[0];
232
+ if (record === undefined) {
233
+ return undefined;
234
+ }
235
+ return {
236
+ unit: toUnitRow(record),
237
+ steps: steps.rows.map(toStepRow),
238
+ calls: calls.rows.map(toCallRow),
239
+ };
240
+ }
241
+ async latestForUnit(unitKey) {
242
+ const { rows } = await this.#call('latestForUnit', async () => this.o.pool.query(Q.latestForUnit, [unitKey]));
243
+ const record = rows[0];
244
+ return record === undefined ? undefined : toUnitRow(record);
245
+ }
246
+ async failuresByReason(since) {
247
+ const { rows } = await this.#call('failuresByReason', async () => this.o.pool.query(Q.failuresByReason, [since]));
248
+ // COUNT(*) is a BIGINT, which arrives as a string.
249
+ return rows.map((r) => ({
250
+ reasonCode: r.reason_code,
251
+ count: Number(r.count),
252
+ }));
253
+ }
254
+ async recentRuns(limit = DEFAULT_RUN_LIMIT) {
255
+ const { rows } = await this.#call('recentRuns', async () => this.o.pool.query(Q.recentRuns, [limit]));
256
+ return rows.map(toRunRow);
257
+ }
258
+ async recordDelivery(delivery, actions) {
259
+ await this.#call('recordDelivery', async () => this.o.pool.query(Q.recordDelivery, [
260
+ delivery.deliveryId,
261
+ delivery.source,
262
+ delivery.topic,
263
+ delivery.shop,
264
+ delivery.webhookId,
265
+ delivery.bodyKey,
266
+ delivery.receivedAt,
267
+ actions,
268
+ ]));
269
+ }
270
+ async moveTask(deliveryId, action, to, at, reasonCode) {
271
+ const { rowCount } = await this.#call('moveTask', async () => this.o.pool.query(Q.moveTask, [
272
+ deliveryId,
273
+ action,
274
+ to,
275
+ at,
276
+ TASK_TRANSITIONS[to],
277
+ reasonCode ?? null,
278
+ ]));
279
+ return rowCount === 1;
280
+ }
281
+ async delivery(deliveryId) {
282
+ const [delivery, tasks] = await this.#call('delivery', async () => Promise.all([
283
+ this.o.pool.query(Q.delivery, [deliveryId]),
284
+ this.o.pool.query(Q.tasksForDelivery, [deliveryId]),
285
+ ]));
286
+ const record = delivery.rows[0];
287
+ return record === undefined
288
+ ? undefined
289
+ : { delivery: toDeliveryRow(record), tasks: tasks.rows.map(toTaskRow) };
290
+ }
291
+ async deadTasks({ action, after = FIRST_TASK, limit = DEFAULT_UNIT_LIMIT, } = {}) {
292
+ const cursor = [after.updatedAt, after.deliveryId, after.action, limit];
293
+ const { rows } = await this.#call('deadTasks', async () => action === undefined
294
+ ? this.o.pool.query(Q.deadTasks, cursor)
295
+ : this.o.pool.query(Q.deadTasksByAction, [
296
+ ...cursor,
297
+ action,
298
+ ]));
299
+ return rows.map(toTaskRow);
300
+ }
301
+ async stuckTasks(before, limit = DEFAULT_UNIT_LIMIT) {
302
+ const { rows } = await this.#call('stuckTasks', async () => this.o.pool.query(Q.stuckTasks, [before, limit]));
303
+ return rows.map(toTaskRow);
304
+ }
305
+ async #call(operation, f) {
306
+ try {
307
+ return await f();
308
+ }
309
+ catch (e) {
310
+ throw toFault(TOOL, operation, e);
311
+ }
312
+ }
313
+ }
314
+ export { Q as JOURNAL_QUERIES };
@@ -0,0 +1,16 @@
1
+ import type pg from 'pg';
2
+ import type { ClaimResult, Clock, Ledger } from '../../contracts/index.js';
3
+ export type PostgresLedgerOptions = {
4
+ /** The app's pool. The ledger never opens its own. docs/decisions/0007. */
5
+ readonly pool: pg.Pool;
6
+ readonly clock: Clock;
7
+ };
8
+ export declare class PostgresLedger implements Ledger {
9
+ #private;
10
+ private readonly o;
11
+ constructor(o: PostgresLedgerOptions);
12
+ claim(key: string, leaseSeconds: number): Promise<ClaimResult>;
13
+ complete(key: string, ttlSeconds: number): Promise<void>;
14
+ /** Releasing a key that was never claimed deletes nothing and is not an error. */
15
+ release(key: string): Promise<void>;
16
+ }
@@ -0,0 +1,97 @@
1
+ import { Unavailable, fromEpochMs, toIso } from '../../contracts/index.js';
2
+ import { isSerializationFailure, toFault } from './faults.js';
3
+ const TOOL = 'ledger';
4
+ /**
5
+ * One conditional write, as in the D1 ledger, whose comments say why a
6
+ * SELECT-then-INSERT would lose a race. `key` is the primary key, so two
7
+ * concurrent claims cannot both insert. The loser of an insert race waits for
8
+ * the winner to commit, then evaluates the `WHERE` against the winner's row,
9
+ * which refuses while the lease is live.
10
+ *
11
+ * `$2` is the caller's `now`, from the injected Clock, never `now()`: the
12
+ * suite advances a test clock and expects a reclaim.
13
+ */
14
+ const CLAIM = `
15
+ INSERT INTO ledger_claims (key, claimed_at, expires_at)
16
+ VALUES ($1, $2, $3)
17
+ ON CONFLICT (key) DO UPDATE SET claimed_at = $2, expires_at = $3,
18
+ completed_at = NULL
19
+ WHERE ledger_claims.expires_at <= $2
20
+ RETURNING claimed_at
21
+ `;
22
+ /** Only ever asked after the write above has already decided we lost. */
23
+ const HOLDER = `SELECT claimed_at, completed_at FROM ledger_claims WHERE key = $1`;
24
+ /**
25
+ * An upsert, not an update: there is no token to check the holder against, and
26
+ * a row that was released or swept still had its work done.
27
+ */
28
+ const COMPLETE = `
29
+ INSERT INTO ledger_claims (key, claimed_at, expires_at, completed_at)
30
+ VALUES ($1, $2, $3, $2)
31
+ ON CONFLICT (key) DO UPDATE SET completed_at = $2, expires_at = $3
32
+ `;
33
+ const RELEASE = `DELETE FROM ledger_claims WHERE key = $1`;
34
+ /** As in the D1 ledger: a holder that vanished three times running is a fault. */
35
+ const ATTEMPTS = 3;
36
+ export class PostgresLedger {
37
+ o;
38
+ constructor(o) {
39
+ this.o = o;
40
+ }
41
+ async claim(key, leaseSeconds) {
42
+ for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
43
+ const now = this.o.clock.now();
44
+ const expiresAt = now + leaseSeconds * 1000;
45
+ const won = await this.#call('claim', async () => {
46
+ try {
47
+ return await this.o.pool.query(CLAIM, [key, now, expiresAt]);
48
+ }
49
+ catch (e) {
50
+ // The app may run its pool at REPEATABLE READ or SERIALIZABLE. There
51
+ // a lost race is this error rather than an empty RETURNING, and the
52
+ // read below finds the winner either way.
53
+ if (isSerializationFailure(e)) {
54
+ return undefined;
55
+ }
56
+ throw e;
57
+ }
58
+ });
59
+ if (won?.rowCount === 1) {
60
+ return { status: 'claimed' };
61
+ }
62
+ const holder = await this.#call('claim', async () => this.o.pool.query(HOLDER, [key]));
63
+ const row = holder.rows[0];
64
+ if (row !== undefined) {
65
+ // BIGINT arrives as a string. Exact up to 2^53 ms. docs/decisions/0007.
66
+ return row.completed_at === null
67
+ ? {
68
+ status: 'in-progress',
69
+ claimedAt: toIso(fromEpochMs(Number(row.claimed_at))),
70
+ }
71
+ : {
72
+ status: 'completed',
73
+ completedAt: toIso(fromEpochMs(Number(row.completed_at))),
74
+ };
75
+ }
76
+ }
77
+ throw new Unavailable(TOOL, `claim on '${key}' found neither a winner nor a holder in ${ATTEMPTS} attempts`);
78
+ }
79
+ async complete(key, ttlSeconds) {
80
+ const now = this.o.clock.now();
81
+ await this.#call('complete', async () => this.o.pool.query(COMPLETE, [key, now, now + ttlSeconds * 1000]));
82
+ }
83
+ /** Releasing a key that was never claimed deletes nothing and is not an error. */
84
+ async release(key) {
85
+ await this.#call('release', async () => this.o.pool.query(RELEASE, [key]));
86
+ }
87
+ async #call(operation, f) {
88
+ try {
89
+ return await f();
90
+ }
91
+ catch (e) {
92
+ // A unique violation is absent on purpose: ON CONFLICT handles the
93
+ // collision, so losing a race is an empty RETURNING, never an error.
94
+ throw toFault(TOOL, operation, e);
95
+ }
96
+ }
97
+ }
@@ -0,0 +1,19 @@
1
+ import type { DeploymentIdentity, LogFields, Logger } from '../../contracts/index.js';
2
+ /**
3
+ * One JSON object per line on stdout, which is where a container platform
4
+ * collects a process's logs. The level is a field, so every level goes to the
5
+ * same stream and a reader filters on it.
6
+ *
7
+ * `identity` and `correlationId` are written last, after `fields`, so a field
8
+ * a caller passes can never shadow them. CloudflareLogger does the same.
9
+ */
10
+ export declare class StdoutLogger implements Logger {
11
+ #private;
12
+ readonly identity: DeploymentIdentity;
13
+ readonly correlationId: string;
14
+ constructor(identity: DeploymentIdentity, correlationId: string);
15
+ info(message: string, fields?: LogFields): void;
16
+ warn(message: string, fields?: LogFields): void;
17
+ error(message: string, fields?: LogFields): void;
18
+ child(correlationId: string): Logger;
19
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * One JSON object per line on stdout, which is where a container platform
3
+ * collects a process's logs. The level is a field, so every level goes to the
4
+ * same stream and a reader filters on it.
5
+ *
6
+ * `identity` and `correlationId` are written last, after `fields`, so a field
7
+ * a caller passes can never shadow them. CloudflareLogger does the same.
8
+ */
9
+ export class StdoutLogger {
10
+ identity;
11
+ correlationId;
12
+ constructor(identity, correlationId) {
13
+ this.identity = identity;
14
+ this.correlationId = correlationId;
15
+ }
16
+ info(message, fields = {}) {
17
+ this.#write('info', message, fields);
18
+ }
19
+ warn(message, fields = {}) {
20
+ this.#write('warn', message, fields);
21
+ }
22
+ error(message, fields = {}) {
23
+ this.#write('error', message, fields);
24
+ }
25
+ child(correlationId) {
26
+ return new StdoutLogger(this.identity, correlationId);
27
+ }
28
+ #write(level, message, fields) {
29
+ process.stdout.write(JSON.stringify({
30
+ ...fields,
31
+ level,
32
+ message,
33
+ identity: this.identity,
34
+ correlationId: this.correlationId,
35
+ }) + '\n');
36
+ }
37
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * WHAT POSTGRES PLUS S3-COMPATIBLE STORAGE ACTUALLY PROVIDES.
3
+ *
4
+ * Every value has a row in `docs/platform-facts.md`, in the table "The
5
+ * Postgres manifest, field by field". Postgres sets no ceiling on a delay, a
6
+ * message or a step result, so those three are the library's own limits, and
7
+ * their rows say so.
8
+ */
9
+ export declare const POSTGRES_MANIFEST: {
10
+ /**
11
+ * `advisory`, for the reason the other two manifests give: `Ledger.claim`
12
+ * is a lease. A unique constraint decides a claim exactly once, but a holder
13
+ * that outlives its ttl is not stopped. docs/decisions/0002.
14
+ */
15
+ readonly lock: "advisory";
16
+ /** `false`: `ClaimResult` carries no token to fence with. docs/decisions/0002. */
17
+ readonly lockFencing: false;
18
+ /**
19
+ * 7 days. `visible_at` is BIGINT milliseconds, which reaches far past this,
20
+ * so the limit is the library's: a delay of weeks is more likely seconds
21
+ * passed as milliseconds than a plan.
22
+ */
23
+ readonly queueDelayMaxSeconds: 604800;
24
+ /**
25
+ * 1 MB. A body is TEXT, which holds about 1 GB, but a consumer claims a
26
+ * batch of rows at once. A payload that needs more belongs in the blob store.
27
+ */
28
+ readonly messageMaxBytes: 1000000;
29
+ /** The largest single PUT, because S3BlobStore does no multipart upload. */
30
+ readonly blobMaxBytes: 5368709120;
31
+ /**
32
+ * Postgres expires rows by comparing epoch milliseconds, so it has no floor.
33
+ * 1 second is the smallest ttl a whole-second interface can ask for.
34
+ */
35
+ readonly cacheMinTtlSeconds: 1;
36
+ readonly journalDialect: "postgres";
37
+ /** No cron here, only `startScheduler`'s intervals. A job that owes local time resolves it. */
38
+ readonly scheduleTimezone: "resolved-in-code";
39
+ /**
40
+ * `startScheduler` ticks as often as it is told, so the library's floor:
41
+ * one whole second, the smallest a whole-second interface can ask for.
42
+ */
43
+ readonly scheduleMinIntervalSeconds: 1;
44
+ /**
45
+ * 1 MiB, the same as Workflows and the memory adapter. This target has no
46
+ * Jobs executor yet. When it has one, a result is TEXT like every JSON
47
+ * column here (decision 0007), which holds about 1 GB, so this is the
48
+ * library's limit, not Postgres's. A larger one would let a step pass on
49
+ * Postgres and fail on Workflows.
50
+ */
51
+ readonly stepResultMaxBytes: 1048576;
52
+ };
@@ -0,0 +1,53 @@
1
+ import { S3_MAX_PUT_BYTES } from '../s3/blob-store.js';
2
+ /**
3
+ * WHAT POSTGRES PLUS S3-COMPATIBLE STORAGE ACTUALLY PROVIDES.
4
+ *
5
+ * Every value has a row in `docs/platform-facts.md`, in the table "The
6
+ * Postgres manifest, field by field". Postgres sets no ceiling on a delay, a
7
+ * message or a step result, so those three are the library's own limits, and
8
+ * their rows say so.
9
+ */
10
+ export const POSTGRES_MANIFEST = {
11
+ /**
12
+ * `advisory`, for the reason the other two manifests give: `Ledger.claim`
13
+ * is a lease. A unique constraint decides a claim exactly once, but a holder
14
+ * that outlives its ttl is not stopped. docs/decisions/0002.
15
+ */
16
+ lock: 'advisory',
17
+ /** `false`: `ClaimResult` carries no token to fence with. docs/decisions/0002. */
18
+ lockFencing: false,
19
+ /**
20
+ * 7 days. `visible_at` is BIGINT milliseconds, which reaches far past this,
21
+ * so the limit is the library's: a delay of weeks is more likely seconds
22
+ * passed as milliseconds than a plan.
23
+ */
24
+ queueDelayMaxSeconds: 604_800,
25
+ /**
26
+ * 1 MB. A body is TEXT, which holds about 1 GB, but a consumer claims a
27
+ * batch of rows at once. A payload that needs more belongs in the blob store.
28
+ */
29
+ messageMaxBytes: 1_000_000,
30
+ /** The largest single PUT, because S3BlobStore does no multipart upload. */
31
+ blobMaxBytes: S3_MAX_PUT_BYTES,
32
+ /**
33
+ * Postgres expires rows by comparing epoch milliseconds, so it has no floor.
34
+ * 1 second is the smallest ttl a whole-second interface can ask for.
35
+ */
36
+ cacheMinTtlSeconds: 1,
37
+ journalDialect: 'postgres',
38
+ /** No cron here, only `startScheduler`'s intervals. A job that owes local time resolves it. */
39
+ scheduleTimezone: 'resolved-in-code',
40
+ /**
41
+ * `startScheduler` ticks as often as it is told, so the library's floor:
42
+ * one whole second, the smallest a whole-second interface can ask for.
43
+ */
44
+ scheduleMinIntervalSeconds: 1,
45
+ /**
46
+ * 1 MiB, the same as Workflows and the memory adapter. This target has no
47
+ * Jobs executor yet. When it has one, a result is TEXT like every JSON
48
+ * column here (decision 0007), which holds about 1 GB, so this is the
49
+ * library's limit, not Postgres's. A larger one would let a step pass on
50
+ * Postgres and fail on Workflows.
51
+ */
52
+ stepResultMaxBytes: 1_048_576,
53
+ };
@@ -0,0 +1,20 @@
1
+ import type pg from 'pg';
2
+ /** The library's Postgres set. docs/decisions/0007 says why it sits here. */
3
+ export declare const MIGRATIONS_DIR: string;
4
+ /**
5
+ * Applies every file in `dir` not yet recorded, in name order, and returns the
6
+ * names it applied. An empty result means there was nothing to do.
7
+ *
8
+ * Each file runs in its own transaction, which first takes a transaction-level
9
+ * advisory lock. Two containers starting together therefore apply each file
10
+ * once: the second waits, then finds it recorded. Postgres DDL is
11
+ * transactional, so a file that fails leaves nothing half-applied, and its
12
+ * name is not recorded. A recorded file whose contents changed stops the run.
13
+ */
14
+ export declare function applyMigrations(pool: pg.Pool, dir?: string): Promise<string[]>;
15
+ /**
16
+ * The files in `dir` not yet recorded, in name order. For an app's start-up
17
+ * check: it only reads, so the app's role needs no DDL rights, and it never
18
+ * waits on a migrator's lock.
19
+ */
20
+ export declare function pendingMigrations(pool: pg.Pool, dir?: string): Promise<string[]>;