@anatta.io/tva 0.0.0-stage → 0.2.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 (190) hide show
  1. package/README.md +50 -2
  2. package/dist/adapters/cloudflare/bindings.d.ts +10 -0
  3. package/dist/adapters/cloudflare/bindings.js +1 -0
  4. package/dist/adapters/cloudflare/blob-store.d.ts +39 -0
  5. package/dist/adapters/cloudflare/blob-store.js +95 -0
  6. package/dist/adapters/cloudflare/cache.d.ts +14 -0
  7. package/dist/adapters/cloudflare/cache.js +48 -0
  8. package/dist/adapters/cloudflare/faults.d.ts +7 -0
  9. package/dist/adapters/cloudflare/faults.js +39 -0
  10. package/dist/adapters/cloudflare/index.d.ts +15 -0
  11. package/dist/adapters/cloudflare/index.js +16 -0
  12. package/dist/adapters/cloudflare/journal.d.ts +110 -0
  13. package/dist/adapters/cloudflare/journal.js +325 -0
  14. package/dist/adapters/cloudflare/ledger.d.ts +14 -0
  15. package/dist/adapters/cloudflare/ledger.js +108 -0
  16. package/dist/adapters/cloudflare/logger.d.ts +22 -0
  17. package/dist/adapters/cloudflare/logger.js +49 -0
  18. package/dist/adapters/cloudflare/manifest.d.ts +81 -0
  19. package/dist/adapters/cloudflare/manifest.js +81 -0
  20. package/dist/adapters/cloudflare/pipelines.d.ts +97 -0
  21. package/dist/adapters/cloudflare/pipelines.js +218 -0
  22. package/dist/adapters/cloudflare/queue.d.ts +80 -0
  23. package/dist/adapters/cloudflare/queue.js +177 -0
  24. package/dist/adapters/cloudflare/retention.d.ts +24 -0
  25. package/dist/adapters/cloudflare/retention.js +103 -0
  26. package/dist/adapters/cloudflare/session-storage.d.ts +27 -0
  27. package/dist/adapters/cloudflare/session-storage.js +78 -0
  28. package/dist/adapters/cloudflare/toolkit.d.ts +16 -0
  29. package/dist/adapters/cloudflare/toolkit.js +57 -0
  30. package/dist/adapters/cloudflare/workflow-pipelines.d.ts +66 -0
  31. package/dist/adapters/cloudflare/workflow-pipelines.js +323 -0
  32. package/dist/adapters/journal-records.d.ts +80 -0
  33. package/dist/adapters/journal-records.js +75 -0
  34. package/dist/adapters/memory/blob-store.d.ts +9 -0
  35. package/dist/adapters/memory/blob-store.js +19 -0
  36. package/dist/adapters/memory/cache.d.ts +13 -0
  37. package/dist/adapters/memory/cache.js +36 -0
  38. package/dist/adapters/memory/clock.d.ts +1 -0
  39. package/dist/adapters/memory/clock.js +4 -0
  40. package/dist/adapters/memory/index.d.ts +11 -0
  41. package/dist/adapters/memory/index.js +11 -0
  42. package/dist/adapters/memory/journal.d.ts +35 -0
  43. package/dist/adapters/memory/journal.js +154 -0
  44. package/dist/adapters/memory/ledger.d.ts +9 -0
  45. package/dist/adapters/memory/ledger.js +33 -0
  46. package/dist/adapters/memory/logger.d.ts +16 -0
  47. package/dist/adapters/memory/logger.js +21 -0
  48. package/dist/adapters/memory/manifest.d.ts +59 -0
  49. package/dist/adapters/memory/manifest.js +59 -0
  50. package/dist/adapters/memory/pipelines.d.ts +62 -0
  51. package/dist/adapters/memory/pipelines.js +219 -0
  52. package/dist/adapters/memory/queue.d.ts +20 -0
  53. package/dist/adapters/memory/queue.js +102 -0
  54. package/dist/adapters/memory/session-storage.d.ts +20 -0
  55. package/dist/adapters/memory/session-storage.js +33 -0
  56. package/dist/adapters/memory/toolkit.d.ts +8 -0
  57. package/dist/adapters/memory/toolkit.js +31 -0
  58. package/dist/adapters/postgres/cache.d.ts +17 -0
  59. package/dist/adapters/postgres/cache.js +69 -0
  60. package/dist/adapters/postgres/config.d.ts +27 -0
  61. package/dist/adapters/postgres/config.js +45 -0
  62. package/dist/adapters/postgres/faults.d.ts +14 -0
  63. package/dist/adapters/postgres/faults.js +47 -0
  64. package/dist/adapters/postgres/index.d.ts +12 -0
  65. package/dist/adapters/postgres/index.js +12 -0
  66. package/dist/adapters/postgres/journal.d.ts +86 -0
  67. package/dist/adapters/postgres/journal.js +337 -0
  68. package/dist/adapters/postgres/ledger.d.ts +16 -0
  69. package/dist/adapters/postgres/ledger.js +97 -0
  70. package/dist/adapters/postgres/logger.d.ts +19 -0
  71. package/dist/adapters/postgres/logger.js +37 -0
  72. package/dist/adapters/postgres/manifest.d.ts +52 -0
  73. package/dist/adapters/postgres/manifest.js +53 -0
  74. package/dist/adapters/postgres/migrate.d.ts +20 -0
  75. package/dist/adapters/postgres/migrate.js +96 -0
  76. package/dist/adapters/postgres/queue.d.ts +64 -0
  77. package/dist/adapters/postgres/queue.js +333 -0
  78. package/dist/adapters/postgres/retention.d.ts +18 -0
  79. package/dist/adapters/postgres/retention.js +104 -0
  80. package/dist/adapters/postgres/session-storage.d.ts +20 -0
  81. package/dist/adapters/postgres/session-storage.js +71 -0
  82. package/dist/adapters/postgres/toolkit.d.ts +25 -0
  83. package/dist/adapters/postgres/toolkit.js +58 -0
  84. package/dist/adapters/postgres/with-client.d.ts +11 -0
  85. package/dist/adapters/postgres/with-client.js +29 -0
  86. package/dist/adapters/reference-executor.d.ts +171 -0
  87. package/dist/adapters/reference-executor.js +569 -0
  88. package/dist/adapters/retention.d.ts +18 -0
  89. package/dist/adapters/retention.js +13 -0
  90. package/dist/adapters/s3/blob-store.d.ts +35 -0
  91. package/dist/adapters/s3/blob-store.js +92 -0
  92. package/dist/adapters/s3/faults.d.ts +8 -0
  93. package/dist/adapters/s3/faults.js +34 -0
  94. package/dist/adapters/s3/index.d.ts +2 -0
  95. package/dist/adapters/s3/index.js +2 -0
  96. package/dist/adapters/session-envelope.d.ts +21 -0
  97. package/dist/adapters/session-envelope.js +122 -0
  98. package/dist/adapters/system-clock.d.ts +8 -0
  99. package/dist/adapters/system-clock.js +8 -0
  100. package/dist/contracts/blob-store.d.ts +11 -0
  101. package/dist/contracts/blob-store.js +1 -0
  102. package/dist/contracts/cache.d.ts +27 -0
  103. package/dist/contracts/cache.js +1 -0
  104. package/dist/contracts/duration.d.ts +23 -0
  105. package/dist/contracts/duration.js +27 -0
  106. package/dist/contracts/faults.d.ts +28 -0
  107. package/dist/contracts/faults.js +29 -0
  108. package/dist/contracts/identity.d.ts +12 -0
  109. package/dist/contracts/identity.js +1 -0
  110. package/dist/contracts/index.d.ts +14 -0
  111. package/dist/contracts/index.js +15 -0
  112. package/dist/contracts/instant.d.ts +17 -0
  113. package/dist/contracts/instant.js +12 -0
  114. package/dist/contracts/journal.d.ts +196 -0
  115. package/dist/contracts/journal.js +10 -0
  116. package/dist/contracts/ledger.d.ts +34 -0
  117. package/dist/contracts/ledger.js +1 -0
  118. package/dist/contracts/logger.d.ts +11 -0
  119. package/dist/contracts/logger.js +1 -0
  120. package/dist/contracts/manifest.d.ts +37 -0
  121. package/dist/contracts/manifest.js +30 -0
  122. package/dist/contracts/pipelines.d.ts +348 -0
  123. package/dist/contracts/pipelines.js +1 -0
  124. package/dist/contracts/queue.d.ts +55 -0
  125. package/dist/contracts/queue.js +1 -0
  126. package/dist/contracts/session-storage.d.ts +18 -0
  127. package/dist/contracts/session-storage.js +1 -0
  128. package/dist/contracts/toolkit.d.ts +21 -0
  129. package/dist/contracts/toolkit.js +1 -0
  130. package/dist/pipelines/index.d.ts +1 -0
  131. package/dist/pipelines/index.js +2 -0
  132. package/dist/pipelines/pipeline.d.ts +142 -0
  133. package/dist/pipelines/pipeline.js +140 -0
  134. package/dist/pipelines/use-case-step.d.ts +24 -0
  135. package/dist/pipelines/use-case-step.js +34 -0
  136. package/dist/schedule/schedule.d.ts +40 -0
  137. package/dist/schedule/schedule.js +135 -0
  138. package/dist/use-cases/index.d.ts +3 -0
  139. package/dist/use-cases/index.js +3 -0
  140. package/dist/use-cases/run-use-case.d.ts +33 -0
  141. package/dist/use-cases/run-use-case.js +117 -0
  142. package/dist/use-cases/use-case-consumer.d.ts +44 -0
  143. package/dist/use-cases/use-case-consumer.js +98 -0
  144. package/dist/use-cases/use-case.d.ts +116 -0
  145. package/dist/use-cases/use-case.js +75 -0
  146. package/dist/webhooks/create-webhook-handler.d.ts +63 -0
  147. package/dist/webhooks/create-webhook-handler.js +253 -0
  148. package/dist/webhooks/dead-letter-consumer.d.ts +14 -0
  149. package/dist/webhooks/dead-letter-consumer.js +42 -0
  150. package/dist/webhooks/define-registry.d.ts +42 -0
  151. package/dist/webhooks/define-registry.js +56 -0
  152. package/dist/webhooks/once.d.ts +15 -0
  153. package/dist/webhooks/once.js +29 -0
  154. package/dist/webhooks/redact-customer-bodies.d.ts +29 -0
  155. package/dist/webhooks/redact-customer-bodies.js +45 -0
  156. package/dist/webhooks/replay-webhooks.d.ts +39 -0
  157. package/dist/webhooks/replay-webhooks.js +82 -0
  158. package/dist/webhooks/sign-shopify-webhook.d.ts +14 -0
  159. package/dist/webhooks/sign-shopify-webhook.js +31 -0
  160. package/dist/webhooks/sweep-stuck-tasks.d.ts +32 -0
  161. package/dist/webhooks/sweep-stuck-tasks.js +73 -0
  162. package/dist/webhooks/webhook-consumer.d.ts +52 -0
  163. package/dist/webhooks/webhook-consumer.js +132 -0
  164. package/migrations/0001_create_ledger_claims.sql +23 -0
  165. package/migrations/0002_create_journal.sql +76 -0
  166. package/migrations/0003_create_shopify_sessions.sql +30 -0
  167. package/migrations/0004_create_journal_steps.sql +34 -0
  168. package/migrations/0007_create_job_tables.sql +71 -0
  169. package/migrations/0008_add_ledger_completed_at.sql +7 -0
  170. package/migrations/0009_create_webhook_receipts.sql +34 -0
  171. package/migrations/0010_index_webhook_deliveries_received_at.sql +2 -0
  172. package/migrations/0011_add_webhook_task_reason_code.sql +4 -0
  173. package/migrations/0012_rename_webhook_task_action_to_use_case.sql +11 -0
  174. package/migrations/0013_rename_job_tables_to_pipeline.sql +24 -0
  175. package/migrations/0016_add_webhook_task_requeues.sql +3 -0
  176. package/migrations/postgres/0001_create_ledger_claims.sql +13 -0
  177. package/migrations/postgres/0002_create_journal.sql +48 -0
  178. package/migrations/postgres/0003_create_shopify_sessions.sql +12 -0
  179. package/migrations/postgres/0004_create_journal_steps.sql +19 -0
  180. package/migrations/postgres/0005_create_cache_entries.sql +14 -0
  181. package/migrations/postgres/0006_create_queue.sql +42 -0
  182. package/migrations/postgres/0007_create_job_tables.sql +40 -0
  183. package/migrations/postgres/0008_add_ledger_completed_at.sql +3 -0
  184. package/migrations/postgres/0009_create_webhook_receipts.sql +23 -0
  185. package/migrations/postgres/0010_index_webhook_deliveries_received_at.sql +2 -0
  186. package/migrations/postgres/0011_add_webhook_task_reason_code.sql +3 -0
  187. package/migrations/postgres/0012_rename_webhook_task_action_to_use_case.sql +5 -0
  188. package/migrations/postgres/0013_rename_job_tables_to_pipeline.sql +22 -0
  189. package/migrations/postgres/0016_add_webhook_task_requeues.sql +3 -0
  190. package/package.json +144 -4
