@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,102 @@
1
+ import { LimitExceeded, checkDuration, fromEpochMs, } from '../../contracts/index.js';
2
+ export class LocalQueue {
3
+ o;
4
+ #pending = [];
5
+ #dead = [];
6
+ #seq = 0;
7
+ constructor(o) {
8
+ this.o = o;
9
+ }
10
+ async send(body, options) {
11
+ const delay = options?.delaySeconds ?? 0;
12
+ // Before the ceiling check, which cannot catch it: NaN > maxDelaySeconds is
13
+ // false, so a NaN delay would pass and the message would never be visible.
14
+ checkDuration('queue', 'delaySeconds', delay);
15
+ // The ADAPTER enforces its own manifest. Never the caller.
16
+ if (delay > this.o.maxDelaySeconds) {
17
+ throw new LimitExceeded('queue', `delaySeconds ${delay} exceeds queueDelayMaxSeconds ${this.o.maxDelaySeconds}`);
18
+ }
19
+ // A Map has no size limit, so this one is enforced because the manifest
20
+ // DECLARES it. An adapter that declares a ceiling and does not apply it
21
+ // lets a body through here that its real counterpart would refuse, which
22
+ // makes the memory adapter useless as the place a payload gets sized.
23
+ const bytes = new TextEncoder().encode(JSON.stringify(body)).byteLength;
24
+ if (bytes > this.o.maxBytes) {
25
+ throw new LimitExceeded('queue', `body of ${bytes} bytes exceeds messageMaxBytes ${this.o.maxBytes}`);
26
+ }
27
+ const id = `local-${++this.#seq}`;
28
+ this.#pending.push({
29
+ id,
30
+ body,
31
+ visibleAt: fromEpochMs(this.o.clock.now() + delay * 1000),
32
+ attempt: 0,
33
+ });
34
+ return id;
35
+ }
36
+ async sendBatch(bodies, options) {
37
+ const ids = [];
38
+ for (const b of bodies) {
39
+ ids.push(await this.send(b, options));
40
+ }
41
+ return ids;
42
+ }
43
+ /** Test and dev only. Deliberately NOT on the Queue contract. */
44
+ async drain(consumer, batchSize = 10) {
45
+ const now = this.o.clock.now();
46
+ const due = this.#pending
47
+ .filter((m) => m.visibleAt <= now)
48
+ .slice(0, batchSize);
49
+ if (due.length === 0) {
50
+ return;
51
+ }
52
+ const acked = new Set();
53
+ const retried = new Map();
54
+ const messages = due.map((m) => ({
55
+ id: m.id,
56
+ body: m.body,
57
+ attempt: m.attempt + 1,
58
+ enqueuedAt: new Date(m.visibleAt).toISOString(),
59
+ identity: this.o.identity,
60
+ }));
61
+ const batch = {
62
+ messages,
63
+ ack: (id) => {
64
+ acked.add(id);
65
+ },
66
+ retry: (id, opts) => {
67
+ retried.set(id, opts?.delaySeconds ?? 0);
68
+ },
69
+ };
70
+ await consumer(batch);
71
+ for (const m of due) {
72
+ if (acked.has(m.id)) {
73
+ this.#remove(m);
74
+ continue;
75
+ }
76
+ // Neither acked nor retried counts as retried: at-least-once means the default
77
+ // on an unhandled message is redelivery, never loss.
78
+ m.attempt += 1;
79
+ if (m.attempt >= this.o.maxAttempts) {
80
+ this.#remove(m);
81
+ this.#dead.push(m);
82
+ continue;
83
+ }
84
+ m.visibleAt = fromEpochMs(this.o.clock.now() + (retried.get(m.id) ?? 0) * 1000);
85
+ }
86
+ }
87
+ #remove(m) {
88
+ const i = this.#pending.indexOf(m);
89
+ if (i >= 0) {
90
+ this.#pending.splice(i, 1);
91
+ }
92
+ }
93
+ pendingCount() {
94
+ return this.#pending.length;
95
+ }
96
+ deadCount() {
97
+ return this.#dead.length;
98
+ }
99
+ dead() {
100
+ return this.#dead.map((m) => m.body);
101
+ }
102
+ }
@@ -0,0 +1,20 @@
1
+ import type { Session } from '@shopify/shopify-api';
2
+ import type { SessionStorage } from '../../contracts/index.js';
3
+ /**
4
+ * No encryption. There is no "raw column" here for an attacker or a test to
5
+ * read, so the encryption-at-rest promise is this library's to keep only
6
+ * where a row actually exists on disk — the Cloudflare adapter. The
7
+ * conformance suite in src/contracts/conformance/session-storage.ts covers
8
+ * everything both adapters owe callers; the encryption assertion is
9
+ * necessarily adapter-specific and lives in
10
+ * src/adapters/cloudflare/session-storage.spec.ts.
11
+ */
12
+ export declare class MemorySessionStorage implements SessionStorage {
13
+ #private;
14
+ storeSession(session: Session): Promise<boolean>;
15
+ loadSession(id: string): Promise<Session | undefined>;
16
+ /** Matches @shopify/shopify-app-session-storage-memory: always true. */
17
+ deleteSession(id: string): Promise<boolean>;
18
+ deleteSessions(ids: string[]): Promise<boolean>;
19
+ findSessionsByShop(shop: string): Promise<Session[]>;
20
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * No encryption. There is no "raw column" here for an attacker or a test to
3
+ * read, so the encryption-at-rest promise is this library's to keep only
4
+ * where a row actually exists on disk — the Cloudflare adapter. The
5
+ * conformance suite in src/contracts/conformance/session-storage.ts covers
6
+ * everything both adapters owe callers; the encryption assertion is
7
+ * necessarily adapter-specific and lives in
8
+ * src/adapters/cloudflare/session-storage.spec.ts.
9
+ */
10
+ export class MemorySessionStorage {
11
+ #sessions = new Map();
12
+ async storeSession(session) {
13
+ this.#sessions.set(session.id, session);
14
+ return true;
15
+ }
16
+ async loadSession(id) {
17
+ return this.#sessions.get(id);
18
+ }
19
+ /** Matches @shopify/shopify-app-session-storage-memory: always true. */
20
+ async deleteSession(id) {
21
+ this.#sessions.delete(id);
22
+ return true;
23
+ }
24
+ async deleteSessions(ids) {
25
+ for (const id of ids) {
26
+ this.#sessions.delete(id);
27
+ }
28
+ return true;
29
+ }
30
+ async findSessionsByShop(shop) {
31
+ return [...this.#sessions.values()].filter((s) => s.shop === shop);
32
+ }
33
+ }
@@ -0,0 +1,8 @@
1
+ import type { Clock, DeploymentIdentity, Toolkit } from '../../contracts/index.js';
2
+ export type MemoryToolkitOptions = {
3
+ readonly identity: DeploymentIdentity;
4
+ readonly correlationId?: string;
5
+ readonly clock?: Clock;
6
+ readonly maxQueueAttempts?: number;
7
+ };
8
+ export declare function createInMemoryToolkit<QueueBody = unknown, WebhookBody = unknown>(o: MemoryToolkitOptions): Toolkit<QueueBody, WebhookBody>;
@@ -0,0 +1,31 @@
1
+ import { systemClock } from '../system-clock.js';
2
+ import { MemoryBlobStore } from './blob-store.js';
3
+ import { MemoryCache } from './cache.js';
4
+ import { MemoryJournal } from './journal.js';
5
+ import { LocalLedger } from './ledger.js';
6
+ import { MemoryLogger } from './logger.js';
7
+ import { LOCAL_MANIFEST } from './manifest.js';
8
+ import { LocalQueue } from './queue.js';
9
+ export function createInMemoryToolkit(o) {
10
+ const clock = o.clock ?? systemClock();
11
+ const queueOptions = {
12
+ clock,
13
+ identity: o.identity,
14
+ maxDelaySeconds: LOCAL_MANIFEST.queueDelayMaxSeconds,
15
+ maxBytes: LOCAL_MANIFEST.messageMaxBytes,
16
+ maxAttempts: o.maxQueueAttempts ?? 5,
17
+ };
18
+ return {
19
+ blobStore: new MemoryBlobStore(),
20
+ cache: new MemoryCache({
21
+ clock,
22
+ minTtlSeconds: LOCAL_MANIFEST.cacheMinTtlSeconds,
23
+ }),
24
+ journal: new MemoryJournal(),
25
+ ledger: new LocalLedger(clock),
26
+ logger: new MemoryLogger(o.identity, o.correlationId ?? crypto.randomUUID()),
27
+ queue: new LocalQueue(queueOptions),
28
+ webhookQueue: new LocalQueue(queueOptions),
29
+ clock,
30
+ };
31
+ }
@@ -0,0 +1,17 @@
1
+ import type pg from 'pg';
2
+ import type { Cache, CacheKey, Clock } from '../../contracts/index.js';
3
+ export type PostgresCacheOptions = {
4
+ /** The app's pool. The cache never opens its own. docs/decisions/0007. */
5
+ readonly pool: pg.Pool;
6
+ readonly clock: Clock;
7
+ /** Postgres has no floor of its own. The manifest's value is passed in. */
8
+ readonly minTtlSeconds: number;
9
+ };
10
+ export declare class PostgresCache implements Cache {
11
+ #private;
12
+ private readonly o;
13
+ constructor(o: PostgresCacheOptions);
14
+ get(key: CacheKey): Promise<string | undefined>;
15
+ put(key: CacheKey, value: string, ttlSeconds: number): Promise<void>;
16
+ delete(key: CacheKey): Promise<void>;
17
+ }
@@ -0,0 +1,69 @@
1
+ import { LimitExceeded, checkDuration, plusSeconds, } from '../../contracts/index.js';
2
+ import { toFault } from './faults.js';
3
+ const TOOL = 'cache';
4
+ /**
5
+ * How many expired rows one write removes. Every row comes from a write, and
6
+ * each write clears up to this many, so expired rows are cleared far faster
7
+ * than they are made while the cache is in use. When writes stop, what is left
8
+ * stays until the next write, unread: `get` never returns an expired row.
9
+ */
10
+ const SWEEP_BATCH = 100;
11
+ /**
12
+ * The expiry is decided against the injected Clock, never `now()`, so the
13
+ * suite can advance a test clock. Inclusive: a row at `expires_at` is a miss.
14
+ */
15
+ const GET = `SELECT value FROM cache_entries WHERE key = $1 AND expires_at > $2`;
16
+ /**
17
+ * The upsert, and in the same statement a sweep of up to SWEEP_BATCH expired
18
+ * rows. SKIP LOCKED leaves rows another write is sweeping to it, so concurrent
19
+ * writes never queue on each other. The key being written is left out of the
20
+ * sweep, because the INSERT may update that very row.
21
+ */
22
+ const PUT = `
23
+ WITH swept AS (
24
+ DELETE FROM cache_entries WHERE key IN (
25
+ SELECT key FROM cache_entries
26
+ WHERE expires_at <= $4 AND key <> $1
27
+ LIMIT ${SWEEP_BATCH}
28
+ FOR UPDATE SKIP LOCKED
29
+ )
30
+ )
31
+ INSERT INTO cache_entries (key, value, expires_at)
32
+ VALUES ($1, $2, $3)
33
+ ON CONFLICT (key) DO UPDATE SET value = $2, expires_at = $3
34
+ `;
35
+ const DELETE = `DELETE FROM cache_entries WHERE key = $1`;
36
+ export class PostgresCache {
37
+ o;
38
+ constructor(o) {
39
+ this.o = o;
40
+ }
41
+ async get(key) {
42
+ const { rows } = await this.#call('get', async () => this.o.pool.query(GET, [key, this.o.clock.now()]));
43
+ return rows[0]?.value;
44
+ }
45
+ async put(key, value, ttlSeconds) {
46
+ // Before the manifest check, which cannot catch it: NaN < minTtlSeconds is
47
+ // false, so a NaN ttl would pass and the value would never expire.
48
+ checkDuration(TOOL, 'ttlSeconds', ttlSeconds);
49
+ // The ADAPTER enforces its own manifest. Never the caller.
50
+ if (ttlSeconds < this.o.minTtlSeconds) {
51
+ throw new LimitExceeded(TOOL, `ttlSeconds ${ttlSeconds} is below cacheMinTtlSeconds ${this.o.minTtlSeconds}`);
52
+ }
53
+ const now = this.o.clock.now();
54
+ // A fractional ttl gives a fractional instant, which BIGINT refuses.
55
+ const expiresAt = Math.ceil(plusSeconds(now, ttlSeconds));
56
+ await this.#call('put', async () => this.o.pool.query(PUT, [key, value, expiresAt, now]));
57
+ }
58
+ async delete(key) {
59
+ await this.#call('delete', async () => this.o.pool.query(DELETE, [key]));
60
+ }
61
+ async #call(operation, f) {
62
+ try {
63
+ return await f();
64
+ }
65
+ catch (e) {
66
+ throw toFault(TOOL, operation, e);
67
+ }
68
+ }
69
+ }
@@ -0,0 +1,27 @@
1
+ export type PostgresToolkitConfig = {
2
+ /** For the app's own `pg.Pool`. The toolkit never opens one. docs/decisions/0007. */
3
+ readonly databaseUrl: string;
4
+ readonly s3: {
5
+ /** Absent for AWS, which the SDK finds from the region. */
6
+ readonly endpoint?: string;
7
+ readonly region: string;
8
+ readonly bucket: string;
9
+ /**
10
+ * From `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY`, set as a pair. Set
11
+ * them for MinIO, R2 and GCS (HMAC keys). Leave both unset on AWS, so the
12
+ * SDK's default chain finds the task, pod or instance role.
13
+ */
14
+ readonly credentials?: {
15
+ readonly accessKeyId: string;
16
+ readonly secretAccessKey: string;
17
+ };
18
+ /** MinIO and most self-hosted stores serve a bucket as a path. */
19
+ readonly forcePathStyle: boolean;
20
+ };
21
+ };
22
+ /**
23
+ * Reads and checks every setting once, at start, so a bad deploy fails before
24
+ * it takes traffic instead of on its first request. Every problem is reported
25
+ * together, not the first one found.
26
+ */
27
+ export declare function readPostgresToolkitConfig(env: Readonly<Record<string, string | undefined>>): PostgresToolkitConfig;
@@ -0,0 +1,45 @@
1
+ import { Misconfigured } from '../../contracts/index.js';
2
+ const REQUIRED = ['DATABASE_URL', 'S3_REGION', 'S3_BUCKET'];
3
+ const KEY_PAIR = ['S3_ACCESS_KEY_ID', 'S3_SECRET_ACCESS_KEY'];
4
+ const isUrl = (value, protocols) => URL.canParse(value) && protocols.includes(new URL(value).protocol);
5
+ /**
6
+ * Reads and checks every setting once, at start, so a bad deploy fails before
7
+ * it takes traffic instead of on its first request. Every problem is reported
8
+ * together, not the first one found.
9
+ */
10
+ export function readPostgresToolkitConfig(env) {
11
+ const value = (name) => env[name]?.trim() ?? '';
12
+ const problems = REQUIRED.filter((name) => value(name) === '').map((name) => `${name} is not set`);
13
+ const databaseUrl = value('DATABASE_URL');
14
+ const endpoint = value('S3_ENDPOINT');
15
+ const pathStyle = value('S3_FORCE_PATH_STYLE');
16
+ const accessKeyId = value('S3_ACCESS_KEY_ID');
17
+ const secretAccessKey = value('S3_SECRET_ACCESS_KEY');
18
+ const keys = accessKeyId !== '' || secretAccessKey !== '';
19
+ if (keys) {
20
+ problems.push(...KEY_PAIR.filter((name) => value(name) === '').map((name) => `${name} is not set, though its pair is`));
21
+ }
22
+ if (databaseUrl !== '' && !isUrl(databaseUrl, ['postgres:', 'postgresql:'])) {
23
+ problems.push('DATABASE_URL is not a postgres:// URL');
24
+ }
25
+ if (endpoint !== '' && !isUrl(endpoint, ['http:', 'https:'])) {
26
+ problems.push('S3_ENDPOINT is not an http(s):// URL');
27
+ }
28
+ if (!['', 'true', 'false'].includes(pathStyle)) {
29
+ problems.push('S3_FORCE_PATH_STYLE must be true or false');
30
+ }
31
+ if (problems.length > 0) {
32
+ // Names only, never values: a secret must not reach a log line.
33
+ throw new Misconfigured('config', problems.join('; '));
34
+ }
35
+ return {
36
+ databaseUrl,
37
+ s3: {
38
+ ...(endpoint === '' ? {} : { endpoint }),
39
+ region: value('S3_REGION'),
40
+ bucket: value('S3_BUCKET'),
41
+ ...(keys ? { credentials: { accessKeyId, secretAccessKey } } : {}),
42
+ forcePathStyle: pathStyle === 'true',
43
+ },
44
+ };
45
+ }
@@ -0,0 +1,14 @@
1
+ import { type ToolFault } from '../../contracts/index.js';
2
+ /**
3
+ * 40001, serialization_failure. Under REPEATABLE READ or SERIALIZABLE, a write
4
+ * that meets a row committed after its snapshot fails with this, where READ
5
+ * COMMITTED would have seen the row.
6
+ */
7
+ export declare const isSerializationFailure: (e: unknown) => boolean;
8
+ /**
9
+ * Unknown failures, including a refused connection, which carries a Node
10
+ * error code rather than a SQLSTATE, are Unavailable and so retryable. A
11
+ * retryable answer to something permanent costs a few attempts; a permanent
12
+ * answer to something transient loses the work.
13
+ */
14
+ export declare function toFault(tool: string, operation: string, e: unknown): ToolFault;
@@ -0,0 +1,47 @@
1
+ import { LimitExceeded, Misconfigured, Throttled, Unavailable, } from '../../contracts/index.js';
2
+ /**
3
+ * Postgres reports a failure with a SQLSTATE `code`, whose first two
4
+ * characters are its class. That code is read here, in one place, and the
5
+ * vendor error is kept as `cause`, never in the caller's message.
6
+ *
7
+ * https://www.postgresql.org/docs/current/errcodes-appendix.html
8
+ */
9
+ const MISCONFIGURED = new Set([
10
+ '28', // invalid authorization: wrong user or password
11
+ '3D', // invalid catalog name: no such database
12
+ '3F', // invalid schema name
13
+ '42', // syntax error or access rule violation: no such table, no privilege
14
+ ]);
15
+ const codeOf = (e) => {
16
+ const code = e?.code;
17
+ return typeof code === 'string' && code.length === 5 ? code : undefined;
18
+ };
19
+ /**
20
+ * 40001, serialization_failure. Under REPEATABLE READ or SERIALIZABLE, a write
21
+ * that meets a row committed after its snapshot fails with this, where READ
22
+ * COMMITTED would have seen the row.
23
+ */
24
+ export const isSerializationFailure = (e) => codeOf(e) === '40001';
25
+ /**
26
+ * Unknown failures, including a refused connection, which carries a Node
27
+ * error code rather than a SQLSTATE, are Unavailable and so retryable. A
28
+ * retryable answer to something permanent costs a few attempts; a permanent
29
+ * answer to something transient loses the work.
30
+ */
31
+ export function toFault(tool, operation, e) {
32
+ const sqlClass = codeOf(e)?.slice(0, 2);
33
+ const where = `${operation} failed`;
34
+ const options = { cause: e };
35
+ // Class 53, insufficient resources: too many connections, out of memory.
36
+ if (sqlClass === '53') {
37
+ return new Throttled(tool, where, options);
38
+ }
39
+ if (sqlClass !== undefined && MISCONFIGURED.has(sqlClass)) {
40
+ return new Misconfigured(tool, where, options);
41
+ }
42
+ // Class 22, data exception: a value out of range or too long.
43
+ if (sqlClass === '22') {
44
+ return new LimitExceeded(tool, where, options);
45
+ }
46
+ return new Unavailable(tool, where, options);
47
+ }
@@ -0,0 +1,12 @@
1
+ export * from './cache.js';
2
+ export * from './config.js';
3
+ export { toFault } from './faults.js';
4
+ export * from './journal.js';
5
+ export * from './ledger.js';
6
+ export * from './logger.js';
7
+ export * from './manifest.js';
8
+ export { applyMigrations, pendingMigrations } from './migrate.js';
9
+ export * from './queue.js';
10
+ export * from './retention.js';
11
+ export * from './session-storage.js';
12
+ export * from './toolkit.js';
@@ -0,0 +1,12 @@
1
+ export * from './cache.js';
2
+ export * from './config.js';
3
+ export { toFault } from './faults.js';
4
+ export * from './journal.js';
5
+ export * from './ledger.js';
6
+ export * from './logger.js';
7
+ export * from './manifest.js';
8
+ export { applyMigrations, pendingMigrations } from './migrate.js';
9
+ export * from './queue.js';
10
+ export * from './retention.js';
11
+ export * from './session-storage.js';
12
+ export * from './toolkit.js';
@@ -0,0 +1,83 @@
1
+ import type pg from 'pg';
2
+ import { type CallRow, type DeliveryRow, type Instant, type Journal, type Logger, type ReasonCount, type RunId, type RunRow, type StepRow, type TaskCursor, type TaskRow, type TaskState, type UnitKey, type UnitRow } from '../../contracts/index.js';
3
+ /**
4
+ * Every query this adapter can run, in one place. The D1 journal's queries
5
+ * with `$n` placeholders; its comments say why each one is shaped as it is.
6
+ *
7
+ * Which index serves which read, asserted by `journal.spec.ts` with EXPLAIN:
8
+ *
9
+ * recentRuns journal_runs_started_at
10
+ * unitsForRun journal_units_pkey
11
+ * unit journal_units_pkey, journal_steps_unit,
12
+ * journal_calls_pkey
13
+ * latestForUnit journal_units_unit_key
14
+ * failuresByReason journal_units_recorded_at
15
+ * delivery webhook_deliveries_pkey, webhook_tasks_pkey
16
+ * deadTasks webhook_tasks_state
17
+ * deadTasksByAction webhook_tasks_action_state
18
+ * stuckTasks webhook_tasks_state
19
+ */
20
+ declare const Q: {
21
+ readonly startRun: "\n INSERT INTO journal_runs\n (run_id, job, trigger, mode, started_at, identity)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (run_id) DO UPDATE SET\n job = $2, trigger = $3, mode = $4, started_at = $5, identity = $6\n ";
22
+ readonly finishRun: "UPDATE journal_runs SET ended_at = $2 WHERE run_id = $1";
23
+ readonly recordUnit: "\n INSERT INTO journal_units\n (run_id, unit_key, unit_type, recorded_at, outcome,\n reason_code, plan_hash, plan_ref, duration_ms, external_ids)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\n ON CONFLICT (run_id, unit_key) DO UPDATE SET\n unit_type = $3, recorded_at = $4, outcome = $5,\n reason_code = $6, plan_hash = $7, plan_ref = $8,\n duration_ms = $9, external_ids = $10\n ";
24
+ readonly clearCalls: "DELETE FROM journal_calls WHERE run_id = $1 AND unit_key = $2";
25
+ readonly recordCalls: "\n INSERT INTO journal_calls\n (run_id, unit_key, seq, system, operation,\n status, http_status, idempotency_key, duration_ms)\n SELECT c.run_id, c.unit_key, c.ord - 1, c.system, c.operation,\n c.status, c.http_status, c.idempotency_key, c.duration_ms\n FROM unnest(\n $1::text[], $2::text[], $3::text[], $4::text[], $5::text[],\n $6::integer[], $7::text[], $8::bigint[]\n ) WITH ORDINALITY\n AS c (run_id, unit_key, system, operation, status,\n http_status, idempotency_key, duration_ms, ord)\n ";
26
+ readonly recordStep: "\n INSERT INTO journal_steps\n (run_id, unit_key, step, attempt, outcome,\n reason_code, duration_ms, recorded_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\n ";
27
+ readonly unitsForRun: "\n SELECT * FROM journal_units\n WHERE run_id = $1 ORDER BY unit_key LIMIT $2\n ";
28
+ readonly unit: "SELECT * FROM journal_units WHERE run_id = $1 AND unit_key = $2";
29
+ readonly stepsForUnit: "\n SELECT * FROM journal_steps\n WHERE run_id = $1 AND unit_key = $2 ORDER BY recorded_at, seq\n ";
30
+ readonly callsForUnit: "\n SELECT * FROM journal_calls\n WHERE run_id = $1 AND unit_key = $2 ORDER BY seq\n ";
31
+ readonly latestForUnit: "\n SELECT * FROM journal_units\n WHERE unit_key = $1 ORDER BY recorded_at DESC LIMIT 1\n ";
32
+ readonly failuresByReason: "\n SELECT reason_code, COUNT(*) AS count\n FROM journal_units\n WHERE recorded_at >= $1\n AND reason_code IS NOT NULL\n AND outcome != 'written'\n GROUP BY reason_code\n ORDER BY count DESC, reason_code ASC\n ";
33
+ readonly recentRuns: "SELECT * FROM journal_runs ORDER BY started_at DESC LIMIT $1";
34
+ readonly recordDelivery: "\n WITH delivery AS (\n INSERT INTO webhook_deliveries\n (delivery_id, source, topic, shop, webhook_id, body_key, received_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n ON CONFLICT (delivery_id) DO NOTHING\n )\n INSERT INTO webhook_tasks (delivery_id, action, state, updated_at)\n SELECT $1, action, 'received', $7 FROM unnest($8::text[]) AS action\n ON CONFLICT (delivery_id, action) DO NOTHING\n ";
35
+ readonly moveTask: "\n UPDATE webhook_tasks SET state = $3, updated_at = $4, reason_code = $6\n WHERE delivery_id = $1 AND action = $2 AND state = ANY($5::text[])\n ";
36
+ readonly delivery: "SELECT * FROM webhook_deliveries WHERE delivery_id = $1";
37
+ readonly tasksForDelivery: "\n SELECT * FROM webhook_tasks WHERE delivery_id = $1 ORDER BY action\n ";
38
+ readonly deadTasks: "\n SELECT * FROM webhook_tasks\n WHERE state = 'dead' AND (updated_at, delivery_id, action) > ($1, $2, $3)\n ORDER BY updated_at, delivery_id, action LIMIT $4\n ";
39
+ readonly deadTasksByAction: "\n SELECT * FROM webhook_tasks\n WHERE action = $5 AND state = 'dead'\n AND (updated_at, delivery_id, action) > ($1, $2, $3)\n ORDER BY updated_at, delivery_id LIMIT $4\n ";
40
+ readonly stuckTasks: "\n SELECT * FROM webhook_tasks\n WHERE state IN ('received', 'processing') AND updated_at < $1\n ORDER BY updated_at, delivery_id, action LIMIT $2\n ";
41
+ };
42
+ export type PostgresJournalOptions = {
43
+ /** The app's pool. The journal never opens its own. docs/decisions/0007. */
44
+ readonly pool: pg.Pool;
45
+ /** Where a failed step-row write goes, because `recordStep` must not reject. */
46
+ readonly logger: Logger;
47
+ };
48
+ export declare class PostgresJournal implements Journal {
49
+ #private;
50
+ private readonly o;
51
+ constructor(o: PostgresJournalOptions);
52
+ startRun(row: RunRow): Promise<void>;
53
+ finishRun(runId: RunId, endedAt: Instant): Promise<void>;
54
+ /**
55
+ * One transaction, so a unit is never half recorded: the unit row, the
56
+ * clear of its previous calls, and all its calls in one INSERT.
57
+ */
58
+ recordUnit(unit: UnitRow, calls: readonly CallRow[]): Promise<void>;
59
+ /** Catches every failure and logs it, as the contract requires. */
60
+ recordStep(step: StepRow): Promise<void>;
61
+ unitsForRun(runId: RunId, limit?: number): Promise<readonly UnitRow[]>;
62
+ unit(runId: RunId, unitKey: UnitKey): Promise<{
63
+ unit: UnitRow;
64
+ steps: readonly StepRow[];
65
+ calls: readonly CallRow[];
66
+ } | undefined>;
67
+ latestForUnit(unitKey: UnitKey): Promise<UnitRow | undefined>;
68
+ failuresByReason(since: Instant): Promise<readonly ReasonCount[]>;
69
+ recentRuns(limit?: number): Promise<readonly RunRow[]>;
70
+ recordDelivery(delivery: DeliveryRow, actions: readonly string[]): Promise<void>;
71
+ moveTask(deliveryId: string, action: string, to: Exclude<TaskState, 'received'>, at: Instant, reasonCode?: string): Promise<boolean>;
72
+ delivery(deliveryId: string): Promise<{
73
+ delivery: DeliveryRow;
74
+ tasks: readonly TaskRow[];
75
+ } | undefined>;
76
+ deadTasks({ action, after, limit, }?: {
77
+ readonly action?: string;
78
+ readonly after?: TaskCursor;
79
+ readonly limit?: number;
80
+ }): Promise<readonly TaskRow[]>;
81
+ stuckTasks(before: Instant, limit?: number): Promise<readonly TaskRow[]>;
82
+ }
83
+ export { Q as JOURNAL_QUERIES };