@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,96 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile, readdir } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { withClient } from './with-client.js';
6
+ /** The library's Postgres set. docs/decisions/0007 says why it sits here. */
7
+ export const MIGRATIONS_DIR = fileURLToPath(new URL('../../../migrations/postgres/', import.meta.url));
8
+ /**
9
+ * The same name decision 0004 fixed for D1, so an operator looks in one place
10
+ * on either dialect. The app's own migrations keep their own table.
11
+ *
12
+ * `checksum` is what makes "forward-only" a check rather than a hope: a file
13
+ * edited after it was applied no longer matches, and the run stops instead
14
+ * of leaving databases that disagree about what that file did.
15
+ */
16
+ const BOOKKEEPING = `
17
+ CREATE TABLE IF NOT EXISTS anatta_middleware_migrations (
18
+ name TEXT PRIMARY KEY,
19
+ checksum TEXT NOT NULL,
20
+ applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
21
+ )
22
+ `;
23
+ /** CRLF is folded to LF first, so a Windows checkout of the same file matches. */
24
+ const checksumOf = (sql) => createHash('sha256').update(sql.replaceAll('\r\n', '\n')).digest('hex');
25
+ /**
26
+ * Any fixed key works, as long as nothing else in the database uses it. This
27
+ * one is the first eight bytes of sha256('anatta_middleware_migrations'), read
28
+ * as a signed big-endian integer.
29
+ */
30
+ const LOCK_KEY = '-5465547643023699143';
31
+ const sqlFiles = async (dir) => (await readdir(dir)).filter((n) => n.endsWith('.sql')).sort();
32
+ /**
33
+ * Applies every file in `dir` not yet recorded, in name order, and returns the
34
+ * names it applied. An empty result means there was nothing to do.
35
+ *
36
+ * Each file runs in its own transaction, which first takes a transaction-level
37
+ * advisory lock. Two containers starting together therefore apply each file
38
+ * once: the second waits, then finds it recorded. Postgres DDL is
39
+ * transactional, so a file that fails leaves nothing half-applied, and its
40
+ * name is not recorded. A recorded file whose contents changed stops the run.
41
+ */
42
+ export async function applyMigrations(pool, dir = MIGRATIONS_DIR) {
43
+ const names = await sqlFiles(dir);
44
+ return withClient(pool, async (client) => {
45
+ const applied = [];
46
+ for (const name of names) {
47
+ const sql = await readFile(path.join(dir, name), 'utf8');
48
+ if (await applyOne(client, name, sql)) {
49
+ applied.push(name);
50
+ }
51
+ }
52
+ return applied;
53
+ });
54
+ }
55
+ /**
56
+ * The files in `dir` not yet recorded, in name order. For an app's start-up
57
+ * check: it only reads, so the app's role needs no DDL rights, and it never
58
+ * waits on a migrator's lock.
59
+ */
60
+ export async function pendingMigrations(pool, dir = MIGRATIONS_DIR) {
61
+ const names = await sqlFiles(dir);
62
+ const { rows } = await pool.query("SELECT to_regclass('anatta_middleware_migrations') IS NOT NULL AS found");
63
+ if (rows[0]?.found !== true) {
64
+ return names;
65
+ }
66
+ const recorded = await pool.query('SELECT name FROM anatta_middleware_migrations');
67
+ const applied = new Set(recorded.rows.map((r) => r.name));
68
+ return names.filter((n) => !applied.has(n));
69
+ }
70
+ async function applyOne(client, name, sql) {
71
+ await client.query('BEGIN');
72
+ try {
73
+ await client.query('SELECT pg_advisory_xact_lock($1)', [LOCK_KEY]);
74
+ // Inside the lock: two first runs racing on CREATE TABLE IF NOT EXISTS
75
+ // can still collide in the catalog.
76
+ await client.query(BOOKKEEPING);
77
+ const checksum = checksumOf(sql);
78
+ const { rows } = await client.query('SELECT checksum FROM anatta_middleware_migrations WHERE name = $1', [name]);
79
+ const recorded = rows[0]?.checksum;
80
+ const pending = recorded === undefined;
81
+ if (pending) {
82
+ await client.query(sql);
83
+ await client.query('INSERT INTO anatta_middleware_migrations (name, checksum) VALUES ($1, $2)', [name, checksum]);
84
+ }
85
+ else if (recorded !== checksum) {
86
+ throw new Error(`Migration ${name} was edited after it was applied. Migrations are ` +
87
+ 'forward-only: restore the file and put the change in a new one.');
88
+ }
89
+ await client.query('COMMIT');
90
+ return pending;
91
+ }
92
+ catch (error) {
93
+ await client.query('ROLLBACK');
94
+ throw error;
95
+ }
96
+ }
@@ -0,0 +1,64 @@
1
+ import type pg from 'pg';
2
+ import type { Clock, DeploymentIdentity, Logger, MessageId, Queue, QueueBatch, QueueMessage, SendOptions } from '../../contracts/index.js';
3
+ export type PostgresQueueOptions = {
4
+ /** The app's pool. The queue never opens its own. docs/decisions/0007. */
5
+ readonly pool: pg.Pool;
6
+ readonly clock: Clock;
7
+ readonly identity: DeploymentIdentity;
8
+ /** Which queue this is. One table serves every queue an app has. */
9
+ readonly name: string;
10
+ readonly maxDelaySeconds: number;
11
+ readonly maxBytes: number;
12
+ /** Deliveries before a message goes to the dead letters. Default 5. */
13
+ readonly maxAttempts?: number;
14
+ /** How long a claimed message stays hidden from other consumers. Default 300. */
15
+ readonly leaseSeconds?: number;
16
+ };
17
+ export type RunOptions = {
18
+ /** Aborting stops the loop after the batch in hand is settled. */
19
+ readonly signal: AbortSignal;
20
+ /** Where a failing consumer and a database fault are reported. */
21
+ readonly logger: Logger;
22
+ readonly batchSize?: number;
23
+ /** The wait after an empty claim. Default 1,000 ms. */
24
+ readonly idleMs?: number;
25
+ };
26
+ export declare class PostgresQueue<T> implements Queue<T> {
27
+ #private;
28
+ private readonly o;
29
+ constructor(o: PostgresQueueOptions);
30
+ send(body: T, options?: SendOptions): Promise<MessageId>;
31
+ sendBatch(bodies: readonly T[], options?: SendOptions): Promise<readonly MessageId[]>;
32
+ /**
33
+ * Claims up to `batchSize` visible messages, hands them to `consumer`, and
34
+ * settles each one as the consumer said.
35
+ *
36
+ * Neither acked nor retried is a retry, as in the memory queue: at least
37
+ * once means an unhandled message is delivered again, never lost. A consumer
38
+ * that throws settles nothing, and its messages come back when their lease
39
+ * runs out, as they would after a crash.
40
+ */
41
+ drain(consumer: (batch: QueueBatch<T>) => Promise<void>, batchSize?: number): Promise<void>;
42
+ /**
43
+ * The long-running consumer for a Node worker: drains until `signal` is
44
+ * aborted, waiting `idleMs` after an empty claim. Wire the signal to
45
+ * SIGTERM. A batch in hand is settled before the loop returns, and messages
46
+ * claimed but not settled are left to their lease.
47
+ *
48
+ * A consumer that throws is logged with its message ids, and the loop goes
49
+ * on: those messages come back when their lease runs out. A retryable fault
50
+ * in the database is logged and waited out, doubling from `idleMs` up to 30
51
+ * seconds. Any other fault, such as a missing table, ends the loop, so the
52
+ * worker fails where someone will see it.
53
+ */
54
+ run(consumer: (batch: QueueBatch<T>) => Promise<void>, options: RunOptions): Promise<void>;
55
+ pendingCount(): Promise<number>;
56
+ deadCount(): Promise<number>;
57
+ /** The newest dead letters first, for an operator to read. */
58
+ deadLetters(limit?: number): Promise<readonly QueueMessage<T>[]>;
59
+ /**
60
+ * Moves a dead letter back to the queue, visible now, with its attempt
61
+ * count reset. False when there is no such dead letter.
62
+ */
63
+ replay(id: MessageId): Promise<boolean>;
64
+ }
@@ -0,0 +1,333 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { setTimeout as sleep } from 'node:timers/promises';
3
+ import { LimitExceeded, ToolFault, checkDuration, plusSeconds, toIso, fromEpochMs, } from '../../contracts/index.js';
4
+ import { toFault } from './faults.js';
5
+ import { withClient } from './with-client.js';
6
+ const TOOL = 'queue';
7
+ /**
8
+ * Long enough for one batch of the tagger's work, a few Admin API calls with
9
+ * their own retries, several times over. A lease that runs out while a
10
+ * consumer is still working delivers the message twice; one that is too long
11
+ * only delays recovery after a crash. Duplicates are allowed (delivery is at
12
+ * least once), so the default leans long.
13
+ */
14
+ const DEFAULT_LEASE_SECONDS = 300;
15
+ /** As Cloudflare's default, so a message gets the same number of tries. */
16
+ const DEFAULT_MAX_ATTEMPTS = 5;
17
+ const DEFAULT_BATCH_SIZE = 10;
18
+ /** How long `run` waits before asking again when the queue was empty. */
19
+ const DEFAULT_IDLE_MS = 1_000;
20
+ /** The longest `run` waits after a fault, however many in a row. */
21
+ const MAX_BACKOFF_MS = 30_000;
22
+ const Q = {
23
+ // One statement for any number of bodies: one array per column.
24
+ send: `
25
+ INSERT INTO queue_messages
26
+ (id, queue, body, identity, enqueued_at, visible_at, attempt)
27
+ SELECT m.id, $1, m.body, $2, $3, $4, 0
28
+ FROM unnest($5::text[], $6::text[]) AS m (id, body)
29
+ `,
30
+ // A message that has used every attempt and is visible again, because its
31
+ // last consumer stopped without settling it, goes to the dead letters
32
+ // rather than round again. Without this a message that crashes its
33
+ // consumer would be delivered for ever.
34
+ bury: `
35
+ WITH dead AS (
36
+ DELETE FROM queue_messages WHERE id IN (
37
+ SELECT id FROM queue_messages
38
+ WHERE queue = $1 AND visible_at <= $2 AND attempt >= $3
39
+ FOR UPDATE SKIP LOCKED
40
+ )
41
+ RETURNING id, queue, body, identity, enqueued_at, attempt
42
+ )
43
+ INSERT INTO queue_dead_letters
44
+ (id, queue, body, identity, enqueued_at, attempt, dead_at)
45
+ SELECT id, queue, body, identity, enqueued_at, attempt, $2 FROM dead
46
+ `,
47
+ // The claim. SKIP LOCKED hands two consumers different messages instead of
48
+ // making one wait for the other. Moving `visible_at` to the end of the lease
49
+ // hides the message from every other claim until then.
50
+ claim: `
51
+ UPDATE queue_messages SET visible_at = $3, attempt = attempt + 1
52
+ WHERE id IN (
53
+ SELECT id FROM queue_messages
54
+ WHERE queue = $1 AND visible_at <= $2
55
+ ORDER BY visible_at
56
+ LIMIT $4
57
+ FOR UPDATE SKIP LOCKED
58
+ )
59
+ RETURNING id, body, identity, enqueued_at, attempt
60
+ `,
61
+ ack: `DELETE FROM queue_messages WHERE id = ANY($1::text[])`,
62
+ // Only while the row still holds the attempt this consumer was given. If
63
+ // the lease ran out and another consumer claimed the message, the attempt
64
+ // moved on, and this consumer's retry must not reset that one's lease.
65
+ retry: `
66
+ UPDATE queue_messages m SET visible_at = r.visible_at
67
+ FROM unnest($1::text[], $2::integer[], $3::bigint[])
68
+ AS r (id, attempt, visible_at)
69
+ WHERE m.id = r.id AND m.attempt = r.attempt
70
+ `,
71
+ // A retried message that has used every attempt goes to the dead letters
72
+ // now, rather than waiting to be claimed once more.
73
+ exhaust: `
74
+ WITH dead AS (
75
+ DELETE FROM queue_messages m
76
+ USING unnest($1::text[], $2::integer[]) AS r (id, attempt)
77
+ WHERE m.id = r.id AND m.attempt = r.attempt AND m.attempt >= $3
78
+ RETURNING m.id, m.queue, m.body, m.identity, m.enqueued_at, m.attempt
79
+ )
80
+ INSERT INTO queue_dead_letters
81
+ (id, queue, body, identity, enqueued_at, attempt, dead_at)
82
+ SELECT id, queue, body, identity, enqueued_at, attempt, $4 FROM dead
83
+ `,
84
+ pending: `SELECT COUNT(*) AS n FROM queue_messages WHERE queue = $1`,
85
+ deadCount: `SELECT COUNT(*) AS n FROM queue_dead_letters WHERE queue = $1`,
86
+ deadLetters: `
87
+ SELECT id, body, identity, enqueued_at, attempt FROM queue_dead_letters
88
+ WHERE queue = $1 ORDER BY dead_at DESC, id LIMIT $2
89
+ `,
90
+ // Back to the queue with a fresh count, visible now.
91
+ replay: `
92
+ WITH back AS (
93
+ DELETE FROM queue_dead_letters WHERE queue = $1 AND id = $2
94
+ RETURNING id, queue, body, identity, enqueued_at
95
+ )
96
+ INSERT INTO queue_messages
97
+ (id, queue, body, identity, enqueued_at, visible_at, attempt)
98
+ SELECT id, queue, body, identity, enqueued_at, $3, 0 FROM back
99
+ `,
100
+ };
101
+ const toMessage = (r) => ({
102
+ id: r.id,
103
+ body: JSON.parse(r.body),
104
+ attempt: r.attempt,
105
+ // BIGINT arrives as a string. docs/decisions/0007.
106
+ enqueuedAt: toIso(fromEpochMs(Number(r.enqueued_at))),
107
+ identity: JSON.parse(r.identity),
108
+ });
109
+ export class PostgresQueue {
110
+ o;
111
+ #maxAttempts;
112
+ #leaseSeconds;
113
+ constructor(o) {
114
+ this.o = o;
115
+ this.#maxAttempts = o.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
116
+ this.#leaseSeconds = o.leaseSeconds ?? DEFAULT_LEASE_SECONDS;
117
+ }
118
+ async send(body, options) {
119
+ const [id] = await this.#send('send', [body], options);
120
+ return id;
121
+ }
122
+ async sendBatch(bodies, options) {
123
+ return this.#send('sendBatch', bodies, options);
124
+ }
125
+ /**
126
+ * Claims up to `batchSize` visible messages, hands them to `consumer`, and
127
+ * settles each one as the consumer said.
128
+ *
129
+ * Neither acked nor retried is a retry, as in the memory queue: at least
130
+ * once means an unhandled message is delivered again, never lost. A consumer
131
+ * that throws settles nothing, and its messages come back when their lease
132
+ * runs out, as they would after a crash.
133
+ */
134
+ async drain(consumer, batchSize = DEFAULT_BATCH_SIZE) {
135
+ await this.#drain(consumer, batchSize);
136
+ }
137
+ /**
138
+ * `drain`, returning how many messages it delivered, for `run`. With
139
+ * `onConsumerError`, a consumer that throws is reported there instead of
140
+ * rethrown, and its messages are still left to their lease.
141
+ */
142
+ async #drain(consumer, batchSize = DEFAULT_BATCH_SIZE, onConsumerError) {
143
+ const now = this.o.clock.now();
144
+ const leaseEnds = plusSeconds(now, this.#leaseSeconds);
145
+ const { rows } = await this.#call('drain', async () => {
146
+ await this.o.pool.query(Q.bury, [this.o.name, now, this.#maxAttempts]);
147
+ return this.o.pool.query(Q.claim, [
148
+ this.o.name,
149
+ now,
150
+ Math.ceil(leaseEnds),
151
+ batchSize,
152
+ ]);
153
+ });
154
+ if (rows.length === 0) {
155
+ return 0;
156
+ }
157
+ const messages = rows.map((r) => toMessage(r));
158
+ const acked = new Set();
159
+ const retried = new Map();
160
+ try {
161
+ await consumer({
162
+ messages,
163
+ ack: (id) => {
164
+ acked.add(id);
165
+ retried.delete(id);
166
+ },
167
+ retry: (id, options) => {
168
+ retried.set(id, this.#checkedDelay(options?.delaySeconds));
169
+ acked.delete(id);
170
+ },
171
+ });
172
+ }
173
+ catch (error) {
174
+ if (onConsumerError === undefined) {
175
+ throw error;
176
+ }
177
+ onConsumerError(error, messages.map((m) => m.id));
178
+ return messages.length;
179
+ }
180
+ await this.#settle(messages, acked, retried);
181
+ return messages.length;
182
+ }
183
+ /**
184
+ * The long-running consumer for a Node worker: drains until `signal` is
185
+ * aborted, waiting `idleMs` after an empty claim. Wire the signal to
186
+ * SIGTERM. A batch in hand is settled before the loop returns, and messages
187
+ * claimed but not settled are left to their lease.
188
+ *
189
+ * A consumer that throws is logged with its message ids, and the loop goes
190
+ * on: those messages come back when their lease runs out. A retryable fault
191
+ * in the database is logged and waited out, doubling from `idleMs` up to 30
192
+ * seconds. Any other fault, such as a missing table, ends the loop, so the
193
+ * worker fails where someone will see it.
194
+ */
195
+ async run(consumer, options) {
196
+ const { signal, logger } = options;
197
+ const idleMs = options.idleMs ?? DEFAULT_IDLE_MS;
198
+ // The wait ends early on abort. Its AbortError is the stop, not a fault.
199
+ const wait = async (ms) => sleep(ms, undefined, { signal }).catch(() => { });
200
+ let faults = 0;
201
+ while (!signal.aborted) {
202
+ let delivered;
203
+ try {
204
+ delivered = await this.#drain(consumer, options.batchSize, (error, ids) => {
205
+ logger.error('queue consumer failed', {
206
+ queue: this.o.name,
207
+ ids: ids.join(','),
208
+ error: String(error),
209
+ });
210
+ });
211
+ faults = 0;
212
+ }
213
+ catch (error) {
214
+ if (!(error instanceof ToolFault) || !error.retryable) {
215
+ throw error;
216
+ }
217
+ faults += 1;
218
+ const backoffMs = Math.min(idleMs * 2 ** faults, MAX_BACKOFF_MS);
219
+ logger.warn('queue fault, retrying', {
220
+ queue: this.o.name,
221
+ error: String(error),
222
+ backoffMs,
223
+ });
224
+ await wait(backoffMs);
225
+ continue;
226
+ }
227
+ if (delivered === 0) {
228
+ await wait(idleMs);
229
+ }
230
+ }
231
+ }
232
+ async pendingCount() {
233
+ return this.#count('pendingCount', Q.pending);
234
+ }
235
+ async deadCount() {
236
+ return this.#count('deadCount', Q.deadCount);
237
+ }
238
+ /** The newest dead letters first, for an operator to read. */
239
+ async deadLetters(limit = 100) {
240
+ const { rows } = await this.#call('deadLetters', async () => this.o.pool.query(Q.deadLetters, [this.o.name, limit]));
241
+ return rows.map((r) => toMessage(r));
242
+ }
243
+ /**
244
+ * Moves a dead letter back to the queue, visible now, with its attempt
245
+ * count reset. False when there is no such dead letter.
246
+ */
247
+ async replay(id) {
248
+ const { rowCount } = await this.#call('replay', async () => this.o.pool.query(Q.replay, [this.o.name, id, this.o.clock.now()]));
249
+ return rowCount === 1;
250
+ }
251
+ async #send(operation, bodies, options) {
252
+ const delay = this.#checkedDelay(options?.delaySeconds);
253
+ if (bodies.length === 0) {
254
+ return [];
255
+ }
256
+ const json = bodies.map((b) => {
257
+ const text = JSON.stringify(b);
258
+ // The adapter enforces its own manifest. Postgres would take far more.
259
+ const bytes = Buffer.byteLength(text);
260
+ if (bytes > this.o.maxBytes) {
261
+ throw new LimitExceeded(TOOL, `body of ${bytes} bytes exceeds messageMaxBytes ${this.o.maxBytes}`);
262
+ }
263
+ return text;
264
+ });
265
+ const ids = bodies.map(() => randomUUID());
266
+ const now = this.o.clock.now();
267
+ await this.#call(operation, async () => this.o.pool.query(Q.send, [
268
+ this.o.name,
269
+ JSON.stringify(this.o.identity),
270
+ now,
271
+ Math.ceil(plusSeconds(now, delay)),
272
+ ids,
273
+ json,
274
+ ]));
275
+ return ids;
276
+ }
277
+ async #settle(messages, acked, retried) {
278
+ const now = this.o.clock.now();
279
+ const again = messages.filter((m) => !acked.has(m.id));
280
+ const ids = again.map((m) => m.id);
281
+ const attempts = again.map((m) => m.attempt);
282
+ await this.#call('drain', async () => withClient(this.o.pool, async (client) => {
283
+ try {
284
+ await client.query('BEGIN');
285
+ if (acked.size > 0) {
286
+ await client.query(Q.ack, [[...acked]]);
287
+ }
288
+ if (again.length > 0) {
289
+ await client.query(Q.exhaust, [
290
+ ids,
291
+ attempts,
292
+ this.#maxAttempts,
293
+ now,
294
+ ]);
295
+ await client.query(Q.retry, [
296
+ ids,
297
+ attempts,
298
+ again.map((m) => Math.ceil(plusSeconds(now, retried.get(m.id) ?? 0))),
299
+ ]);
300
+ }
301
+ await client.query('COMMIT');
302
+ }
303
+ catch (error) {
304
+ await client.query('ROLLBACK').catch(() => { });
305
+ throw error;
306
+ }
307
+ }));
308
+ }
309
+ #checkedDelay(delaySeconds) {
310
+ const delay = delaySeconds ?? 0;
311
+ // Before the ceiling check, which cannot catch it: NaN > maxDelaySeconds
312
+ // is false, so a NaN delay would pass and the message would never be
313
+ // visible.
314
+ checkDuration(TOOL, 'delaySeconds', delay);
315
+ if (delay > this.o.maxDelaySeconds) {
316
+ throw new LimitExceeded(TOOL, `delaySeconds ${delay} exceeds queueDelayMaxSeconds ${this.o.maxDelaySeconds}`);
317
+ }
318
+ return delay;
319
+ }
320
+ async #count(operation, sql) {
321
+ const { rows } = await this.#call(operation, async () => this.o.pool.query(sql, [this.o.name]));
322
+ // COUNT(*) is a BIGINT, which arrives as a string.
323
+ return Number(rows[0]?.n ?? 0);
324
+ }
325
+ async #call(operation, f) {
326
+ try {
327
+ return await f();
328
+ }
329
+ catch (e) {
330
+ throw toFault(TOOL, operation, e);
331
+ }
332
+ }
333
+ }
@@ -0,0 +1,18 @@
1
+ import type pg from 'pg';
2
+ import type { BlobStore, Clock } from '../../contracts/index.js';
3
+ import { type SweepOptions } from '../retention.js';
4
+ export { DEFAULT_RETENTION_SECONDS, type SweepOptions } from '../retention.js';
5
+ export type PostgresSweepDeps = {
6
+ /** The app's pool. docs/decisions/0007. */
7
+ readonly pool: pg.Pool;
8
+ readonly clock: Clock;
9
+ };
10
+ /** Deletes one batch of ledger claims whose lease ended `olderThanSeconds` ago. */
11
+ export declare function sweepLedger(deps: PostgresSweepDeps, options?: SweepOptions): Promise<number>;
12
+ /**
13
+ * Deletes one batch of webhook receipts past retention, and their raw bodies,
14
+ * bodies first. Returns how many deliveries it deleted.
15
+ */
16
+ export declare function sweepWebhookReceipts(deps: PostgresSweepDeps & {
17
+ readonly blobStore: BlobStore;
18
+ }, options?: SweepOptions): Promise<number>;
@@ -0,0 +1,104 @@
1
+ import { sweepBounds } from '../retention.js';
2
+ import { toFault } from './faults.js';
3
+ import { withClient } from './with-client.js';
4
+ export { DEFAULT_RETENTION_SECONDS } from '../retention.js';
5
+ /**
6
+ * The twin of the D1 sweep in ../cloudflare/retention.ts, which says why. The
7
+ * outer `expires_at < $1` is what Postgres re-checks on a row a concurrent
8
+ * claim just renewed; the subquery's rows come from the statement's snapshot.
9
+ * Without it the sweep waits on that claim, then deletes its live lease.
10
+ */
11
+ const SWEEP_LEDGER = `
12
+ DELETE FROM ledger_claims WHERE expires_at < $1 AND key IN (
13
+ SELECT key FROM ledger_claims WHERE expires_at < $1
14
+ ORDER BY expires_at LIMIT $2
15
+ )
16
+ `;
17
+ const SWEPT_DELIVERIES = `
18
+ SELECT delivery_id, body_key FROM webhook_deliveries d
19
+ WHERE received_at < $1 AND NOT EXISTS (
20
+ SELECT 1 FROM webhook_tasks t
21
+ WHERE t.delivery_id = d.delivery_id AND t.state NOT IN ('done', 'dead')
22
+ )
23
+ ORDER BY received_at LIMIT $2
24
+ `;
25
+ /**
26
+ * Run in one READ COMMITTED transaction, in this order. A replay may move a
27
+ * task dead → replayed while the bodies are deleted; its rows must then stay,
28
+ * so its retry fails visibly. One statement cannot promise that: its CTEs all
29
+ * read the snapshot it started with. So the tasks are locked first, which makes
30
+ * a concurrent move wait or be seen, and each delete after it is a new
31
+ * statement that reads every move committed before the lock.
32
+ */
33
+ const LOCK_TASKS = `
34
+ SELECT 1 FROM webhook_tasks WHERE delivery_id = ANY($1::text[]) FOR UPDATE
35
+ `;
36
+ const DELETE_TASKS = `
37
+ DELETE FROM webhook_tasks
38
+ WHERE delivery_id = ANY($1::text[])
39
+ AND NOT EXISTS (
40
+ SELECT 1 FROM webhook_tasks k
41
+ WHERE k.delivery_id = webhook_tasks.delivery_id
42
+ AND k.state NOT IN ('done', 'dead')
43
+ )
44
+ `;
45
+ // After DELETE_TASKS, so a delivery that kept a task keeps its row.
46
+ const DELETE_DELIVERIES = `
47
+ DELETE FROM webhook_deliveries
48
+ WHERE delivery_id = ANY($1::text[])
49
+ AND NOT EXISTS (
50
+ SELECT 1 FROM webhook_tasks t
51
+ WHERE t.delivery_id = webhook_deliveries.delivery_id
52
+ )
53
+ `;
54
+ /** Deletes one batch of ledger claims whose lease ended `olderThanSeconds` ago. */
55
+ export async function sweepLedger(deps, options = {}) {
56
+ const { cutoff, limit } = sweepBounds('ledger', deps.clock, options, 1_000);
57
+ try {
58
+ const result = await deps.pool.query(SWEEP_LEDGER, [cutoff, limit]);
59
+ return result.rowCount ?? 0;
60
+ }
61
+ catch (e) {
62
+ throw toFault('ledger', 'sweepLedger', e);
63
+ }
64
+ }
65
+ /**
66
+ * Deletes one batch of webhook receipts past retention, and their raw bodies,
67
+ * bodies first. Returns how many deliveries it deleted.
68
+ */
69
+ export async function sweepWebhookReceipts(deps, options = {}) {
70
+ const { cutoff, limit } = sweepBounds('journal', deps.clock, options, 100);
71
+ let rows;
72
+ try {
73
+ ;
74
+ ({ rows } = await deps.pool.query(SWEPT_DELIVERIES, [cutoff, limit]));
75
+ }
76
+ catch (e) {
77
+ throw toFault('journal', 'sweepWebhookReceipts', e);
78
+ }
79
+ if (rows.length === 0) {
80
+ return 0;
81
+ }
82
+ await Promise.all(rows.map(async (r) => deps.blobStore.delete(r.body_key)));
83
+ const ids = [rows.map((r) => r.delivery_id)];
84
+ try {
85
+ await withClient(deps.pool, async (client) => {
86
+ try {
87
+ // Pinned, since the order above relies on it whatever the app's default.
88
+ await client.query('BEGIN ISOLATION LEVEL READ COMMITTED');
89
+ await client.query(LOCK_TASKS, ids);
90
+ await client.query(DELETE_TASKS, ids);
91
+ await client.query(DELETE_DELIVERIES, ids);
92
+ await client.query('COMMIT');
93
+ }
94
+ catch (error) {
95
+ await client.query('ROLLBACK').catch(() => { });
96
+ throw error;
97
+ }
98
+ });
99
+ }
100
+ catch (e) {
101
+ throw toFault('journal', 'sweepWebhookReceipts', e);
102
+ }
103
+ return rows.length;
104
+ }
@@ -0,0 +1,20 @@
1
+ import type { Session } from '@shopify/shopify-api';
2
+ import type pg from 'pg';
3
+ import type { SessionStorage } from '../../contracts/index.js';
4
+ export type PostgresSessionStorageOptions = {
5
+ /** The app's pool. The storage never opens its own. docs/decisions/0007. */
6
+ readonly pool: pg.Pool;
7
+ /** The raw secret, base64 decoding to 32 bytes. docs/decisions/0005. */
8
+ readonly key: string;
9
+ };
10
+ export declare class PostgresSessionStorage implements SessionStorage {
11
+ #private;
12
+ private readonly o;
13
+ constructor(o: PostgresSessionStorageOptions);
14
+ storeSession(session: Session): Promise<boolean>;
15
+ loadSession(id: string): Promise<Session | undefined>;
16
+ /** True even when nothing was stored, as Shopify's own storages answer. */
17
+ deleteSession(id: string): Promise<boolean>;
18
+ deleteSessions(ids: string[]): Promise<boolean>;
19
+ findSessionsByShop(shop: string): Promise<Session[]>;
20
+ }