@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,55 @@
1
+ import type { DeploymentIdentity } from './identity.js';
2
+ export type MessageId = string & {
3
+ readonly __messageId: unique symbol;
4
+ };
5
+ export type QueueMessage<T> = {
6
+ readonly id: MessageId;
7
+ readonly body: T;
8
+ /** 1 on first delivery. */
9
+ readonly attempt: number;
10
+ readonly enqueuedAt: string;
11
+ readonly identity: DeploymentIdentity;
12
+ };
13
+ export type SendOptions = {
14
+ /**
15
+ * Rejected — never clamped — above the adapter's declared
16
+ * queueDelayMaxSeconds.
17
+ *
18
+ * Must be a finite, non-negative number. Anything else — `NaN`, `Infinity`,
19
+ * a negative — is a caller bug rather than a target condition, and is
20
+ * rejected with a **TypeError, not a ToolFault**, so it escapes the retry
21
+ * envelope. A `NaN` delay would otherwise pass the ceiling check and produce
22
+ * a message that is never visible and therefore never delivered, with no
23
+ * error anywhere. A rejected send leaves no message behind.
24
+ */
25
+ readonly delaySeconds?: number;
26
+ };
27
+ export type RetryOptions = {
28
+ readonly delaySeconds?: number;
29
+ };
30
+ /**
31
+ * At-least-once delivery. MAY reorder.
32
+ * A caller that depends on delivery order is incorrect; the conformance suite
33
+ * asserts that reordering is permitted.
34
+ */
35
+ export interface Queue<T> {
36
+ send(body: T, options?: SendOptions): Promise<MessageId>;
37
+ sendBatch(bodies: readonly T[], options?: SendOptions): Promise<readonly MessageId[]>;
38
+ }
39
+ /**
40
+ * Acknowledgement is PER MESSAGE.
41
+ *
42
+ * There is deliberately no ackAll()/retryAll(). A batch of ten where the fourth fails
43
+ * must leave nine acknowledged and one retried; a convenience that makes the wrong
44
+ * thing easy does not belong on the interface.
45
+ *
46
+ * A message neither acked nor retried by the time the consumer returns is
47
+ * redelivered, on every adapter. On Cloudflare that holds only through
48
+ * `consumeQueueBatch`, because the platform acks it otherwise.
49
+ */
50
+ export interface QueueBatch<T> {
51
+ readonly messages: readonly QueueMessage<T>[];
52
+ ack(id: MessageId): void;
53
+ retry(id: MessageId, options?: RetryOptions): void;
54
+ }
55
+ export type QueueConsumer<T> = (batch: QueueBatch<T>) => Promise<void>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Shopify's own five-method interface, re-exported as a TYPE ONLY.
3
+ *
4
+ * This is the one named exception to "src/contracts/ imports nothing" —
5
+ * docs/decisions/0005 says why. `export type` plus this project's
6
+ * `verbatimModuleSyntax` means the compiler erases this line entirely; no
7
+ * value, no class and no vendor code crosses into the emitted output. The
8
+ * adapters that implement this (src/adapters/memory/session-storage.ts,
9
+ * src/adapters/cloudflare/session-storage.ts) import `Session` — the real
10
+ * class, at runtime — because they have to construct one. That import
11
+ * belongs to them, and does not belong here.
12
+ *
13
+ * eslint.config.js bans every other non-relative import under
14
+ * src/contracts/**, with this file and conformance/session-storage.ts as the
15
+ * two overrides, so the exception stays this narrow mechanically rather than
16
+ * by memory.
17
+ */
18
+ export type { SessionStorage } from '@shopify/shopify-app-session-storage';
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,21 @@
1
+ import type { BlobStore } from './blob-store.js';
2
+ import type { Cache } from './cache.js';
3
+ import type { Clock } from './instant.js';
4
+ import type { Journal } from './journal.js';
5
+ import type { Ledger } from './ledger.js';
6
+ import type { Logger } from './logger.js';
7
+ import type { Queue } from './queue.js';
8
+ export type Toolkit<QueueBody = unknown, WebhookBody = unknown> = {
9
+ readonly cache: Cache;
10
+ readonly blobStore: BlobStore;
11
+ readonly ledger: Ledger;
12
+ readonly journal: Journal;
13
+ readonly logger: Logger;
14
+ readonly clock: Clock;
15
+ readonly queue: Queue<QueueBody>;
16
+ /**
17
+ * Webhook pointers, on a queue of their own rather than `queue`, so that
18
+ * their retries and dead letters are not the app's. docs/decisions/0011.
19
+ */
20
+ readonly webhookQueue: Queue<WebhookBody>;
21
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,40 @@
1
+ import type { RunId, Toolkit, ToolManifest } from '../contracts/index.js';
2
+ export type ScheduledTask = {
3
+ /** Part of the Ledger key and the Journal's `job`. No ':'. */
4
+ readonly name: string;
5
+ readonly everySeconds: number;
6
+ /** `runId` is this run's Journal run, for a task that records its own units. */
7
+ readonly run: (context: {
8
+ readonly runId: RunId;
9
+ }) => Promise<void>;
10
+ };
11
+ /** Made only by `defineSchedule`, so every schedule has been checked. */
12
+ export type Schedule = {
13
+ readonly tasks: readonly ScheduledTask[];
14
+ readonly __schedule: true;
15
+ };
16
+ /** A toolkit has all four, so a toolkit can be passed as it is. */
17
+ export type ScheduleDeps = Pick<Toolkit, 'ledger' | 'journal' | 'clock' | 'logger'>;
18
+ export type TaskOutcome = 'ran' | 'failed' | 'skipped';
19
+ export type TaskResult = {
20
+ readonly name: string;
21
+ readonly outcome: TaskOutcome;
22
+ };
23
+ export declare function defineSchedule(manifest: Pick<ToolManifest, 'scheduleMinIntervalSeconds'>, tasks: readonly ScheduledTask[]): Schedule;
24
+ /**
25
+ * One tick. Each task runs at most once per slot, `floor(now / everySeconds)`,
26
+ * across every ticker, because the slot is claimed in the Ledger first. A slot
27
+ * the tickers missed is not run later. Tasks run in turn, and one that throws
28
+ * is journaled as failed without stopping the others.
29
+ */
30
+ export declare function runDueTasks(schedule: Schedule, deps: ScheduleDeps): Promise<readonly TaskResult[]>;
31
+ export type SchedulerOptions = {
32
+ readonly tickSeconds: number;
33
+ readonly signal: AbortSignal;
34
+ };
35
+ /**
36
+ * The Node target's ticker: tick, sleep `tickSeconds`, repeat, until `signal`
37
+ * aborts. Resolves once it has stopped. It reads no time itself; the slot comes
38
+ * from `deps.clock`. A tick longer than the shortest interval misses slots.
39
+ */
40
+ export declare function startScheduler(schedule: Schedule, deps: ScheduleDeps, { tickSeconds, signal }: SchedulerOptions): Promise<void>;
@@ -0,0 +1,135 @@
1
+ export function defineSchedule(manifest, tasks) {
2
+ const names = new Set();
3
+ for (const { name, everySeconds } of tasks) {
4
+ if (name.includes(':')) {
5
+ throw new TypeError(`task name must not contain ':': ${name}`);
6
+ }
7
+ if (names.has(name)) {
8
+ throw new TypeError(`duplicate task name: ${name}`);
9
+ }
10
+ names.add(name);
11
+ if (!Number.isInteger(everySeconds)) {
12
+ throw new RangeError(`${name}: everySeconds must be a whole number, not ${everySeconds}`);
13
+ }
14
+ if (everySeconds < manifest.scheduleMinIntervalSeconds) {
15
+ throw new RangeError(`${name}: everySeconds must be at least ${manifest.scheduleMinIntervalSeconds} on this target, not ${everySeconds}`);
16
+ }
17
+ }
18
+ return { tasks, __schedule: true };
19
+ }
20
+ /**
21
+ * One tick. Each task runs at most once per slot, `floor(now / everySeconds)`,
22
+ * across every ticker, because the slot is claimed in the Ledger first. A slot
23
+ * the tickers missed is not run later. Tasks run in turn, and one that throws
24
+ * is journaled as failed without stopping the others.
25
+ */
26
+ export async function runDueTasks(schedule, deps) {
27
+ const now = deps.clock.now();
28
+ const results = [];
29
+ for (const task of schedule.tasks) {
30
+ const slot = Math.floor(now / 1000 / task.everySeconds);
31
+ let outcome;
32
+ try {
33
+ outcome = await runSlot(task, slot, deps);
34
+ }
35
+ catch (error) {
36
+ // A Ledger or Journal fault. The tick goes on to the next task.
37
+ deps.logger.error('schedule: slot faulted', {
38
+ task: task.name,
39
+ slot,
40
+ error: String(error),
41
+ });
42
+ outcome = 'failed';
43
+ }
44
+ results.push({ name: task.name, outcome });
45
+ }
46
+ return results;
47
+ }
48
+ async function runSlot(task, slot, { ledger, journal, clock, logger }) {
49
+ const key = `schedule:${task.name}:${slot}`;
50
+ // A ticker that dies mid-run frees the slot for another once the lease ends.
51
+ const claim = await ledger.claim(key, task.everySeconds);
52
+ if (claim.status !== 'claimed') {
53
+ return 'skipped';
54
+ }
55
+ const runId = crypto.randomUUID();
56
+ const startedAt = clock.now();
57
+ // The journal is not on the correctness path: a write it loses is logged,
58
+ // and the task runs anyway.
59
+ const record = async (write) => {
60
+ try {
61
+ await write();
62
+ }
63
+ catch (error) {
64
+ logger.error('schedule: journal write failed', {
65
+ task: task.name,
66
+ slot,
67
+ error: String(error),
68
+ });
69
+ }
70
+ };
71
+ let failed = false;
72
+ await record(async () => journal.startRun({
73
+ runId,
74
+ job: task.name,
75
+ trigger: 'schedule',
76
+ mode: 'live',
77
+ startedAt,
78
+ identity: logger.identity,
79
+ }));
80
+ try {
81
+ await task.run({ runId });
82
+ }
83
+ catch (error) {
84
+ failed = true;
85
+ logger.error('schedule: task failed', {
86
+ task: task.name,
87
+ slot,
88
+ error: String(error),
89
+ });
90
+ }
91
+ // Completed on failure too: the next slot retries it, not every tick of this one.
92
+ await ledger.complete(key, task.everySeconds);
93
+ const endedAt = clock.now();
94
+ await record(async () => journal.recordUnit({
95
+ runId,
96
+ unitKey: key,
97
+ unitType: 'schedule-slot',
98
+ recordedAt: endedAt,
99
+ outcome: failed ? 'failed' : 'written',
100
+ ...(failed ? { reasonCode: 'task-threw' } : {}),
101
+ durationMs: endedAt - startedAt,
102
+ }, []));
103
+ await record(async () => journal.finishRun(runId, endedAt));
104
+ return failed ? 'failed' : 'ran';
105
+ }
106
+ /**
107
+ * The Node target's ticker: tick, sleep `tickSeconds`, repeat, until `signal`
108
+ * aborts. Resolves once it has stopped. It reads no time itself; the slot comes
109
+ * from `deps.clock`. A tick longer than the shortest interval misses slots.
110
+ */
111
+ export async function startScheduler(schedule, deps, { tickSeconds, signal }) {
112
+ if (!(tickSeconds > 0)) {
113
+ throw new RangeError(`tickSeconds must be a positive number, not ${tickSeconds}`);
114
+ }
115
+ while (!signal.aborted) {
116
+ await runDueTasks(schedule, deps);
117
+ await sleep(tickSeconds * 1000, signal);
118
+ }
119
+ }
120
+ async function sleep(ms, signal) {
121
+ return new Promise((resolve) => {
122
+ // An abort during the tick has already fired its event.
123
+ if (signal.aborted) {
124
+ resolve();
125
+ return;
126
+ }
127
+ const wake = () => {
128
+ clearTimeout(timer);
129
+ signal.removeEventListener('abort', wake);
130
+ resolve();
131
+ };
132
+ const timer = setTimeout(wake, ms);
133
+ signal.addEventListener('abort', wake);
134
+ });
135
+ }
@@ -0,0 +1,63 @@
1
+ import { type SessionStorage, type Toolkit } from '../contracts/index.js';
2
+ import type { WebhookRegistry } from './define-registry.js';
3
+ /**
4
+ * The largest body the edge reads. Shopify publishes no cap for classic
5
+ * webhooks; its Events API caps an HTTPS delivery at 5 MB
6
+ * (https://shopify.dev/docs/apps/build/events/delivery-structure, 2026-11-11).
7
+ */
8
+ export declare const WEBHOOK_MAX_BODY_BYTES: number;
9
+ /** What the edge sends to `webhookQueue`: one per Action of each delivery it accepts. */
10
+ export type WebhookMessage = {
11
+ readonly source: string;
12
+ /** As Shopify sends it, for example `orders/create`. */
13
+ readonly topic: string;
14
+ readonly shop: string;
15
+ /** `X-Shopify-Webhook-Id`: the same on every retry of one delivery. */
16
+ readonly webhookId: string;
17
+ /** The raw body's key in `blobStore`, written before this message was sent. */
18
+ readonly bodyKey: string;
19
+ /** The registered Action this message runs: one task of the delivery's receipt. */
20
+ readonly action: string;
21
+ };
22
+ /** A delivery's dedup key, and its id in the journal's receipts. Scoped by shop, as the #126 spike recommends. */
23
+ export declare const webhookDeliveryId: ({ source, shop, topic, webhookId, }: Pick<WebhookMessage, "source" | "shop" | "topic" | "webhookId">) => string;
24
+ export type WebhookHandlerOptions = {
25
+ /** Names the app. Part of every dedup key, so keep it once deliveries arrive. */
26
+ readonly source: string;
27
+ /**
28
+ * The consumer's registry. A delivery is receipted with one task per Action
29
+ * of its `(source, topic)`, and queued as one message per task. A topic with
30
+ * none is receipted, answered 200 as `unknown-topic` and not queued.
31
+ */
32
+ readonly registry: Pick<WebhookRegistry<never>, 'actionsFor'>;
33
+ /** The app's client secret, which signs every delivery. */
34
+ readonly secret: string;
35
+ /**
36
+ * The secret before a rotation, accepted as well while set; an empty string
37
+ * counts as unset. Shopify can sign with it for up to an hour after rotating
38
+ * (https://shopify.dev/docs/apps/build/webhooks/subscribe/https, 2026-11-11),
39
+ * and retries resend that signature: keep it for a day.
40
+ */
41
+ readonly previousSecret?: string;
42
+ readonly toolkit: Pick<Toolkit<unknown, WebhookMessage>, 'ledger' | 'journal' | 'webhookQueue' | 'blobStore' | 'clock' | 'logger'>;
43
+ /** A shop with no session here is unknown: uninstalled, or never installed. */
44
+ readonly sessionStorage: Pick<SessionStorage, 'findSessionsByShop'>;
45
+ /** Topics queued even for an unknown shop, such as `shop/redact`. None by default: docs/decisions/0010. */
46
+ readonly unknownShopTopics?: readonly string[];
47
+ /**
48
+ * How long the source retries a failed delivery. Only checked against the
49
+ * other two windows: they must cover it.
50
+ */
51
+ readonly retryHorizonSeconds?: number;
52
+ /** A delivery whose `X-Shopify-Triggered-At` is further than this from now gets 401 `stale-delivery`. */
53
+ readonly replayWindowSeconds?: number;
54
+ /** How long a queued delivery is remembered, so a redelivery is skipped. */
55
+ readonly dedupTtlSeconds?: number;
56
+ };
57
+ /**
58
+ * The edge for Shopify webhooks: replay window, size, signature, shop, dedup
59
+ * claim, raw body to `blobStore`, a receipt in the journal, then one pointer
60
+ * per registered Action on `webhookQueue`, in one `sendBatch`, before the 200. Each answer is one journal unit. Throws unless retry horizon ≤ replay
61
+ * window ≤ dedup TTL, so a misconfigured app fails at start-up.
62
+ */
63
+ export declare function createWebhookHandler(options: WebhookHandlerOptions): (request: Request) => Promise<Response>;
@@ -0,0 +1,246 @@
1
+ import { checkDuration, instant, toIso, } from '../contracts/index.js';
2
+ import { failed, skipped, written, } from '../actions/action.js';
3
+ import { runAction, withRun } from '../actions/run-action.js';
4
+ /**
5
+ * The largest body the edge reads. Shopify publishes no cap for classic
6
+ * webhooks; its Events API caps an HTTPS delivery at 5 MB
7
+ * (https://shopify.dev/docs/apps/build/events/delivery-structure, 2026-11-11).
8
+ */
9
+ export const WEBHOOK_MAX_BODY_BYTES = 5 * 1024 * 1024;
10
+ /** Past Shopify's 5-second budget, so a crash mid-request frees the delivery for a later retry. */
11
+ const DEDUP_LEASE_SECONDS = 60;
12
+ /** The windows' defaults, from the #126 retry spike (docs/spikes/shopify-webhook-retries.md, PR #175). */
13
+ const WEBHOOK_WINDOW_DEFAULTS = {
14
+ /** Shopify retries a failed delivery for 4 hours, documented. */
15
+ retryHorizonSeconds: 4 * 60 * 60,
16
+ /** The horizon plus 50 % for clock skew and delivery lag. */
17
+ replayWindowSeconds: 6 * 60 * 60,
18
+ dedupTtlSeconds: 24 * 60 * 60,
19
+ };
20
+ /** A delivery's dedup key, and its id in the journal's receipts. Scoped by shop, as the #126 spike recommends. */
21
+ export const webhookDeliveryId = ({ source, shop, topic, webhookId, }) => `${source}:${shop}:${topic}:${webhookId}`;
22
+ /** Any other decision answers 500 when retryable and 200 when not. */
23
+ const REJECTION_STATUS = {
24
+ 'missing-header': 401,
25
+ 'stale-delivery': 401,
26
+ 'invalid-hmac': 401,
27
+ 'body-too-large': 413,
28
+ };
29
+ const receiveWebhook = {
30
+ name: 'receive-webhook',
31
+ unitType: 'webhook',
32
+ key: ({ unitKey }) => unitKey,
33
+ async run({ request }, { deps, logger, track }) {
34
+ const { source, secret, previousSecret, toolkit, sessionStorage } = deps;
35
+ const hmac = request.headers.get('X-Shopify-Hmac-Sha256');
36
+ const topic = request.headers.get('X-Shopify-Topic');
37
+ const shop = request.headers.get('X-Shopify-Shop-Domain');
38
+ const webhookId = request.headers.get('X-Shopify-Webhook-Id');
39
+ const triggeredAtHeader = request.headers.get('X-Shopify-Triggered-At');
40
+ if (!hmac || !topic || !shop || !webhookId || !triggeredAtHeader) {
41
+ return failed('missing-header');
42
+ }
43
+ const ids = { externalIds: { shop } };
44
+ const triggeredAt = parseInstant(triggeredAtHeader);
45
+ // Before the body is read, as docs/design.md §7.2 orders it. Measured from
46
+ // Triggered-At, which every retry repeats, so it must cover the retry horizon.
47
+ if (triggeredAt === undefined ||
48
+ Math.abs(toolkit.clock.now() - triggeredAt) >
49
+ deps.replayWindowSeconds * 1000) {
50
+ return failed('stale-delivery', ids);
51
+ }
52
+ const body = await readBody(request, WEBHOOK_MAX_BODY_BYTES);
53
+ if (body === undefined) {
54
+ return failed('body-too-large', ids);
55
+ }
56
+ // Truthy, not just defined: WebCrypto throws on a zero-length key.
57
+ const secrets = previousSecret ? [secret, previousSecret] : [secret];
58
+ if (!(await isSignedWith(secrets, hmac, body))) {
59
+ return failed('invalid-hmac', ids);
60
+ }
61
+ if (!deps.unknownShopTopics?.includes(topic) &&
62
+ (await sessionStorage.findSessionsByShop(shop)).length === 0) {
63
+ return skipped('unknown-shop', ids);
64
+ }
65
+ const key = webhookDeliveryId({ source, shop, topic, webhookId });
66
+ const claim = await toolkit.ledger.claim(key, DEDUP_LEASE_SECONDS);
67
+ if (claim.status === 'completed') {
68
+ return skipped('duplicate-delivery', ids);
69
+ }
70
+ // Not a 200: the holder may still fail its send and release, and a 200
71
+ // would end Shopify's retries of a delivery nobody queued.
72
+ if (claim.status === 'in-progress') {
73
+ return skipped('delivery-in-progress', { ...ids, retryable: true });
74
+ }
75
+ // Shop in the key, so a customers/redact finds one shop's bodies (decision
76
+ // 0010). Dated by Triggered-At, so a retry after midnight overwrites the
77
+ // same key with the same bytes.
78
+ const bodyKey = `webhooks/${source}/${shop}/${toIso(triggeredAt).slice(0, 10)}/${webhookId}`;
79
+ const actions = deps.registry
80
+ .actionsFor(source, topic)
81
+ .map((registration) => registration.action.name);
82
+ try {
83
+ await track('blob', 'put', async () => toolkit.blobStore.put(bodyKey, body, {
84
+ contentType: 'application/json',
85
+ }));
86
+ }
87
+ catch (error) {
88
+ logger.error('body store failed', { error: String(error) });
89
+ await toolkit.ledger.release(key);
90
+ return failed('body-store-failed', { ...ids, retryable: true });
91
+ }
92
+ // A required write: without the receipt, nothing could find this delivery
93
+ // again if the send below is lost.
94
+ try {
95
+ await track('journal', 'recordDelivery', async () => toolkit.journal.recordDelivery({
96
+ deliveryId: key,
97
+ source,
98
+ topic,
99
+ shop,
100
+ webhookId,
101
+ bodyKey,
102
+ receivedAt: toolkit.clock.now(),
103
+ }, actions));
104
+ }
105
+ catch (error) {
106
+ logger.error('receipt failed', { error: String(error) });
107
+ await toolkit.ledger.release(key);
108
+ return failed('receipt-failed', { ...ids, retryable: true });
109
+ }
110
+ // Recorded, so the unhandled-topic alarm can count it, and never 4xx:
111
+ // design §7.1. Completed, so Shopify's redelivery is a duplicate.
112
+ if (actions.length === 0) {
113
+ await toolkit.ledger.complete(key, deps.dedupTtlSeconds);
114
+ return skipped('unknown-topic', ids);
115
+ }
116
+ // One call, so a throw means resend all: Postgres sends none, and each
117
+ // Action's task makes a resent pointer harmless where some were sent (#127).
118
+ try {
119
+ await track('queue', 'sendBatch', async () => toolkit.webhookQueue.sendBatch(actions.map((action) => ({
120
+ source,
121
+ topic,
122
+ shop,
123
+ webhookId,
124
+ bodyKey,
125
+ action,
126
+ }))));
127
+ }
128
+ catch (error) {
129
+ // Logged first, so a release that fails too cannot hide this error.
130
+ logger.error('enqueue failed', { error: String(error) });
131
+ // Free the delivery, so Shopify's retry is not taken for a duplicate.
132
+ await toolkit.ledger.release(key);
133
+ return failed('enqueue-failed', { ...ids, retryable: true });
134
+ }
135
+ // If this throws, the lease stands, and a retry after it queues the
136
+ // delivery a second time.
137
+ await toolkit.ledger.complete(key, deps.dedupTtlSeconds);
138
+ return written(ids);
139
+ },
140
+ };
141
+ /**
142
+ * The edge for Shopify webhooks: replay window, size, signature, shop, dedup
143
+ * claim, raw body to `blobStore`, a receipt in the journal, then one pointer
144
+ * per registered Action on `webhookQueue`, in one `sendBatch`, before the 200. Each answer is one journal unit. Throws unless retry horizon ≤ replay
145
+ * window ≤ dedup TTL, so a misconfigured app fails at start-up.
146
+ */
147
+ export function createWebhookHandler(options) {
148
+ // Web Crypto rejects a zero-length HMAC key, so an unset secret would fail every request outside the journal.
149
+ if (!options.secret) {
150
+ throw new TypeError('createWebhookHandler needs a non-empty secret');
151
+ }
152
+ // The source starts every dedup key.
153
+ if (!options.source) {
154
+ throw new TypeError('createWebhookHandler needs a non-empty source');
155
+ }
156
+ const { retryHorizonSeconds = WEBHOOK_WINDOW_DEFAULTS.retryHorizonSeconds, replayWindowSeconds = WEBHOOK_WINDOW_DEFAULTS.replayWindowSeconds, dedupTtlSeconds = WEBHOOK_WINDOW_DEFAULTS.dedupTtlSeconds, } = options;
157
+ checkDuration('webhooks', 'retryHorizonSeconds', retryHorizonSeconds);
158
+ checkDuration('webhooks', 'replayWindowSeconds', replayWindowSeconds);
159
+ checkDuration('webhooks', 'dedupTtlSeconds', dedupTtlSeconds);
160
+ // A shorter window rejects Shopify's own late retries; a shorter TTL lets a
161
+ // delivery the window admits be queued twice.
162
+ if (retryHorizonSeconds > replayWindowSeconds ||
163
+ replayWindowSeconds > dedupTtlSeconds) {
164
+ throw new TypeError(`webhooks (${options.source}): need retryHorizonSeconds (${retryHorizonSeconds}) ≤ replayWindowSeconds (${replayWindowSeconds}) ≤ dedupTtlSeconds (${dedupTtlSeconds})`);
165
+ }
166
+ const deps = { ...options, replayWindowSeconds, dedupTtlSeconds };
167
+ return async (request) => {
168
+ const topic = request.headers.get('X-Shopify-Topic') || 'unknown';
169
+ const decision = await withRun(options.toolkit, {
170
+ // Named the way @shopify/shopify-api names topics, as the example's runs are.
171
+ job: `webhook.${topic.toUpperCase().replace(/[/.]/g, '_')}`,
172
+ trigger: 'http',
173
+ mode: 'live',
174
+ }, async (scope) => runAction(receiveWebhook, {
175
+ request,
176
+ unitKey: request.headers.get('X-Shopify-Webhook-Id') || scope.runId,
177
+ }, scope, deps));
178
+ return new Response(null, { status: statusFor(decision) });
179
+ };
180
+ }
181
+ function statusFor(decision) {
182
+ if (decision.outcome === 'written') {
183
+ return 200;
184
+ }
185
+ const retryable = 'retryable' in decision && decision.retryable === true;
186
+ return REJECTION_STATUS[decision.reasonCode] ?? (retryable ? 500 : 200);
187
+ }
188
+ /** An unparseable timestamp is treated as outside every window. */
189
+ function parseInstant(iso) {
190
+ try {
191
+ return instant(iso);
192
+ }
193
+ catch {
194
+ return undefined;
195
+ }
196
+ }
197
+ /**
198
+ * The body, or undefined once it passes `maxBytes`. Reading stops there, so
199
+ * an unsigned body costs at most that much memory.
200
+ */
201
+ async function readBody(request, maxBytes) {
202
+ // Typed here because the Workers typings leave `Request.body` untyped.
203
+ const stream = request.body;
204
+ if (stream === null) {
205
+ return new Uint8Array();
206
+ }
207
+ // A reader, not `for await`: apps type-check this source, and under a DOM
208
+ // lib without DOM.AsyncIterable a stream is not async-iterable.
209
+ const reader = stream.getReader();
210
+ const chunks = [];
211
+ let size = 0;
212
+ for (let next = await reader.read(); !next.done; next = await reader.read()) {
213
+ size += next.value.byteLength;
214
+ if (size > maxBytes) {
215
+ await reader.cancel();
216
+ return undefined;
217
+ }
218
+ chunks.push(next.value);
219
+ }
220
+ const body = new Uint8Array(size);
221
+ let offset = 0;
222
+ for (const chunk of chunks) {
223
+ body.set(chunk, offset);
224
+ offset += chunk.byteLength;
225
+ }
226
+ return body;
227
+ }
228
+ /** Shopify's signature: base64 HMAC-SHA256 of the raw body. */
229
+ async function isSignedWith(secrets, hmac, body) {
230
+ let signature;
231
+ try {
232
+ signature = Uint8Array.from(atob(hmac), (char) => char.charCodeAt(0));
233
+ }
234
+ catch {
235
+ // Not base64, so it cannot be Shopify's signature.
236
+ return false;
237
+ }
238
+ for (const secret of secrets) {
239
+ const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);
240
+ // verify compares in constant time; comparing base64 strings would not.
241
+ if (await crypto.subtle.verify('HMAC', key, signature, body)) {
242
+ return true;
243
+ }
244
+ }
245
+ return false;
246
+ }
@@ -0,0 +1,14 @@
1
+ import type { QueueConsumer } from '../contracts/index.js';
2
+ import type { JournalDeps } from '../actions/run-action.js';
3
+ import { type WebhookMessage } from './create-webhook-handler.js';
4
+ /**
5
+ * The consumer of the webhook queue's dead-letter queue: design §7.1, "a DLQ
6
+ * nobody reads is a slower black hole". Each message's task becomes `dead`
7
+ * with reason `dead-lettered`, where `deadTasks` and replay find it.
8
+ *
9
+ * Only a task still `received`, `processing` or `failed` moves: one the
10
+ * consumer already marked `dead` keeps its own reason, and a `done` or
11
+ * `replayed` one is not this message's to touch. A journal write that throws
12
+ * retries the message.
13
+ */
14
+ export declare function createDeadLetterConsumer(toolkit: JournalDeps): QueueConsumer<WebhookMessage>;
@@ -0,0 +1,42 @@
1
+ import { webhookDeliveryId, } from './create-webhook-handler.js';
2
+ /**
3
+ * The consumer of the webhook queue's dead-letter queue: design §7.1, "a DLQ
4
+ * nobody reads is a slower black hole". Each message's task becomes `dead`
5
+ * with reason `dead-lettered`, where `deadTasks` and replay find it.
6
+ *
7
+ * Only a task still `received`, `processing` or `failed` moves: one the
8
+ * consumer already marked `dead` keeps its own reason, and a `done` or
9
+ * `replayed` one is not this message's to touch. A journal write that throws
10
+ * retries the message.
11
+ */
12
+ export function createDeadLetterConsumer(toolkit) {
13
+ const { journal, clock, logger } = toolkit;
14
+ return async (batch) => {
15
+ for (const message of batch.messages) {
16
+ const deliveryId = webhookDeliveryId(message.body);
17
+ const { action } = message.body;
18
+ const context = { deliveryId, action, messageId: message.id };
19
+ try {
20
+ const task = (await journal.delivery(deliveryId))?.tasks.find((t) => t.action === action);
21
+ if (task !== undefined &&
22
+ ['received', 'processing', 'failed'].includes(task.state)) {
23
+ // `dead` is reachable only from `processing`.
24
+ await journal.moveTask(deliveryId, action, 'processing', clock.now());
25
+ await journal.moveTask(deliveryId, action, 'dead', clock.now(), 'dead-lettered');
26
+ }
27
+ logger.warn('webhook dead-lettered', {
28
+ ...context,
29
+ state: task?.state ?? null,
30
+ });
31
+ batch.ack(message.id);
32
+ }
33
+ catch (error) {
34
+ logger.error('webhook receipt failed', {
35
+ ...context,
36
+ error: String(error),
37
+ });
38
+ batch.retry(message.id);
39
+ }
40
+ }
41
+ };
42
+ }