@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,80 @@
1
+ import type { Clock, DeploymentIdentity, MessageId, Queue, QueueBatch, QueueConsumer, SendOptions } from '../../contracts/index.js';
2
+ import type { QueueBinding, QueueMessageBatch } from './bindings.js';
3
+ /**
4
+ * What actually goes on the wire.
5
+ *
6
+ * Cloudflare's producer takes a body and nothing else: `send()` returns queue
7
+ * metrics, not an id, and there is nowhere to attach a header. So the three
8
+ * things `QueueMessage` promises and the platform does not carry — the id the
9
+ * caller was given, when it was enqueued, and WHICH DEPLOYMENT sent it — travel
10
+ * inside the body.
11
+ *
12
+ * `v` is a version marker. The day this shape changes, a consumer will be
13
+ * draining messages of both shapes for as long as the retention window, and a
14
+ * field that says which is which costs one byte now and a rewrite later.
15
+ */
16
+ export type Envelope<T> = {
17
+ readonly v: 1;
18
+ readonly id: MessageId;
19
+ readonly body: T;
20
+ readonly enqueuedAt: string;
21
+ readonly identity: DeploymentIdentity;
22
+ };
23
+ export type CloudflareQueueOptions = {
24
+ readonly queue: QueueBinding<Envelope<unknown>>;
25
+ readonly clock: Clock;
26
+ readonly identity: DeploymentIdentity;
27
+ readonly maxDelaySeconds: number;
28
+ readonly maxBytes: number;
29
+ readonly batchMaxMessages: number;
30
+ readonly batchMaxBytes: number;
31
+ };
32
+ /**
33
+ * Queue over a Cloudflare Queues producer binding.
34
+ *
35
+ * EVERY CEILING IS CHECKED HERE, BEFORE THE CALL, and none of them is clamped.
36
+ * That is not defensive habit: in workerd the platform enforces none of its own
37
+ * documented limits. A `delaySeconds` of 86,401, a 200 KB body and a
38
+ * 150-message batch were all accepted locally without complaint — see
39
+ * docs/platform-facts.md. An adapter that leaves this to the platform passes
40
+ * every local test and fails once deployed, which is the exact failure the
41
+ * manifest exists to prevent.
42
+ */
43
+ export declare class CloudflareQueue<T> implements Queue<T> {
44
+ #private;
45
+ private readonly o;
46
+ constructor(o: CloudflareQueueOptions);
47
+ send(body: T, options?: SendOptions): Promise<MessageId>;
48
+ sendBatch(bodies: readonly T[], options?: SendOptions): Promise<readonly MessageId[]>;
49
+ }
50
+ /**
51
+ * The consumer half: Cloudflare's `MessageBatch` as the contract's `QueueBatch`.
52
+ *
53
+ * ACKNOWLEDGEMENT IS PER MESSAGE. The returned batch has no `ackAll` and no
54
+ * `retryAll`, however convenient they look and however much the Cloudflare
55
+ * batch underneath offers them — a batch of ten where the fourth fails must
56
+ * leave nine acknowledged and one retried, and a convenience that makes the
57
+ * wrong thing a one-liner does not belong on the interface.
58
+ *
59
+ * Reordering stays permitted. Nothing here sorts, buffers or re-sequences: the
60
+ * contract says delivery MAY reorder, and an adapter that quietly guaranteed
61
+ * more would have callers depending on it by the time it stopped being true.
62
+ */
63
+ export declare function toQueueBatch<T>(batch: QueueMessageBatch<Envelope<T>>): QueueBatch<T>;
64
+ /**
65
+ * Runs `consumer` on the batch, then retries every message it neither acked
66
+ * nor retried. Cloudflare acks those implicitly when the handler returns, so
67
+ * without this a forgotten settle loses the message here and redelivers it on
68
+ * every other adapter. A consumer that throws settles nothing, and Cloudflare
69
+ * retries the whole batch.
70
+ */
71
+ export declare function consumeQueueBatch<T>(batch: QueueMessageBatch<Envelope<T>>, consumer: QueueConsumer<T>): Promise<void>;
72
+ /**
73
+ * Cloudflare's `sendBatch` caps, which are NOT manifest fields — `ToolManifest`
74
+ * has no batch shape, and adding one is a contract change with its own issue.
75
+ * They live here so the adapter can enforce them, and they carry rows in
76
+ * docs/platform-facts.md like everything else.
77
+ */
78
+ export declare const QUEUE_BATCH_MAX_MESSAGES = 100;
79
+ /** "256KB in total", read as 1,000-byte KB for the same reason as the message cap. */
80
+ export declare const QUEUE_BATCH_MAX_BYTES = 256000;
@@ -0,0 +1,177 @@
1
+ import { LimitExceeded, checkDuration } from '../../contracts/index.js';
2
+ import { toFault } from './faults.js';
3
+ const TOOL = 'queue';
4
+ const sizeOf = (envelope) => new TextEncoder().encode(JSON.stringify(envelope)).byteLength;
5
+ /**
6
+ * Queue over a Cloudflare Queues producer binding.
7
+ *
8
+ * EVERY CEILING IS CHECKED HERE, BEFORE THE CALL, and none of them is clamped.
9
+ * That is not defensive habit: in workerd the platform enforces none of its own
10
+ * documented limits. A `delaySeconds` of 86,401, a 200 KB body and a
11
+ * 150-message batch were all accepted locally without complaint — see
12
+ * docs/platform-facts.md. An adapter that leaves this to the platform passes
13
+ * every local test and fails once deployed, which is the exact failure the
14
+ * manifest exists to prevent.
15
+ */
16
+ export class CloudflareQueue {
17
+ o;
18
+ constructor(o) {
19
+ this.o = o;
20
+ }
21
+ async send(body, options) {
22
+ const delaySeconds = this.#checkedDelay(options);
23
+ const envelope = this.#wrap(body);
24
+ this.#checkSize(envelope);
25
+ await this.#call('send', async () => this.o.queue.send(envelope, delaySeconds === undefined ? {} : { delaySeconds }));
26
+ return envelope.id;
27
+ }
28
+ async sendBatch(bodies, options) {
29
+ // No round trip to send nothing. Cloudflare would accept the empty batch;
30
+ // the caller still gets billed for the request.
31
+ if (bodies.length === 0) {
32
+ return [];
33
+ }
34
+ const delaySeconds = this.#checkedDelay(options);
35
+ if (bodies.length > this.o.batchMaxMessages) {
36
+ // THROWN, NOT SPLIT. Splitting would turn one call into several
37
+ // independent ones, so a failure halfway leaves some messages sent and
38
+ // the caller holding a rejected promise with no way to know which. It is
39
+ // also the batch equivalent of clamping a delay, and the contract is
40
+ // explicit that a ceiling is reported rather than quietly worked around.
41
+ throw new LimitExceeded(TOOL, `batch of ${bodies.length} messages exceeds the ${this.o.batchMaxMessages} the target accepts`);
42
+ }
43
+ const envelopes = bodies.map((b) => this.#wrap(b));
44
+ let total = 0;
45
+ for (const envelope of envelopes) {
46
+ total += this.#checkSize(envelope);
47
+ }
48
+ if (total > this.o.batchMaxBytes) {
49
+ throw new LimitExceeded(TOOL, `batch of ${total} bytes exceeds the ${this.o.batchMaxBytes} the target accepts`);
50
+ }
51
+ await this.#call('sendBatch', async () => this.o.queue.sendBatch(envelopes.map((body) => ({ body })), delaySeconds === undefined ? {} : { delaySeconds }));
52
+ return envelopes.map((e) => e.id);
53
+ }
54
+ #wrap(body) {
55
+ return {
56
+ v: 1,
57
+ // The platform generates an id server-side and shows it only to the
58
+ // consumer, so the sender would never learn it. This one is the sender's,
59
+ // and it is what comes back on delivery.
60
+ id: crypto.randomUUID(),
61
+ body,
62
+ enqueuedAt: new Date(this.o.clock.now()).toISOString(),
63
+ identity: this.o.identity,
64
+ };
65
+ }
66
+ #checkedDelay(options) {
67
+ const delaySeconds = options?.delaySeconds;
68
+ if (delaySeconds === undefined) {
69
+ return undefined;
70
+ }
71
+ // Before the ceiling check, which cannot catch it: NaN > maxDelaySeconds is
72
+ // false, so a NaN delay would reach the platform and produce a message that
73
+ // is never visible and therefore never delivered.
74
+ checkDuration(TOOL, 'delaySeconds', delaySeconds);
75
+ if (delaySeconds > this.o.maxDelaySeconds) {
76
+ throw new LimitExceeded(TOOL, `delaySeconds ${delaySeconds} exceeds queueDelayMaxSeconds ${this.o.maxDelaySeconds}`);
77
+ }
78
+ return delaySeconds;
79
+ }
80
+ /** Returns the size, so a batch can total what it has already checked. */
81
+ #checkSize(envelope) {
82
+ // The ENVELOPE is measured, not the caller's body. The identity and the
83
+ // timestamps are on the wire and count against the platform's limit, so
84
+ // measuring the body alone would under-report by exactly the amount this
85
+ // adapter added.
86
+ const bytes = sizeOf(envelope);
87
+ if (bytes > this.o.maxBytes) {
88
+ throw new LimitExceeded(TOOL, `message of ${bytes} bytes exceeds messageMaxBytes ${this.o.maxBytes}`);
89
+ }
90
+ return bytes;
91
+ }
92
+ async #call(operation, f) {
93
+ try {
94
+ return await f();
95
+ }
96
+ catch (e) {
97
+ throw toFault(TOOL, operation, e);
98
+ }
99
+ }
100
+ }
101
+ /**
102
+ * The consumer half: Cloudflare's `MessageBatch` as the contract's `QueueBatch`.
103
+ *
104
+ * ACKNOWLEDGEMENT IS PER MESSAGE. The returned batch has no `ackAll` and no
105
+ * `retryAll`, however convenient they look and however much the Cloudflare
106
+ * batch underneath offers them — a batch of ten where the fourth fails must
107
+ * leave nine acknowledged and one retried, and a convenience that makes the
108
+ * wrong thing a one-liner does not belong on the interface.
109
+ *
110
+ * Reordering stays permitted. Nothing here sorts, buffers or re-sequences: the
111
+ * contract says delivery MAY reorder, and an adapter that quietly guaranteed
112
+ * more would have callers depending on it by the time it stopped being true.
113
+ */
114
+ export function toQueueBatch(batch) {
115
+ // Keyed by OUR id, the one send() returned, so the caller can acknowledge a
116
+ // message using the identifier they already hold.
117
+ const platform = new Map();
118
+ const messages = batch.messages.map((m) => {
119
+ platform.set(m.body.id, m);
120
+ return {
121
+ id: m.body.id,
122
+ body: m.body.body,
123
+ // Cloudflare's own counter: 1 on first delivery, incremented on retry.
124
+ attempt: m.attempts,
125
+ enqueuedAt: m.body.enqueuedAt,
126
+ identity: m.body.identity,
127
+ };
128
+ });
129
+ return {
130
+ messages,
131
+ ack: (id) => {
132
+ platform.get(id)?.ack();
133
+ },
134
+ retry: (id, options) => {
135
+ const delaySeconds = options?.delaySeconds;
136
+ platform
137
+ .get(id)
138
+ ?.retry(delaySeconds === undefined ? {} : { delaySeconds });
139
+ },
140
+ };
141
+ }
142
+ /**
143
+ * Runs `consumer` on the batch, then retries every message it neither acked
144
+ * nor retried. Cloudflare acks those implicitly when the handler returns, so
145
+ * without this a forgotten settle loses the message here and redelivers it on
146
+ * every other adapter. A consumer that throws settles nothing, and Cloudflare
147
+ * retries the whole batch.
148
+ */
149
+ export async function consumeQueueBatch(batch, consumer) {
150
+ const inner = toQueueBatch(batch);
151
+ const settled = new Set();
152
+ await consumer({
153
+ messages: inner.messages,
154
+ ack: (id) => {
155
+ settled.add(id);
156
+ inner.ack(id);
157
+ },
158
+ retry: (id, options) => {
159
+ settled.add(id);
160
+ inner.retry(id, options);
161
+ },
162
+ });
163
+ for (const m of inner.messages) {
164
+ if (!settled.has(m.id)) {
165
+ inner.retry(m.id);
166
+ }
167
+ }
168
+ }
169
+ /**
170
+ * Cloudflare's `sendBatch` caps, which are NOT manifest fields — `ToolManifest`
171
+ * has no batch shape, and adding one is a contract change with its own issue.
172
+ * They live here so the adapter can enforce them, and they carry rows in
173
+ * docs/platform-facts.md like everything else.
174
+ */
175
+ export const QUEUE_BATCH_MAX_MESSAGES = 100;
176
+ /** "256KB in total", read as 1,000-byte KB for the same reason as the message cap. */
177
+ export const QUEUE_BATCH_MAX_BYTES = 256_000;
@@ -0,0 +1,24 @@
1
+ import type { BlobStore, Clock } from '../../contracts/index.js';
2
+ import { type SweepOptions } from '../retention.js';
3
+ export { DEFAULT_RETENTION_SECONDS, type SweepOptions } from '../retention.js';
4
+ export type CloudflareSweepDeps = {
5
+ readonly db: D1Database;
6
+ readonly clock: Clock;
7
+ };
8
+ /** Deletes one batch of ledger claims whose lease ended `olderThanSeconds` ago. */
9
+ export declare function sweepLedger(deps: CloudflareSweepDeps, options?: SweepOptions): Promise<number>;
10
+ /**
11
+ * Deletes one batch of webhook receipts past retention, and their raw bodies.
12
+ * Bodies go first: a crash after them leaves rows the next sweep finishes, and
13
+ * deleting a missing blob is a no-op. Returns how many deliveries it deleted.
14
+ */
15
+ export declare function sweepWebhookReceipts(deps: CloudflareSweepDeps & {
16
+ readonly blobStore: BlobStore;
17
+ }, options?: SweepOptions): Promise<number>;
18
+ /** For the query-plan tests, as the journal exports its own. */
19
+ export declare const RETENTION_QUERIES: {
20
+ readonly sweepLedger: "\n DELETE FROM ledger_claims WHERE expires_at < ?1 AND key IN (\n SELECT key FROM ledger_claims WHERE expires_at < ?1\n ORDER BY expires_at LIMIT ?2\n )\n";
21
+ readonly sweptDeliveries: "\n SELECT delivery_id, body_key FROM webhook_deliveries d\n WHERE received_at < ?1 AND NOT EXISTS (\n SELECT 1 FROM webhook_tasks t\n WHERE t.delivery_id = d.delivery_id AND t.state NOT IN ('done', 'dead')\n )\n ORDER BY received_at LIMIT ?2\n";
22
+ readonly deleteTasks: "\n DELETE FROM webhook_tasks\n WHERE delivery_id IN (SELECT value FROM json_each(?1))\n AND NOT EXISTS (\n SELECT 1 FROM webhook_tasks k\n WHERE k.delivery_id = webhook_tasks.delivery_id\n AND k.state NOT IN ('done', 'dead')\n )\n";
23
+ readonly deleteDeliveries: "\n DELETE FROM webhook_deliveries\n WHERE delivery_id IN (SELECT value FROM json_each(?1))\n AND NOT EXISTS (\n SELECT 1 FROM webhook_tasks t\n WHERE t.delivery_id = webhook_deliveries.delivery_id\n )\n";
24
+ };
@@ -0,0 +1,103 @@
1
+ import { sweepBounds } from '../retention.js';
2
+ import { toFault } from './faults.js';
3
+ export { DEFAULT_RETENTION_SECONDS } from '../retention.js';
4
+ /**
5
+ * Not a Ledger method: the Ledger has no surface beyond claim, complete and
6
+ * release (#113). A completed claim's `expires_at` is already its long TTL, so
7
+ * a row past `expires_at` holds nothing, live lease or completion alike.
8
+ */
9
+ // The outer expiry check matters on Postgres (its twin says why); here D1
10
+ // serializes writes, and it keeps the two statements the same.
11
+ const SWEEP_LEDGER = `
12
+ DELETE FROM ledger_claims WHERE expires_at < ?1 AND key IN (
13
+ SELECT key FROM ledger_claims WHERE expires_at < ?1
14
+ ORDER BY expires_at LIMIT ?2
15
+ )
16
+ `;
17
+ /**
18
+ * Only a delivery whose every task is final: `done`, or `dead`, which 0010's
19
+ * 30 days exist to replay. Any other task still needs the body.
20
+ */
21
+ const SWEPT_DELIVERIES = `
22
+ SELECT delivery_id, body_key FROM webhook_deliveries d
23
+ WHERE received_at < ?1 AND NOT EXISTS (
24
+ SELECT 1 FROM webhook_tasks t
25
+ WHERE t.delivery_id = d.delivery_id AND t.state NOT IN ('done', 'dead')
26
+ )
27
+ ORDER BY received_at LIMIT ?2
28
+ `;
29
+ // One bound parameter, the ids as a JSON array: D1 allows 100 per query.
30
+ // Final checked again: a replay may move a task dead → replayed while the
31
+ // bodies are deleted. Its rows then stay, and its retry fails visibly.
32
+ // Correlated, so it searches the primary key per delivery, not every task.
33
+ const DELETE_TASKS = `
34
+ DELETE FROM webhook_tasks
35
+ WHERE delivery_id IN (SELECT value FROM json_each(?1))
36
+ AND NOT EXISTS (
37
+ SELECT 1 FROM webhook_tasks k
38
+ WHERE k.delivery_id = webhook_tasks.delivery_id
39
+ AND k.state NOT IN ('done', 'dead')
40
+ )
41
+ `;
42
+ // Runs after DELETE_TASKS, so a delivery that kept a task keeps its row.
43
+ const DELETE_DELIVERIES = `
44
+ DELETE FROM webhook_deliveries
45
+ WHERE delivery_id IN (SELECT value FROM json_each(?1))
46
+ AND NOT EXISTS (
47
+ SELECT 1 FROM webhook_tasks t
48
+ WHERE t.delivery_id = webhook_deliveries.delivery_id
49
+ )
50
+ `;
51
+ /** Deletes one batch of ledger claims whose lease ended `olderThanSeconds` ago. */
52
+ export async function sweepLedger(deps, options = {}) {
53
+ const { cutoff, limit } = sweepBounds('ledger', deps.clock, options, 1_000);
54
+ try {
55
+ const result = await deps.db.prepare(SWEEP_LEDGER).bind(cutoff, limit).run();
56
+ return result.meta.changes;
57
+ }
58
+ catch (e) {
59
+ throw toFault('ledger', 'sweepLedger', e);
60
+ }
61
+ }
62
+ /**
63
+ * Deletes one batch of webhook receipts past retention, and their raw bodies.
64
+ * Bodies go first: a crash after them leaves rows the next sweep finishes, and
65
+ * deleting a missing blob is a no-op. Returns how many deliveries it deleted.
66
+ */
67
+ export async function sweepWebhookReceipts(deps, options = {}) {
68
+ const { cutoff, limit } = sweepBounds('journal', deps.clock, options, 100);
69
+ let rows;
70
+ try {
71
+ ;
72
+ ({ results: rows } = await deps.db
73
+ .prepare(SWEPT_DELIVERIES)
74
+ .bind(cutoff, limit)
75
+ .all());
76
+ }
77
+ catch (e) {
78
+ throw toFault('journal', 'sweepWebhookReceipts', e);
79
+ }
80
+ if (rows.length === 0) {
81
+ return 0;
82
+ }
83
+ await Promise.all(rows.map(async (r) => deps.blobStore.delete(r.body_key)));
84
+ const ids = JSON.stringify(rows.map((r) => r.delivery_id));
85
+ try {
86
+ // One batch, so a delivery never outlives its tasks or the reverse.
87
+ await deps.db.batch([
88
+ deps.db.prepare(DELETE_TASKS).bind(ids),
89
+ deps.db.prepare(DELETE_DELIVERIES).bind(ids),
90
+ ]);
91
+ }
92
+ catch (e) {
93
+ throw toFault('journal', 'sweepWebhookReceipts', e);
94
+ }
95
+ return rows.length;
96
+ }
97
+ /** For the query-plan tests, as the journal exports its own. */
98
+ export const RETENTION_QUERIES = {
99
+ sweepLedger: SWEEP_LEDGER,
100
+ sweptDeliveries: SWEPT_DELIVERIES,
101
+ deleteTasks: DELETE_TASKS,
102
+ deleteDeliveries: DELETE_DELIVERIES,
103
+ };
@@ -0,0 +1,27 @@
1
+ import type { Session } from '@shopify/shopify-api';
2
+ import type { SessionStorage } from '../../contracts/index.js';
3
+ export type CloudflareSessionStorageOptions = {
4
+ readonly db: D1Database;
5
+ /**
6
+ * The raw secret from Worker secrets — base64, decoding to 32 bytes. Not a
7
+ * CryptoKey: importing is async and the constructor stays synchronous,
8
+ * matching CloudflareLedger/CloudflareJournal.
9
+ */
10
+ readonly key: string;
11
+ };
12
+ export declare class CloudflareSessionStorage implements SessionStorage {
13
+ #private;
14
+ private readonly o;
15
+ constructor(o: CloudflareSessionStorageOptions);
16
+ storeSession(session: Session): Promise<boolean>;
17
+ loadSession(id: string): Promise<Session | undefined>;
18
+ /**
19
+ * Matches Shopify's own MemorySessionStorage: unconditionally true, even
20
+ * when the id was never stored. A DELETE that affects zero rows is not a
21
+ * fault, and callers — including Shopify's own OAuth flow — rely on the
22
+ * boolean meaning "the session is gone," not "a row existed."
23
+ */
24
+ deleteSession(id: string): Promise<boolean>;
25
+ deleteSessions(ids: string[]): Promise<boolean>;
26
+ findSessionsByShop(shop: string): Promise<Session[]>;
27
+ }
@@ -0,0 +1,78 @@
1
+ import { SessionEnvelope } from '../session-envelope.js';
2
+ import { toFault } from './faults.js';
3
+ const TOOL = 'sessions';
4
+ /**
5
+ * Every query this adapter can run. `id` and `shop` are the only plaintext
6
+ * columns — the only two things SessionStorage ever looks up by.
7
+ */
8
+ const Q = {
9
+ store: `
10
+ INSERT INTO shopify_sessions (id, shop, version, iv, ciphertext)
11
+ VALUES (?1, ?2, ?3, ?4, ?5)
12
+ ON CONFLICT(id) DO UPDATE SET
13
+ shop = ?2, version = ?3, iv = ?4, ciphertext = ?5
14
+ `,
15
+ load: `SELECT shop, version, iv, ciphertext FROM shopify_sessions WHERE id = ?1`,
16
+ deleteOne: `DELETE FROM shopify_sessions WHERE id = ?1`,
17
+ findByShop: `
18
+ SELECT id, shop, version, iv, ciphertext FROM shopify_sessions WHERE shop = ?1
19
+ `,
20
+ };
21
+ const toBytes = (value) => value instanceof ArrayBuffer
22
+ ? new Uint8Array(value)
23
+ : Uint8Array.from(value);
24
+ export class CloudflareSessionStorage {
25
+ o;
26
+ #envelope;
27
+ constructor(o) {
28
+ this.o = o;
29
+ this.#envelope = new SessionEnvelope(o.key);
30
+ }
31
+ async storeSession(session) {
32
+ const { version, iv, ciphertext } = await this.#envelope.seal(session);
33
+ await this.#call('storeSession', async () => this.o.db
34
+ .prepare(Q.store)
35
+ .bind(session.id, session.shop, version, iv, ciphertext)
36
+ .run());
37
+ return true;
38
+ }
39
+ async loadSession(id) {
40
+ const row = await this.#call('loadSession', async () => this.o.db.prepare(Q.load).bind(id).first());
41
+ if (row === null) {
42
+ return undefined;
43
+ }
44
+ return this.#envelope.open(id, row.shop, toBytes(row.iv), toBytes(row.ciphertext));
45
+ }
46
+ /**
47
+ * Matches Shopify's own MemorySessionStorage: unconditionally true, even
48
+ * when the id was never stored. A DELETE that affects zero rows is not a
49
+ * fault, and callers — including Shopify's own OAuth flow — rely on the
50
+ * boolean meaning "the session is gone," not "a row existed."
51
+ */
52
+ async deleteSession(id) {
53
+ await this.#call('deleteSession', async () => this.o.db.prepare(Q.deleteOne).bind(id).run());
54
+ return true;
55
+ }
56
+ async deleteSessions(ids) {
57
+ if (ids.length === 0) {
58
+ return true;
59
+ }
60
+ await this.#call('deleteSessions', async () => this.o.db.batch(ids.map((id) => this.o.db.prepare(Q.deleteOne).bind(id))));
61
+ return true;
62
+ }
63
+ async findSessionsByShop(shop) {
64
+ const { results } = await this.#call('findSessionsByShop', async () => this.o.db
65
+ .prepare(Q.findByShop)
66
+ .bind(shop)
67
+ .all());
68
+ return Promise.all(results.map(async (row) => this.#envelope.open(row.id, row.shop, toBytes(row.iv), toBytes(row.ciphertext))));
69
+ }
70
+ async #call(operation, f) {
71
+ try {
72
+ return await f();
73
+ }
74
+ catch (e) {
75
+ throw toFault(TOOL, operation, e);
76
+ }
77
+ }
78
+ }
@@ -0,0 +1,16 @@
1
+ import type { DeploymentIdentity, Toolkit } from '../../contracts/index.js';
2
+ import type { QueueBinding } from './bindings.js';
3
+ import { type Envelope } from './queue.js';
4
+ export type CloudflareToolkitOptions = {
5
+ readonly identity: DeploymentIdentity;
6
+ readonly correlationId?: string;
7
+ };
8
+ /**
9
+ * The bindings the toolkit reads. `WEBHOOK_QUEUE` is optional because an app
10
+ * compiles this file against its own `Env`, and one built before the webhook
11
+ * queue existed has no such binding.
12
+ */
13
+ export type CloudflareToolkitEnv = Omit<Env, 'WEBHOOK_QUEUE'> & {
14
+ readonly WEBHOOK_QUEUE?: QueueBinding<Envelope<unknown>>;
15
+ };
16
+ export declare function createCloudflareToolkit<QueueBody = unknown, WebhookBody = unknown>(env: CloudflareToolkitEnv, o: CloudflareToolkitOptions): Toolkit<QueueBody, WebhookBody>;
@@ -0,0 +1,57 @@
1
+ import { Misconfigured } from '../../contracts/index.js';
2
+ import { systemClock } from '../system-clock.js';
3
+ import { CloudflareBlobStore } from './blob-store.js';
4
+ import { CloudflareCache } from './cache.js';
5
+ import { CloudflareJournal } from './journal.js';
6
+ import { CloudflareLedger } from './ledger.js';
7
+ import { CloudflareLogger } from './logger.js';
8
+ import { CLOUDFLARE_MANIFEST } from './manifest.js';
9
+ import { CloudflareQueue, QUEUE_BATCH_MAX_BYTES, QUEUE_BATCH_MAX_MESSAGES, } from './queue.js';
10
+ /**
11
+ * `webhookQueue` without its binding. The toolkit still builds, so an app that
12
+ * never sends a webhook pointer keeps working, and one that does is told what
13
+ * is missing rather than handed a TypeError.
14
+ */
15
+ const unboundQueue = (binding) => {
16
+ const fail = async () => {
17
+ throw new Misconfigured('queue', `no ${binding} producer binding in wrangler.jsonc`);
18
+ };
19
+ return { send: fail, sendBatch: fail };
20
+ };
21
+ export function createCloudflareToolkit(env, o) {
22
+ const clock = systemClock();
23
+ const logger = new CloudflareLogger(o.identity, o.correlationId ?? crypto.randomUUID());
24
+ const queueOptions = {
25
+ clock,
26
+ identity: o.identity,
27
+ maxDelaySeconds: CLOUDFLARE_MANIFEST.queueDelayMaxSeconds,
28
+ maxBytes: CLOUDFLARE_MANIFEST.messageMaxBytes,
29
+ batchMaxMessages: QUEUE_BATCH_MAX_MESSAGES,
30
+ batchMaxBytes: QUEUE_BATCH_MAX_BYTES,
31
+ };
32
+ return {
33
+ cache: new CloudflareCache({
34
+ kv: env.CACHE,
35
+ clock,
36
+ minTtlSeconds: CLOUDFLARE_MANIFEST.cacheMinTtlSeconds,
37
+ }),
38
+ blobStore: new CloudflareBlobStore({
39
+ bucket: env.BLOBS,
40
+ maxBytes: CLOUDFLARE_MANIFEST.blobMaxBytes,
41
+ }),
42
+ queue: new CloudflareQueue({
43
+ ...queueOptions,
44
+ queue: env.QUEUE,
45
+ }),
46
+ webhookQueue: env.WEBHOOK_QUEUE === undefined
47
+ ? unboundQueue('WEBHOOK_QUEUE')
48
+ : new CloudflareQueue({
49
+ ...queueOptions,
50
+ queue: env.WEBHOOK_QUEUE,
51
+ }),
52
+ ledger: new CloudflareLedger({ db: env.DB, clock }),
53
+ journal: new CloudflareJournal({ db: env.DB, logger }),
54
+ logger,
55
+ clock,
56
+ };
57
+ }
@@ -0,0 +1,57 @@
1
+ import { WorkflowEntrypoint } from 'cloudflare:workers';
2
+ import type { JobRegistration, Jobs, JsonValue, RunId } from '../../contracts/index.js';
3
+ /**
4
+ * DURABLE JOBS ON CLOUDFLARE WORKFLOWS.
5
+ *
6
+ * Two halves, over one Workflow binding:
7
+ *
8
+ * - `workflowJobsEntrypoint` returns ONE GENERIC `WorkflowEntrypoint` class
9
+ * that runs every registered Job. It finds the Job from the instance id's
10
+ * prefix: a Job name has no `-`, so the id's first `-` ends the name
11
+ * (`JobInstanceId`). Export it from the Worker's main module and bind it as
12
+ * a Workflow.
13
+ * - `createWorkflowJobs` is the `Jobs` a route calls. It creates and reads
14
+ * instances through that binding.
15
+ *
16
+ * One binding serves every Job. Workflows scopes ids to a binding and
17
+ * `status(id)` takes no Job name, so a binding per Job would make `status`
18
+ * guess which binding to ask.
19
+ *
20
+ * THE CLASS HOLDS NO JOB LOGIC. Every step is one `step.do` with the step's
21
+ * own retries and timeout, and the exhaustion handler is one more. Deployed
22
+ * Workflows replays `run()` after a suspension and local Workflows does not
23
+ * (docs/spikes/cloudflare-workflows.md, "Three more findings"), so the code
24
+ * between the `step.do` calls only reads the event and what earlier
25
+ * `step.do` calls returned. A test that passes locally does not prove this.
26
+ */
27
+ /** What an instance is created with. The id carries the Job name and key. */
28
+ export type WorkflowJobsParams = {
29
+ readonly input: JsonValue;
30
+ readonly runId: RunId;
31
+ };
32
+ /** The Workflow binding the executor creates and reads instances through. */
33
+ export type JobsWorkflow = Workflow<WorkflowJobsParams>;
34
+ export type WorkflowJobsEntrypointOptions = {
35
+ /** Defaults to `CLOUDFLARE_MANIFEST.stepResultMaxBytes`, 1 MiB. */
36
+ readonly stepResultMaxBytes?: number;
37
+ };
38
+ /**
39
+ * The generic Workflow class. `registrations` is called with the Worker's
40
+ * `env` in each invocation, so a deps builder can close over the bindings:
41
+ *
42
+ * export const JobsWorkflow = workflowJobsEntrypoint((env: Env) => [
43
+ * (register) => register(selfSignUp, () => createSignUpDeps(env)),
44
+ * ])
45
+ *
46
+ * It must return the same registrations `createWorkflowJobs` was given.
47
+ */
48
+ export declare function workflowJobsEntrypoint<Env>(registrations: (env: Env) => readonly JobRegistration[], options?: WorkflowJobsEntrypointOptions): new (ctx: ExecutionContext, env: Env) => WorkflowEntrypoint<Env, WorkflowJobsParams>;
49
+ export type WorkflowJobsOptions = {
50
+ readonly workflow: JobsWorkflow;
51
+ readonly registrations: readonly JobRegistration[];
52
+ };
53
+ /**
54
+ * `Jobs` over the Workflow binding that `workflowJobsEntrypoint`'s class is
55
+ * bound to. Throws when it is built if a registration's name breaks the rule.
56
+ */
57
+ export declare function createWorkflowJobs(options: WorkflowJobsOptions): Jobs;