@@ -0,0 +1,116 @@
1
+ import type { Logger, RunId, RunRow, UnitKey } from '../contracts/index.js';
2
+ import { type JournalDeps } from './run-use-case.js';
3
+ /**
4
+ * A USE CASE IS ONE UNIT OF WORK WITH ONE OBSERVABLE OUTCOME, whatever
5
+ * triggered it. It takes typed input and returns a Decision: what the system
6
+ * chose to do with one unit, and why. Name it VerbNoun in the business's
7
+ * words, for example `TagOrder`. It orchestrates; the pure decision logic it
8
+ * calls is a Rule. Extend this class and write `run`; it never writes to the
9
+ * journal. `execute` is the only way to call it: it opens the use case's own
10
+ * journal run and records the decision in it, so the record does not depend
11
+ * on the author or the trigger remembering to write it (#94, decision 0013).
12
+ * `run` is protected, so no caller can skip `execute`.
13
+ *
14
+ * Hold no per-call state on `this`: one instance serves every message, and
15
+ * concurrent ones share it. Per-call state lives in `run`'s locals and its
16
+ * `UseCaseContext`. For a one-off use case, `defineUseCase` takes a plain object.
17
+ *
18
+ * A use case runs inline and reaches one outcome per unit. Work that needs
19
+ * retries between its steps, or must survive a restart part way through, is a
20
+ * `PipelineDefinition`.
21
+ *
22
+ * Cleanup happens inside `run`: free what it claimed, then return the
23
+ * decision.
24
+ */
25
+ export declare abstract class UseCase<Input, Reason extends string, Deps> {
26
+ /** Added to every log line the use case writes. */
27
+ abstract readonly name: string;
28
+ /** The journal's `unitType`, for example `order`. */
29
+ abstract readonly unitType: string;
30
+ constructor();
31
+ /** The journal's unit key. A pure function of the input. */
32
+ abstract key(input: Input): UnitKey;
33
+ /** The domain logic: decide what to do with one unit. */
34
+ protected abstract run(input: Input, context: UseCaseContext<Deps>): Promise<Decision<Reason>>;
35
+ /**
36
+ * Runs the use case in a journal run of its own: starts the run, times the
37
+ * unit, collects the calls it tracks, records its decision and finishes the
38
+ * run. One call, one run, one unit.
39
+ *
40
+ * A throw from `run` records no unit and is rethrown: a fault is not a
41
+ * decision, and the trigger decides what it means. A rejected `startRun` or
42
+ * `recordUnit` reaches the caller too, so a queue consumer retries the
43
+ * message. A rejected `finishRun` is logged, not thrown: the decision is
44
+ * already recorded.
45
+ */
46
+ execute(input: Input, options: ExecuteOptions<Deps>): Promise<Decision<Reason>>;
47
+ }
48
+ /** A one-off use case as a plain object, for `defineUseCase`. */
49
+ export type UseCaseDefinition<Input, Reason extends string, Deps> = {
50
+ readonly name: string;
51
+ readonly unitType: string;
52
+ readonly key: (input: Input) => UnitKey;
53
+ readonly run: (input: Input, context: UseCaseContext<Deps>) => Promise<Decision<Reason>>;
54
+ };
55
+ /**
56
+ * A use case from a plain object, for one that is not worth a class: a test,
57
+ * or a unit whose decision is already made. Its `run` is still reachable only
58
+ * through `execute`.
59
+ */
60
+ export declare function defineUseCase<Input, Reason extends string, Deps>(definition: UseCaseDefinition<Input, Reason, Deps>): UseCase<Input, Reason, Deps>;
61
+ /** What `execute` needs to open the use case's run, and the use case's deps. */
62
+ export type ExecuteOptions<Deps> = {
63
+ /** Writes the run, the unit and the log lines. A `Toolkit` is one. */
64
+ readonly toolkit: JournalDeps;
65
+ /** What started this call: a route, a queue message, a schedule, a replay. */
66
+ readonly trigger: RunRow['trigger'];
67
+ /** Passed to `run` as `context.deps`. */
68
+ readonly deps: Deps;
69
+ /** The run's `job`. Defaults to `<trigger>.<name>`, for example `queue.order-tagger`. */
70
+ readonly job?: string;
71
+ /** The run's id. Defaults to a new UUID; pass one to log it before the run starts. */
72
+ readonly runId?: RunId;
73
+ /** Defaults to `live`. */
74
+ readonly mode?: RunRow['mode'];
75
+ };
76
+ export type UseCaseContext<Deps> = {
77
+ readonly deps: Deps;
78
+ /** Adds `useCase`, `runId` and `unitKey` to every line. */
79
+ readonly logger: Logger;
80
+ /**
81
+ * Calls `fn` and records it as an `ok` or `failed` call with its duration.
82
+ * Returns what `fn` returns, and rethrows what it throws. A property, not a
83
+ * method, so a use case can destructure it from the context.
84
+ */
85
+ readonly track: <T>(system: string, operation: string, fn: () => Promise<T>) => Promise<T>;
86
+ };
87
+ type DecisionExtras = {
88
+ readonly externalIds?: Readonly<Record<string, string>>;
89
+ };
90
+ type RetryableExtras = DecisionExtras & {
91
+ /**
92
+ * Try the unit again later: a queue retries the message, and an HTTP
93
+ * transport answers 500. Same word as `ToolFault.retryable`.
94
+ */
95
+ readonly retryable?: boolean;
96
+ };
97
+ /**
98
+ * Every outcome but `written` carries a reason code from the domain's closed
99
+ * list, and only `failed` and `skipped` can be retryable: an `unchanged` unit
100
+ * has nothing left to do. A throw is not a decision: it is a fault, it records
101
+ * nothing, and the transport retries it.
102
+ */
103
+ export type Decision<Reason extends string> = ({
104
+ readonly outcome: 'written';
105
+ } & DecisionExtras) | ({
106
+ readonly outcome: 'failed' | 'skipped';
107
+ readonly reasonCode: Reason;
108
+ } & RetryableExtras) | ({
109
+ readonly outcome: 'unchanged' | 'would-write';
110
+ readonly reasonCode: Reason;
111
+ } & DecisionExtras);
112
+ export declare function written(extras?: DecisionExtras): Decision<never>;
113
+ export declare function skipped<R extends string>(reasonCode: R, extras?: RetryableExtras): Decision<R>;
114
+ export declare function failed<R extends string>(reasonCode: R, extras?: RetryableExtras): Decision<R>;
115
+ export declare function unchanged<R extends string>(reasonCode: R, extras?: DecisionExtras): Decision<R>;
116
+ export {};
@@ -0,0 +1,75 @@
1
+ import { runUseCase } from './run-use-case.js';
2
+ /**
3
+ * A USE CASE IS ONE UNIT OF WORK WITH ONE OBSERVABLE OUTCOME, whatever
4
+ * triggered it. It takes typed input and returns a Decision: what the system
5
+ * chose to do with one unit, and why. Name it VerbNoun in the business's
6
+ * words, for example `TagOrder`. It orchestrates; the pure decision logic it
7
+ * calls is a Rule. Extend this class and write `run`; it never writes to the
8
+ * journal. `execute` is the only way to call it: it opens the use case's own
9
+ * journal run and records the decision in it, so the record does not depend
10
+ * on the author or the trigger remembering to write it (#94, decision 0013).
11
+ * `run` is protected, so no caller can skip `execute`.
12
+ *
13
+ * Hold no per-call state on `this`: one instance serves every message, and
14
+ * concurrent ones share it. Per-call state lives in `run`'s locals and its
15
+ * `UseCaseContext`. For a one-off use case, `defineUseCase` takes a plain object.
16
+ *
17
+ * A use case runs inline and reaches one outcome per unit. Work that needs
18
+ * retries between its steps, or must survive a restart part way through, is a
19
+ * `PipelineDefinition`.
20
+ *
21
+ * Cleanup happens inside `run`: free what it claimed, then return the
22
+ * decision.
23
+ */
24
+ export class UseCase {
25
+ constructor() {
26
+ // TypeScript has no `final`. An override of `execute` could skip the
27
+ // journal, which is what this class exists to prevent.
28
+ if (this.execute !== UseCase.prototype.execute) {
29
+ throw new TypeError(`${new.target.name} must not override execute`);
30
+ }
31
+ }
32
+ /**
33
+ * Runs the use case in a journal run of its own: starts the run, times the
34
+ * unit, collects the calls it tracks, records its decision and finishes the
35
+ * run. One call, one run, one unit.
36
+ *
37
+ * A throw from `run` records no unit and is rethrown: a fault is not a
38
+ * decision, and the trigger decides what it means. A rejected `startRun` or
39
+ * `recordUnit` reaches the caller too, so a queue consumer retries the
40
+ * message. A rejected `finishRun` is logged, not thrown: the decision is
41
+ * already recorded.
42
+ */
43
+ async execute(input, options) {
44
+ return runUseCase(this, input, options, async (context) => this.run(input, context));
45
+ }
46
+ }
47
+ /**
48
+ * A use case from a plain object, for one that is not worth a class: a test,
49
+ * or a unit whose decision is already made. Its `run` is still reachable only
50
+ * through `execute`.
51
+ */
52
+ export function defineUseCase(definition) {
53
+ return new (class extends UseCase {
54
+ name = definition.name;
55
+ unitType = definition.unitType;
56
+ key(input) {
57
+ return definition.key(input);
58
+ }
59
+ async run(input, context) {
60
+ return definition.run(input, context);
61
+ }
62
+ })();
63
+ }
64
+ export function written(extras = {}) {
65
+ return { outcome: 'written', ...extras };
66
+ }
67
+ export function skipped(reasonCode, extras = {}) {
68
+ return { outcome: 'skipped', reasonCode, ...extras };
69
+ }
70
+ export function failed(reasonCode, extras = {}) {
71
+ return { outcome: 'failed', reasonCode, ...extras };
72
+ }
73
+ export function unchanged(reasonCode, extras = {}) {
74
+ return { outcome: 'unchanged', reasonCode, ...extras };
75
+ }
@@ -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 use case 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 use case this message runs: one task of the delivery's receipt. */
20
+ readonly useCase: 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 use case
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>, 'useCasesFor'>;
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 use case 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,253 @@
1
+ import { checkDuration, instant, toIso, } from '../contracts/index.js';
2
+ import { UseCase, failed, skipped, written, } from '../use-cases/use-case.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 const WEBHOOK_MAX_BODY_BYTES = 5 * 1024 * 1024;
9
+ /** Past Shopify's 5-second budget, so a crash mid-request frees the delivery for a later retry. */
10
+ const DEDUP_LEASE_SECONDS = 60;
11
+ /** The windows' defaults, from the #126 retry spike (docs/spikes/shopify-webhook-retries.md, PR #175). */
12
+ const WEBHOOK_WINDOW_DEFAULTS = {
13
+ /** Shopify retries a failed delivery for 4 hours, documented. */
14
+ retryHorizonSeconds: 4 * 60 * 60,
15
+ /** The horizon plus 50 % for clock skew and delivery lag. */
16
+ replayWindowSeconds: 6 * 60 * 60,
17
+ dedupTtlSeconds: 24 * 60 * 60,
18
+ };
19
+ /** A delivery's dedup key, and its id in the journal's receipts. Scoped by shop, as the #126 spike recommends. */
20
+ export const webhookDeliveryId = ({ source, shop, topic, webhookId, }) => `${source}:${shop}:${topic}:${webhookId}`;
21
+ /** Any other decision answers 500 when retryable and 200 when not. */
22
+ const REJECTION_STATUS = {
23
+ 'missing-header': 401,
24
+ 'stale-delivery': 401,
25
+ 'invalid-hmac': 401,
26
+ 'body-too-large': 413,
27
+ };
28
+ class ReceiveWebhook extends UseCase {
29
+ name = 'receive-webhook';
30
+ unitType = 'webhook';
31
+ key({ unitKey }) {
32
+ return unitKey;
33
+ }
34
+ async run({ request }, { deps, logger, track }) {
35
+ const { source, secret, previousSecret, toolkit, sessionStorage } = deps;
36
+ const hmac = request.headers.get('X-Shopify-Hmac-Sha256');
37
+ const topic = request.headers.get('X-Shopify-Topic');
38
+ const shop = request.headers.get('X-Shopify-Shop-Domain');
39
+ const webhookId = request.headers.get('X-Shopify-Webhook-Id');
40
+ const triggeredAtHeader = request.headers.get('X-Shopify-Triggered-At');
41
+ if (!hmac || !topic || !shop || !webhookId || !triggeredAtHeader) {
42
+ return failed('missing-header');
43
+ }
44
+ const ids = { externalIds: { shop } };
45
+ const triggeredAt = parseInstant(triggeredAtHeader);
46
+ // Before the body is read, as docs/design.md §7.2 orders it. Measured from
47
+ // Triggered-At, which every retry repeats, so it must cover the retry horizon.
48
+ if (triggeredAt === undefined ||
49
+ Math.abs(toolkit.clock.now() - triggeredAt) >
50
+ deps.replayWindowSeconds * 1000) {
51
+ return failed('stale-delivery', ids);
52
+ }
53
+ const body = await readBody(request, WEBHOOK_MAX_BODY_BYTES);
54
+ if (body === undefined) {
55
+ return failed('body-too-large', ids);
56
+ }
57
+ // Truthy, not just defined: WebCrypto throws on a zero-length key.
58
+ const secrets = previousSecret ? [secret, previousSecret] : [secret];
59
+ if (!(await isSignedWith(secrets, hmac, body))) {
60
+ return failed('invalid-hmac', ids);
61
+ }
62
+ if (!deps.unknownShopTopics?.includes(topic) &&
63
+ (await sessionStorage.findSessionsByShop(shop)).length === 0) {
64
+ return skipped('unknown-shop', ids);
65
+ }
66
+ const key = webhookDeliveryId({ source, shop, topic, webhookId });
67
+ const claim = await toolkit.ledger.claim(key, DEDUP_LEASE_SECONDS);
68
+ if (claim.status === 'completed') {
69
+ return skipped('duplicate-delivery', ids);
70
+ }
71
+ // Not a 200: the holder may still fail its send and release, and a 200
72
+ // would end Shopify's retries of a delivery nobody queued.
73
+ if (claim.status === 'in-progress') {
74
+ return skipped('delivery-in-progress', { ...ids, retryable: true });
75
+ }
76
+ // Shop in the key, so a customers/redact finds one shop's bodies (decision
77
+ // 0010). Dated by Triggered-At, so a retry after midnight overwrites the
78
+ // same key with the same bytes.
79
+ const bodyKey = `webhooks/${source}/${shop}/${toIso(triggeredAt).slice(0, 10)}/${webhookId}`;
80
+ const useCases = deps.registry
81
+ .useCasesFor(source, topic)
82
+ .map((registration) => registration.useCase.name);
83
+ try {
84
+ await track('blob', 'put', async () => toolkit.blobStore.put(bodyKey, body, {
85
+ contentType: 'application/json',
86
+ }));
87
+ }
88
+ catch (error) {
89
+ logger.error('body store failed', { error: String(error) });
90
+ await toolkit.ledger.release(key);
91
+ return failed('body-store-failed', { ...ids, retryable: true });
92
+ }
93
+ // A required write: without the receipt, nothing could find this delivery
94
+ // again if the send below is lost.
95
+ try {
96
+ await track('journal', 'recordDelivery', async () => toolkit.journal.recordDelivery({
97
+ deliveryId: key,
98
+ source,
99
+ topic,
100
+ shop,
101
+ webhookId,
102
+ bodyKey,
103
+ receivedAt: toolkit.clock.now(),
104
+ }, useCases));
105
+ }
106
+ catch (error) {
107
+ logger.error('receipt failed', { error: String(error) });
108
+ await toolkit.ledger.release(key);
109
+ return failed('receipt-failed', { ...ids, retryable: true });
110
+ }
111
+ // Recorded, so the unhandled-topic alarm can count it, and never 4xx:
112
+ // design §7.1. Completed, so Shopify's redelivery is a duplicate.
113
+ if (useCases.length === 0) {
114
+ await toolkit.ledger.complete(key, deps.dedupTtlSeconds);
115
+ return skipped('unknown-topic', ids);
116
+ }
117
+ // One call, so a throw means resend all: Postgres sends none, and each
118
+ // use case's task makes a resent pointer harmless where some were sent (#127).
119
+ try {
120
+ await track('queue', 'sendBatch', async () => toolkit.webhookQueue.sendBatch(useCases.map((useCase) => ({
121
+ source,
122
+ topic,
123
+ shop,
124
+ webhookId,
125
+ bodyKey,
126
+ useCase,
127
+ }))));
128
+ }
129
+ catch (error) {
130
+ // Logged first, so a release that fails too cannot hide this error.
131
+ logger.error('enqueue failed', { error: String(error) });
132
+ // Free the delivery, so Shopify's retry is not taken for a duplicate.
133
+ await toolkit.ledger.release(key);
134
+ return failed('enqueue-failed', { ...ids, retryable: true });
135
+ }
136
+ // If this throws, the lease stands, and a retry after it queues the
137
+ // delivery a second time.
138
+ await toolkit.ledger.complete(key, deps.dedupTtlSeconds);
139
+ return written(ids);
140
+ }
141
+ }
142
+ const receiveWebhook = new ReceiveWebhook();
143
+ /**
144
+ * The edge for Shopify webhooks: replay window, size, signature, shop, dedup
145
+ * claim, raw body to `blobStore`, a receipt in the journal, then one pointer
146
+ * per registered use case on `webhookQueue`, in one `sendBatch`, before the 200. Each answer is one journal unit. Throws unless retry horizon ≤ replay
147
+ * window ≤ dedup TTL, so a misconfigured app fails at start-up.
148
+ */
149
+ export function createWebhookHandler(options) {
150
+ // Web Crypto rejects a zero-length HMAC key, so an unset secret would fail every request outside the journal.
151
+ if (!options.secret) {
152
+ throw new TypeError('createWebhookHandler needs a non-empty secret');
153
+ }
154
+ // The source starts every dedup key.
155
+ if (!options.source) {
156
+ throw new TypeError('createWebhookHandler needs a non-empty source');
157
+ }
158
+ const { retryHorizonSeconds = WEBHOOK_WINDOW_DEFAULTS.retryHorizonSeconds, replayWindowSeconds = WEBHOOK_WINDOW_DEFAULTS.replayWindowSeconds, dedupTtlSeconds = WEBHOOK_WINDOW_DEFAULTS.dedupTtlSeconds, } = options;
159
+ checkDuration('webhooks', 'retryHorizonSeconds', retryHorizonSeconds);
160
+ checkDuration('webhooks', 'replayWindowSeconds', replayWindowSeconds);
161
+ checkDuration('webhooks', 'dedupTtlSeconds', dedupTtlSeconds);
162
+ // A shorter window rejects Shopify's own late retries; a shorter TTL lets a
163
+ // delivery the window admits be queued twice.
164
+ if (retryHorizonSeconds > replayWindowSeconds ||
165
+ replayWindowSeconds > dedupTtlSeconds) {
166
+ throw new TypeError(`webhooks (${options.source}): need retryHorizonSeconds (${retryHorizonSeconds}) ≤ replayWindowSeconds (${replayWindowSeconds}) ≤ dedupTtlSeconds (${dedupTtlSeconds})`);
167
+ }
168
+ const deps = { ...options, replayWindowSeconds, dedupTtlSeconds };
169
+ return async (request) => {
170
+ const topic = request.headers.get('X-Shopify-Topic') || 'unknown';
171
+ // Chosen here, so a request with no webhook id is keyed by its run.
172
+ const runId = crypto.randomUUID();
173
+ const input = {
174
+ request,
175
+ unitKey: request.headers.get('X-Shopify-Webhook-Id') || runId,
176
+ };
177
+ const decision = await receiveWebhook.execute(input, {
178
+ toolkit: options.toolkit,
179
+ trigger: 'http',
180
+ // Named the way @shopify/shopify-api names topics.
181
+ job: `webhook.${topic.toUpperCase().replace(/[/.]/g, '_')}`,
182
+ runId,
183
+ deps,
184
+ });
185
+ return new Response(null, { status: statusFor(decision) });
186
+ };
187
+ }
188
+ function statusFor(decision) {
189
+ if (decision.outcome === 'written') {
190
+ return 200;
191
+ }
192
+ const retryable = 'retryable' in decision && decision.retryable === true;
193
+ return REJECTION_STATUS[decision.reasonCode] ?? (retryable ? 500 : 200);
194
+ }
195
+ /** An unparseable timestamp is treated as outside every window. */
196
+ function parseInstant(iso) {
197
+ try {
198
+ return instant(iso);
199
+ }
200
+ catch {
201
+ return undefined;
202
+ }
203
+ }
204
+ /**
205
+ * The body, or undefined once it passes `maxBytes`. Reading stops there, so
206
+ * an unsigned body costs at most that much memory.
207
+ */
208
+ async function readBody(request, maxBytes) {
209
+ // Typed here because the Workers typings leave `Request.body` untyped.
210
+ const stream = request.body;
211
+ if (stream === null) {
212
+ return new Uint8Array();
213
+ }
214
+ // A reader, not `for await`: apps type-check this source, and under a DOM
215
+ // lib without DOM.AsyncIterable a stream is not async-iterable.
216
+ const reader = stream.getReader();
217
+ const chunks = [];
218
+ let size = 0;
219
+ for (let next = await reader.read(); !next.done; next = await reader.read()) {
220
+ size += next.value.byteLength;
221
+ if (size > maxBytes) {
222
+ await reader.cancel();
223
+ return undefined;
224
+ }
225
+ chunks.push(next.value);
226
+ }
227
+ const body = new Uint8Array(size);
228
+ let offset = 0;
229
+ for (const chunk of chunks) {
230
+ body.set(chunk, offset);
231
+ offset += chunk.byteLength;
232
+ }
233
+ return body;
234
+ }
235
+ /** Shopify's signature: base64 HMAC-SHA256 of the raw body. */
236
+ async function isSignedWith(secrets, hmac, body) {
237
+ let signature;
238
+ try {
239
+ signature = Uint8Array.from(atob(hmac), (char) => char.charCodeAt(0));
240
+ }
241
+ catch {
242
+ // Not base64, so it cannot be Shopify's signature.
243
+ return false;
244
+ }
245
+ for (const secret of secrets) {
246
+ const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);
247
+ // verify compares in constant time; comparing base64 strings would not.
248
+ if (await crypto.subtle.verify('HMAC', key, signature, body)) {
249
+ return true;
250
+ }
251
+ }
252
+ return false;
253
+ }
@@ -0,0 +1,14 @@
1
+ import type { QueueConsumer } from '../contracts/index.js';
2
+ import type { JournalDeps } from '../use-cases/run-use-case.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 { useCase } = message.body;
18
+ const context = { deliveryId, useCase, messageId: message.id };
19
+ try {
20
+ const task = (await journal.delivery(deliveryId))?.tasks.find((t) => t.useCase === useCase);
21
+ if (task !== undefined &&
22
+ ['received', 'processing', 'failed'].includes(task.state)) {
23
+ // `dead` is reachable only from `processing`.
24
+ await journal.moveTask(deliveryId, useCase, 'processing', clock.now());
25
+ await journal.moveTask(deliveryId, useCase, '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
+ }
@@ -0,0 +1,42 @@
1
+ import type { WebhookUseCase } from './webhook-consumer.js';
2
+ /**
3
+ * The most use cases one topic may have: the edge sends one pointer per use case
4
+ * in one `sendBatch`, which Cloudflare caps at 100 messages (#127,
5
+ * docs/platform-facts.md "`sendBatch` cap").
6
+ */
7
+ export declare const WEBHOOK_MAX_USE_CASES_PER_TOPIC = 100;
8
+ /** One use case for one `(source, topic)`, with its own retry settings. */
9
+ export type WebhookRegistration<Deps> = {
10
+ readonly source: string;
11
+ /** As Shopify sends it, for example `orders/create`. */
12
+ readonly topic: string;
13
+ readonly useCase: WebhookUseCase<Deps>;
14
+ /** Overrides the consumer's `retryDelaySeconds` for this use case. */
15
+ readonly retryDelaySeconds?: number;
16
+ /**
17
+ * Overrides the consumer's `maxAttempts`, which it must not exceed. Below
18
+ * it, a task that runs out is `dead` and its message is acked: replay reads
19
+ * the journal, not the dead-letter queue.
20
+ */
21
+ readonly maxAttempts?: number;
22
+ };
23
+ /** What only the domain knows about a topic. */
24
+ export type WebhookTopicSettings = {
25
+ readonly source: string;
26
+ readonly topic: string;
27
+ /** The longest normal gap between deliveries, for the silence alarm (design §7.4). */
28
+ readonly quietPeriodSeconds: number;
29
+ };
30
+ export type WebhookRegistry<Deps> = {
31
+ readonly useCases: readonly WebhookRegistration<Deps>[];
32
+ readonly topics: readonly WebhookTopicSettings[];
33
+ /** The topic's use cases, in registration order; none for an unknown topic. */
34
+ useCasesFor(source: string, topic: string): readonly WebhookRegistration<Deps>[];
35
+ };
36
+ /**
37
+ * The `(source, topic, useCase)` table the edge and the consumer share, as
38
+ * data. Throws on a duplicate, on more than `WEBHOOK_MAX_USE_CASES_PER_TOPIC`
39
+ * use cases for a topic, on settings for a topic with no use case and on a bad
40
+ * duration, so a misconfigured app fails at start-up.
41
+ */
42
+ export declare function defineRegistry<Deps>(useCases: readonly WebhookRegistration<Deps>[], topics?: readonly WebhookTopicSettings[]): WebhookRegistry<Deps>;
@@ -0,0 +1,56 @@
1
+ import { checkDuration } from '../contracts/index.js';
2
+ /**
3
+ * The most use cases one topic may have: the edge sends one pointer per use case
4
+ * in one `sendBatch`, which Cloudflare caps at 100 messages (#127,
5
+ * docs/platform-facts.md "`sendBatch` cap").
6
+ */
7
+ export const WEBHOOK_MAX_USE_CASES_PER_TOPIC = 100;
8
+ /**
9
+ * The `(source, topic, useCase)` table the edge and the consumer share, as
10
+ * data. Throws on a duplicate, on more than `WEBHOOK_MAX_USE_CASES_PER_TOPIC`
11
+ * use cases for a topic, on settings for a topic with no use case and on a bad
12
+ * duration, so a misconfigured app fails at start-up.
13
+ */
14
+ export function defineRegistry(useCases, topics = []) {
15
+ const byTopic = new Map();
16
+ for (const registration of useCases) {
17
+ const { source, topic, useCase } = registration;
18
+ const label = `${source} ${topic} ${useCase.name}`;
19
+ const key = topicKey(source, topic);
20
+ const registered = byTopic.get(key) ?? [];
21
+ if (registered.some((other) => other.useCase.name === useCase.name)) {
22
+ throw new TypeError(`webhook registry: ${label} is registered twice`);
23
+ }
24
+ if (registered.length === WEBHOOK_MAX_USE_CASES_PER_TOPIC) {
25
+ throw new TypeError(`webhook registry: ${source} ${topic} has more than ${WEBHOOK_MAX_USE_CASES_PER_TOPIC} use cases`);
26
+ }
27
+ if (registration.retryDelaySeconds !== undefined) {
28
+ checkDuration(label, 'retryDelaySeconds', registration.retryDelaySeconds);
29
+ }
30
+ if (registration.maxAttempts !== undefined &&
31
+ !(Number.isInteger(registration.maxAttempts) &&
32
+ registration.maxAttempts >= 1)) {
33
+ throw new TypeError(`webhook registry: ${label} maxAttempts must be a whole number ≥ 1`);
34
+ }
35
+ byTopic.set(key, [...registered, registration]);
36
+ }
37
+ const settled = new Set();
38
+ for (const { source, topic, quietPeriodSeconds } of topics) {
39
+ const key = topicKey(source, topic);
40
+ if (!byTopic.has(key)) {
41
+ throw new TypeError(`webhook registry: ${source} ${topic} has settings but no use case`);
42
+ }
43
+ if (settled.has(key)) {
44
+ throw new TypeError(`webhook registry: ${source} ${topic} has settings twice`);
45
+ }
46
+ settled.add(key);
47
+ checkDuration(`${source} ${topic}`, 'quietPeriodSeconds', quietPeriodSeconds);
48
+ }
49
+ return {
50
+ useCases,
51
+ topics,
52
+ useCasesFor: (source, topic) => byTopic.get(topicKey(source, topic)) ?? [],
53
+ };
54
+ }
55
+ // JSON, so no source or topic can collide with another through a separator.
56
+ const topicKey = (source, topic) => JSON.stringify([source, topic]);