@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
package/README.md CHANGED
@@ -1,3 +1,51 @@
1
- # Temporary Holding Version
1
+ # TVA Library
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **The platform primitives a Shopify React Router app does not come with** — caching, blob storage, queues, durable pipelines, an idempotency ledger, and a run journal you can actually read — behind interfaces that survive changing platform.
4
+
5
+ **Status: early. Built alongside a real engagement, not ahead of one.**
6
+
7
+ ---
8
+
9
+ ## The problem
10
+
11
+ Shopify's React Router app template is an excellent server-rendered admin UI and backend-for-frontend, and it stops there. No cache, no blob storage, no queue, no straightforward way to use a database. So application data ends up in Shopify metafields, where it cannot be queried, indexed or audited.
12
+
13
+ **The doctrine this ships with, and it matters more than the code:**
14
+
15
+ > **Shopify remains the system of record for commerce objects.** Products, customers, companies, orders.
16
+ >
17
+ > **This library's store holds what your app knows about its own work.** Runs, decisions, reason codes, idempotency claims, receipts, configuration.
18
+ >
19
+ > **If a fact exists in both, Shopify wins, and ours is a cache with a stated staleness budget.**
20
+
21
+ ---
22
+
23
+ ## Layout
24
+
25
+ ```
26
+ src/
27
+ contracts/ tool interfaces and their conformance suites. Zero dependencies
28
+ adapters/
29
+ memory/ in-process. Every test runs against it. Passes the suite
30
+ examples/
31
+ cloudflare/ a real engagement, importing the library
32
+ docs/
33
+ design.md what this is, how it is layered, and what it refuses
34
+ operator-ledger.md the run journal, and the screens that read it
35
+ etl.md a worked ETL design
36
+ ```
37
+
38
+ **`src/contracts/` imports nothing.** Not an adapter, not a vendor SDK, not a third-party package. That one rule is the portability story; everything else follows from it.
39
+
40
+ **Two implementations of every interface, from day one.** The memory adapter is not extra work — the first test needs it — and two implementations passing one suite is the only evidence available that an interface is not one vendor's API in disguise.
41
+
42
+ ---
43
+
44
+ ## Getting started
45
+
46
+ ```bash
47
+ npm install
48
+ npm run check # lint, typecheck, test
49
+ ```
50
+
51
+ Contributing, and how commits and pull requests are written here: **`CONTRIBUTING.md`**.
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Aliases for the Cloudflare binding types this adapter names.
3
+ *
4
+ * `Queue` is both a Cloudflare global and one of our contracts, and a module
5
+ * that imports ours cannot then name the global — the import shadows it for the
6
+ * whole file. This module imports nothing, so the globals are visible here and
7
+ * the collision is resolved once rather than worked around in each file.
8
+ */
9
+ export type QueueBinding<Body = unknown> = Queue<Body>;
10
+ export type QueueMessageBatch<Body = unknown> = MessageBatch<Body>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,39 @@
1
+ import type { BlobKey, BlobStore, PutOptions } from '../../contracts/index.js';
2
+ export type CloudflareBlobStoreOptions = {
3
+ readonly bucket: R2Bucket;
4
+ readonly maxBytes: number;
5
+ };
6
+ /**
7
+ * BlobStore over an R2 bucket.
8
+ *
9
+ * Two things R2 gives away for free that an emulation would get wrong, and are
10
+ * therefore NOT re-implemented here:
11
+ *
12
+ * - `prefix` is a string prefix. R2 has no directories, so `a/` does not
13
+ * match `ab` without anybody arranging for it.
14
+ * - `delete` on a key that does not exist resolves. A retry after an
15
+ * ambiguous response is safe.
16
+ *
17
+ * The one thing R2 does NOT give away is a complete listing: `list` returns at
18
+ * most 1,000 keys and truncates silently. See `list` below.
19
+ */
20
+ export declare class CloudflareBlobStore implements BlobStore {
21
+ #private;
22
+ private readonly o;
23
+ constructor(o: CloudflareBlobStoreOptions);
24
+ put(key: BlobKey, body: Uint8Array | string, options?: PutOptions): Promise<void>;
25
+ get(key: BlobKey): Promise<Uint8Array | undefined>;
26
+ getText(key: BlobKey): Promise<string | undefined>;
27
+ delete(key: BlobKey): Promise<void>;
28
+ /**
29
+ * Pages to completion.
30
+ *
31
+ * R2 returns at most 1,000 keys and sets `truncated`. One un-paged `list()`
32
+ * returns a partial answer WITH NO ERROR, which is the worst shape a bug can
33
+ * take: the caller gets a plausible list and no reason to doubt it.
34
+ *
35
+ * `truncated` is the signal, not a short page — the documentation is explicit
36
+ * that comparing the count against the limit is the wrong check.
37
+ */
38
+ list(prefix: string): Promise<readonly BlobKey[]>;
39
+ }
@@ -0,0 +1,95 @@
1
+ import { LimitExceeded } from '../../contracts/index.js';
2
+ import { toFault } from './faults.js';
3
+ /**
4
+ * The name this tool answers to in a fault message and a log line: `blobs: put
5
+ * failed`. It matches the binding an operator reads in wrangler.jsonc, which is
6
+ * the name they will be looking at when something goes wrong.
7
+ */
8
+ const TOOL = 'blobs';
9
+ /**
10
+ * BlobStore over an R2 bucket.
11
+ *
12
+ * Two things R2 gives away for free that an emulation would get wrong, and are
13
+ * therefore NOT re-implemented here:
14
+ *
15
+ * - `prefix` is a string prefix. R2 has no directories, so `a/` does not
16
+ * match `ab` without anybody arranging for it.
17
+ * - `delete` on a key that does not exist resolves. A retry after an
18
+ * ambiguous response is safe.
19
+ *
20
+ * The one thing R2 does NOT give away is a complete listing: `list` returns at
21
+ * most 1,000 keys and truncates silently. See `list` below.
22
+ */
23
+ export class CloudflareBlobStore {
24
+ o;
25
+ constructor(o) {
26
+ this.o = o;
27
+ }
28
+ async put(key, body, options) {
29
+ // Encoded before the size check, because a string's length is characters
30
+ // and the limit is bytes. 'é' is one of the first and two of the second.
31
+ const bytes = typeof body === 'string' ? new TextEncoder().encode(body) : body;
32
+ // The ADAPTER enforces its own manifest, before the call — the same rule
33
+ // the cache follows. Reaching R2 to be told no costs a round trip and can
34
+ // fail for a second, unrelated reason on the way.
35
+ if (bytes.byteLength > this.o.maxBytes) {
36
+ throw new LimitExceeded(TOOL, `body of ${bytes.byteLength} bytes is above blobMaxBytes ${this.o.maxBytes}`);
37
+ }
38
+ // exactOptionalPropertyTypes: passing `{ contentType: undefined }` is not
39
+ // the same as passing nothing, so the absent case passes no options at all.
40
+ const contentType = options?.contentType;
41
+ await this.#call('put', async () => contentType === undefined
42
+ ? this.o.bucket.put(key, bytes)
43
+ : this.o.bucket.put(key, bytes, { httpMetadata: { contentType } }));
44
+ }
45
+ async get(key) {
46
+ return this.#call('get', async () => {
47
+ const object = await this.o.bucket.get(key);
48
+ return object === null ? undefined : await object.bytes();
49
+ });
50
+ }
51
+ async getText(key) {
52
+ return this.#call('getText', async () => {
53
+ const object = await this.o.bucket.get(key);
54
+ return object === null ? undefined : await object.text();
55
+ });
56
+ }
57
+ async delete(key) {
58
+ await this.#call('delete', async () => this.o.bucket.delete(key));
59
+ }
60
+ /**
61
+ * Pages to completion.
62
+ *
63
+ * R2 returns at most 1,000 keys and sets `truncated`. One un-paged `list()`
64
+ * returns a partial answer WITH NO ERROR, which is the worst shape a bug can
65
+ * take: the caller gets a plausible list and no reason to doubt it.
66
+ *
67
+ * `truncated` is the signal, not a short page — the documentation is explicit
68
+ * that comparing the count against the limit is the wrong check.
69
+ */
70
+ async list(prefix) {
71
+ return this.#call('list', async () => {
72
+ const keys = [];
73
+ let cursor;
74
+ for (;;) {
75
+ const page = await this.o.bucket.list(cursor === undefined ? { prefix } : { prefix, cursor });
76
+ keys.push(...page.objects.map((o) => o.key));
77
+ if (!page.truncated) {
78
+ // Sorted because the contract says sorted. R2 already orders a page
79
+ // lexicographically and pages concatenate in order, so this is a
80
+ // no-op that costs nothing and stops the contract resting on it.
81
+ return keys.sort();
82
+ }
83
+ cursor = page.cursor;
84
+ }
85
+ });
86
+ }
87
+ async #call(operation, f) {
88
+ try {
89
+ return await f();
90
+ }
91
+ catch (e) {
92
+ throw toFault(TOOL, operation, e);
93
+ }
94
+ }
95
+ }
@@ -0,0 +1,14 @@
1
+ import type { Cache, CacheKey, Clock } from '../../contracts/index.js';
2
+ export type CloudflareCacheOptions = {
3
+ readonly kv: KVNamespace;
4
+ readonly clock: Clock;
5
+ readonly minTtlSeconds: number;
6
+ };
7
+ export declare class CloudflareCache implements Cache {
8
+ #private;
9
+ private readonly o;
10
+ constructor(o: CloudflareCacheOptions);
11
+ get(key: CacheKey): Promise<string | undefined>;
12
+ put(key: CacheKey, value: string, ttlSeconds: number): Promise<void>;
13
+ delete(key: CacheKey): Promise<void>;
14
+ }
@@ -0,0 +1,48 @@
1
+ import { LimitExceeded, checkDuration, plusSeconds, } from '../../contracts/index.js';
2
+ import { toFault } from './faults.js';
3
+ export class CloudflareCache {
4
+ o;
5
+ constructor(o) {
6
+ this.o = o;
7
+ }
8
+ async get(key) {
9
+ const { value, metadata } = await this.#call('get', async () => this.o.kv.getWithMetadata(key, 'text'));
10
+ // The metadata is the hit signal, not the value: KV returns null for a
11
+ // stored empty string, and '' is a hit while undefined is a miss.
12
+ if (metadata === null) {
13
+ return undefined;
14
+ }
15
+ // Inclusive: at exactly expiresAt the value is gone. Unlike the memory
16
+ // adapter this does not delete the key — KV removes it on its own ttl, and
17
+ // a delete here would spend a write to save a read that is already right.
18
+ if (metadata.expiresAt <= this.o.clock.now()) {
19
+ return undefined;
20
+ }
21
+ return value ?? '';
22
+ }
23
+ async put(key, value, ttlSeconds) {
24
+ // Before the manifest check, which cannot catch it: NaN < minTtlSeconds is
25
+ // false, so a NaN ttl would reach KV as an expirationTtl of NaN.
26
+ checkDuration('cache', 'ttlSeconds', ttlSeconds);
27
+ // The ADAPTER enforces its own manifest, before the call. KV has its own
28
+ // floor of 60 seconds, which is what the manifest field records.
29
+ if (ttlSeconds < this.o.minTtlSeconds) {
30
+ throw new LimitExceeded('cache', `ttlSeconds ${ttlSeconds} is below cacheMinTtlSeconds ${this.o.minTtlSeconds}`);
31
+ }
32
+ const metadata = {
33
+ expiresAt: plusSeconds(this.o.clock.now(), ttlSeconds),
34
+ };
35
+ await this.#call('put', async () => this.o.kv.put(key, value, { expirationTtl: ttlSeconds, metadata }));
36
+ }
37
+ async delete(key) {
38
+ await this.#call('delete', async () => this.o.kv.delete(key));
39
+ }
40
+ async #call(operation, f) {
41
+ try {
42
+ return await f();
43
+ }
44
+ catch (e) {
45
+ throw toFault('cache', operation, e);
46
+ }
47
+ }
48
+ }
@@ -0,0 +1,7 @@
1
+ import { type ToolFault } from '../../contracts/index.js';
2
+ /**
3
+ * Unknown failures are Unavailable, which is retryable. A retryable answer to
4
+ * something permanent costs a few wasted attempts; a permanent answer to
5
+ * something transient loses the work.
6
+ */
7
+ export declare function toFault(tool: string, operation: string, e: unknown): ToolFault;
@@ -0,0 +1,39 @@
1
+ import { LimitExceeded, Misconfigured, Throttled, Unavailable, } from '../../contracts/index.js';
2
+ /**
3
+ * A Cloudflare binding reports failure as an Error whose message carries the
4
+ * HTTP status the storage service returned — for example
5
+ * `KV PUT failed: 400 Invalid expiration_ttl of 59`.
6
+ *
7
+ * That string is the only signal available, so it is read here, in one place,
8
+ * and never anywhere else. The vendor message is kept as `cause` and never
9
+ * reaches a caller's message, because a caller that reads it starts depending
10
+ * on it.
11
+ */
12
+ const STATUS = /\b(\d{3})\b/;
13
+ const statusOf = (e) => {
14
+ if (!(e instanceof Error)) {
15
+ return undefined;
16
+ }
17
+ const m = STATUS.exec(e.message);
18
+ return m?.[1] === undefined ? undefined : Number(m[1]);
19
+ };
20
+ /**
21
+ * Unknown failures are Unavailable, which is retryable. A retryable answer to
22
+ * something permanent costs a few wasted attempts; a permanent answer to
23
+ * something transient loses the work.
24
+ */
25
+ export function toFault(tool, operation, e) {
26
+ const status = statusOf(e);
27
+ const where = `${operation} failed`;
28
+ const options = { cause: e };
29
+ if (status === 429) {
30
+ return new Throttled(tool, where, options);
31
+ }
32
+ if (status === 401 || status === 403 || status === 404) {
33
+ return new Misconfigured(tool, where, options);
34
+ }
35
+ if (status !== undefined && status >= 400 && status < 500) {
36
+ return new LimitExceeded(tool, where, options);
37
+ }
38
+ return new Unavailable(tool, where, options);
39
+ }
@@ -0,0 +1,15 @@
1
+ export * from './blob-store.js';
2
+ export * from './cache.js';
3
+ export * from './faults.js';
4
+ export { createCloudflarePipelines } from './pipelines.js';
5
+ export type { CloudflarePipelines, CloudflarePipelinesOptions, } from './pipelines.js';
6
+ export type { WakeUp } from '../reference-executor.js';
7
+ export * from './journal.js';
8
+ export * from './ledger.js';
9
+ export * from './logger.js';
10
+ export * from './manifest.js';
11
+ export * from './queue.js';
12
+ export * from './retention.js';
13
+ export * from './session-storage.js';
14
+ export * from './toolkit.js';
15
+ export * from './workflow-pipelines.js';
@@ -0,0 +1,16 @@
1
+ export * from './blob-store.js';
2
+ export * from './cache.js';
3
+ export * from './faults.js';
4
+ // The executor's factory and its types, and not its store: the step state
5
+ // tables have no interface, and nothing outside the executor reads or writes
6
+ // them (docs/decisions/0006).
7
+ export { createCloudflarePipelines } from './pipelines.js';
8
+ export * from './journal.js';
9
+ export * from './ledger.js';
10
+ export * from './logger.js';
11
+ export * from './manifest.js';
12
+ export * from './queue.js';
13
+ export * from './retention.js';
14
+ export * from './session-storage.js';
15
+ export * from './toolkit.js';
16
+ export * from './workflow-pipelines.js';
@@ -0,0 +1,110 @@
1
+ import { type CallRow, type DeliveryRow, type Instant, type Journal, type Logger, type ReasonCount, type RunId, type RunRow, type StepRow, type TaskCursor, type TaskRow, type TaskState, type UnitKey, type UnitRow } from '../../contracts/index.js';
2
+ /**
3
+ * Every query this adapter can run, in one place.
4
+ *
5
+ * Named queries only. No method takes SQL, nothing here is assembled from a
6
+ * caller's value, and every parameter is bound. A new operator screen means a
7
+ * new entry in this object, which is a moment of review rather than an ad-hoc
8
+ * SELECT in a route.
9
+ *
10
+ * Which index serves which query — asserted by `journal.spec.ts` with EXPLAIN
11
+ * QUERY PLAN, so it stays true rather than staying written down:
12
+ *
13
+ * recentRuns journal_runs_started_at
14
+ * unitsForRun journal_units primary key (run_id, unit_key)
15
+ * unit journal_units primary key, journal_steps_unit,
16
+ * journal_calls primary key
17
+ * latestForUnit journal_units_unit_key
18
+ * failuresByReason journal_units_recorded_at
19
+ * delivery webhook_deliveries and webhook_tasks primary keys
20
+ * deadTasks webhook_tasks_state
21
+ * deadTasksByUseCase webhook_tasks_use_case_state
22
+ * stuckTasks webhook_tasks_state
23
+ * reclaimStuckTask sqlite_autoindex_webhook_tasks_1
24
+ */
25
+ declare const Q: {
26
+ readonly startRun: "\n INSERT INTO journal_runs\n (run_id, job, trigger, mode, started_at, identity)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6)\n ON CONFLICT(run_id) DO UPDATE SET\n job = ?2, trigger = ?3, mode = ?4, started_at = ?5, identity = ?6\n ";
27
+ readonly finishRun: "UPDATE journal_runs SET ended_at = ?2 WHERE run_id = ?1";
28
+ readonly recordUnit: "\n INSERT INTO journal_units\n (run_id, unit_key, unit_type, recorded_at, outcome,\n reason_code, plan_hash, plan_ref, duration_ms, external_ids)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)\n ON CONFLICT(run_id, unit_key) DO UPDATE SET\n unit_type = ?3, recorded_at = ?4, outcome = ?5,\n reason_code = ?6, plan_hash = ?7, plan_ref = ?8,\n duration_ms = ?9, external_ids = ?10\n ";
29
+ readonly clearCalls: "DELETE FROM journal_calls WHERE run_id = ?1 AND unit_key = ?2";
30
+ readonly recordCall: "\n INSERT INTO journal_calls\n (run_id, unit_key, seq, system, operation,\n status, http_status, idempotency_key, duration_ms)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)\n ";
31
+ readonly recordStep: "\n INSERT INTO journal_steps\n (run_id, unit_key, step, attempt, outcome,\n reason_code, duration_ms, recorded_at)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)\n ";
32
+ readonly unitsForRun: "\n SELECT * FROM journal_units\n WHERE run_id = ?1 ORDER BY unit_key LIMIT ?2\n ";
33
+ readonly unit: "SELECT * FROM journal_units WHERE run_id = ?1 AND unit_key = ?2";
34
+ readonly stepsForUnit: "\n SELECT * FROM journal_steps\n WHERE run_id = ?1 AND unit_key = ?2 ORDER BY recorded_at, seq\n ";
35
+ readonly callsForUnit: "\n SELECT * FROM journal_calls\n WHERE run_id = ?1 AND unit_key = ?2 ORDER BY seq\n ";
36
+ readonly latestForUnit: "\n SELECT * FROM journal_units\n WHERE unit_key = ?1 ORDER BY recorded_at DESC LIMIT 1\n ";
37
+ readonly failuresByReason: "\n SELECT reason_code AS reasonCode, COUNT(*) AS count\n FROM journal_units\n WHERE recorded_at >= ?1\n AND reason_code IS NOT NULL\n AND outcome != 'written'\n GROUP BY reason_code\n ORDER BY count DESC, reason_code ASC\n ";
38
+ readonly recentRuns: "SELECT * FROM journal_runs ORDER BY started_at DESC LIMIT ?1";
39
+ readonly recordDelivery: "\n INSERT INTO webhook_deliveries\n (delivery_id, source, topic, shop, webhook_id, body_key, received_at)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)\n ON CONFLICT(delivery_id) DO NOTHING\n ";
40
+ readonly recordTask: "\n INSERT INTO webhook_tasks (delivery_id, use_case, state, updated_at)\n VALUES (?1, ?2, 'received', ?3)\n ON CONFLICT(delivery_id, use_case) DO NOTHING\n ";
41
+ readonly moveTask: "\n UPDATE webhook_tasks SET state = ?3, updated_at = ?4, reason_code = ?9,\n requeues = CASE WHEN ?3 = 'replayed' THEN 0 ELSE requeues END\n WHERE delivery_id = ?1 AND use_case = ?2 AND state IN (?5, ?6, ?7, ?8)\n ";
42
+ readonly delivery: "SELECT * FROM webhook_deliveries WHERE delivery_id = ?1";
43
+ readonly tasksForDelivery: "\n SELECT * FROM webhook_tasks WHERE delivery_id = ?1 ORDER BY use_case\n ";
44
+ readonly deadTasks: "\n SELECT * FROM webhook_tasks\n WHERE state = 'dead' AND (updated_at, delivery_id, use_case) > (?1, ?2, ?3)\n ORDER BY updated_at, delivery_id, use_case LIMIT ?4\n ";
45
+ readonly deadTasksByUseCase: "\n SELECT * FROM webhook_tasks\n WHERE use_case = ?5 AND state = 'dead'\n AND (updated_at, delivery_id, use_case) > (?1, ?2, ?3)\n ORDER BY updated_at, delivery_id LIMIT ?4\n ";
46
+ readonly stuckTasks: "\n SELECT * FROM webhook_tasks\n WHERE state IN ('received', 'processing', 'replayed') AND updated_at < ?1\n ORDER BY updated_at, delivery_id, use_case LIMIT ?2\n ";
47
+ readonly reclaimStuckTask: "\n UPDATE webhook_tasks SET\n updated_at = ?5,\n state = CASE WHEN ?4 = 'dead' THEN 'dead' ELSE state END,\n reason_code = CASE WHEN ?4 = 'dead' THEN 'stuck' ELSE reason_code END,\n requeues = CASE WHEN ?4 = 'dead' THEN requeues ELSE requeues + 1 END\n WHERE delivery_id = ?1 AND use_case = ?2 AND updated_at = ?3\n AND state IN ('received', 'processing', 'replayed')\n ";
48
+ };
49
+ export type CloudflareJournalOptions = {
50
+ readonly db: D1Database;
51
+ /**
52
+ * Where a failed step-row write goes, because `recordStep` must not reject.
53
+ * Required: without it the failure would go nowhere, and a journal that
54
+ * loses a row without saying so is the silence plan §9.3 calls a defect.
55
+ */
56
+ readonly logger: Logger;
57
+ };
58
+ export declare class CloudflareJournal implements Journal {
59
+ #private;
60
+ private readonly o;
61
+ constructor(o: CloudflareJournalOptions);
62
+ startRun(row: RunRow): Promise<void>;
63
+ finishRun(runId: RunId, endedAt: Instant): Promise<void>;
64
+ /**
65
+ * One write, not one per step.
66
+ *
67
+ * `D1.batch` sends the unit and every one of its calls in a single round trip
68
+ * and runs them in one implicit transaction, so a unit is never half
69
+ * recorded. A loop of awaits would be N round trips and N chances to leave a
70
+ * unit with some of its calls.
71
+ *
72
+ * One statement per call rather than one multi-row INSERT: D1 binds at most
73
+ * 100 parameters per query, and nine columns means a batch of twelve calls
74
+ * would already be over the limit.
75
+ */
76
+ recordUnit(unit: UnitRow, calls: readonly CallRow[]): Promise<void>;
77
+ /**
78
+ * One statement, not batched with the unit: it is written after each
79
+ * attempt, while the unit row is written once at the end.
80
+ *
81
+ * Catches every failure and logs it, as the contract requires. The fault is
82
+ * mapped first, so the log line names the same tool, operation and fault
83
+ * kind a rejection would have, and the vendor message stays in `cause`.
84
+ */
85
+ recordStep(step: StepRow): Promise<void>;
86
+ unitsForRun(runId: RunId, limit?: number): Promise<readonly UnitRow[]>;
87
+ unit(runId: RunId, unitKey: UnitKey): Promise<{
88
+ unit: UnitRow;
89
+ steps: readonly StepRow[];
90
+ calls: readonly CallRow[];
91
+ } | undefined>;
92
+ latestForUnit(unitKey: UnitKey): Promise<UnitRow | undefined>;
93
+ failuresByReason(since: Instant): Promise<readonly ReasonCount[]>;
94
+ recentRuns(limit?: number): Promise<readonly RunRow[]>;
95
+ /** One `D1.batch`, so the delivery and its tasks land together or not at all. */
96
+ recordDelivery(delivery: DeliveryRow, useCases: readonly string[]): Promise<void>;
97
+ moveTask(deliveryId: string, useCase: string, to: Exclude<TaskState, 'received'>, at: Instant, reasonCode?: string): Promise<boolean>;
98
+ delivery(deliveryId: string): Promise<{
99
+ delivery: DeliveryRow;
100
+ tasks: readonly TaskRow[];
101
+ } | undefined>;
102
+ deadTasks({ useCase, after, limit, }?: {
103
+ readonly useCase?: string;
104
+ readonly after?: TaskCursor;
105
+ readonly limit?: number;
106
+ }): Promise<readonly TaskRow[]>;
107
+ stuckTasks(before: Instant, limit?: number): Promise<readonly TaskRow[]>;
108
+ reclaimStuckTask(task: Pick<TaskRow, 'deliveryId' | 'useCase' | 'updatedAt'>, at: Instant, to: 'requeued' | 'dead'): Promise<boolean>;
109
+ }
110
+ export { Q as JOURNAL_QUERIES };