@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,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,66 @@
1
+ import { WorkflowEntrypoint } from 'cloudflare:workers';
2
+ import type { PipelineRegistration, Pipelines, JsonValue, RunId, StepToolkit } from '../../contracts/index.js';
3
+ /**
4
+ * DURABLE PIPELINES ON CLOUDFLARE WORKFLOWS.
5
+ *
6
+ * Two halves, over one Workflow binding:
7
+ *
8
+ * - `workflowPipelinesEntrypoint` returns ONE GENERIC `WorkflowEntrypoint` class
9
+ * that runs every registered Pipeline. It finds the Pipeline from the instance id's
10
+ * prefix: a Pipeline name has no `-`, so the id's first `-` ends the name
11
+ * (`PipelineInstanceId`). Export it from the Worker's main module and bind it as
12
+ * a Workflow.
13
+ * - `createWorkflowPipelines` is the `Pipelines` a route calls. It creates and reads
14
+ * instances through that binding.
15
+ *
16
+ * One binding serves every Pipeline. Workflows scopes ids to a binding and
17
+ * `status(id)` takes no Pipeline name, so a binding per Pipeline would make `status`
18
+ * guess which binding to ask.
19
+ *
20
+ * THE CLASS HOLDS NO PIPELINE 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 Pipeline name and key. */
28
+ export type WorkflowPipelinesParams = {
29
+ readonly input: JsonValue;
30
+ readonly runId: RunId;
31
+ };
32
+ /** The Workflow binding the executor creates and reads instances through. */
33
+ export type PipelinesWorkflow = Workflow<WorkflowPipelinesParams>;
34
+ export type WorkflowPipelinesEntrypointOptions<Env> = {
35
+ /**
36
+ * The journal, clock and logger every step receives as `toolkit`. Called
37
+ * with the Worker's `env` in each invocation, as `registrations` is. The
38
+ * reference executor passes its own; a Workflow has none until it builds one.
39
+ */
40
+ readonly toolkit: (env: Env) => StepToolkit;
41
+ /** Defaults to `CLOUDFLARE_MANIFEST.stepResultMaxBytes`, 1 MiB. */
42
+ readonly stepResultMaxBytes?: number;
43
+ };
44
+ /**
45
+ * The generic Workflow class. `registrations` is called with the Worker's
46
+ * `env` in each invocation, so a deps builder can close over the bindings:
47
+ *
48
+ * export const PipelinesWorkflow = workflowPipelinesEntrypoint(
49
+ * (env: Env) => [
50
+ * (register) => register(selfSignUp, () => createSignUpDeps(env)),
51
+ * ],
52
+ * { toolkit: (env: Env) => toolkitFor(env) },
53
+ * )
54
+ *
55
+ * It must return the same registrations `createWorkflowPipelines` was given.
56
+ */
57
+ export declare function workflowPipelinesEntrypoint<Env>(registrations: (env: Env) => readonly PipelineRegistration[], options: WorkflowPipelinesEntrypointOptions<Env>): new (ctx: ExecutionContext, env: Env) => WorkflowEntrypoint<Env, WorkflowPipelinesParams>;
58
+ export type WorkflowPipelinesOptions = {
59
+ readonly workflow: PipelinesWorkflow;
60
+ readonly registrations: readonly PipelineRegistration[];
61
+ };
62
+ /**
63
+ * `Pipelines` over the Workflow binding that `workflowPipelinesEntrypoint`'s class is
64
+ * bound to. Throws when it is built if a registration's name breaks the rule.
65
+ */
66
+ export declare function createWorkflowPipelines(options: WorkflowPipelinesOptions): Pipelines;
@@ -0,0 +1,323 @@
1
+ import { WorkflowEntrypoint } from 'cloudflare:workers';
2
+ import { NonRetryableError } from 'cloudflare:workflows';
3
+ import { LimitExceeded, Misconfigured, Unavailable, } from '../../contracts/index.js';
4
+ import { toFault } from './faults.js';
5
+ import { CLOUDFLARE_MANIFEST } from './manifest.js';
6
+ const TOOL = 'pipelines';
7
+ const NAME = /^[A-Za-z0-9_]{1,64}$/;
8
+ const KEY = /^[A-Za-z0-9_-]+$/;
9
+ const ID = /^[A-Za-z0-9_]+-[A-Za-z0-9_-]+$/;
10
+ const ID_MAX = 100;
11
+ /**
12
+ * Workflows' documented maximum event payload, 1 MiB (docs/platform-facts.md,
13
+ * "Maximum event payload"). The params are the input and the run id, and
14
+ * they are checked here, before `create()` (rule 7).
15
+ */
16
+ const PARAMS_MAX_BYTES = 1_048_576;
17
+ /**
18
+ * THE EXHAUSTION HANDLER'S STEP. The contract says a throw from the handler
19
+ * is a fault and the executor runs it again, and that `failed` means it has
20
+ * finished, so it gets as many retries as Workflows allows: 10,000
21
+ * (docs/platform-facts.md, "Maximum retries per step"). A fixed minute
22
+ * between them keeps a handler that always throws from spinning. The
23
+ * reference executor waits a minute too. The contract gives the handler no
24
+ * timeout, so this sets none, and Workflows' default applies.
25
+ *
26
+ * A handler that throws 10,001 times fails its step, and the instance ends
27
+ * `errored`, which `status` reports as `failed` although the handler never
28
+ * finished. That is the one way this executor breaks "failed means the
29
+ * handler has finished", and it takes about a week of throws.
30
+ */
31
+ const HANDLER_STEP = {
32
+ retries: { limit: 10_000, delay: 60_000, backoff: 'constant' },
33
+ };
34
+ /**
35
+ * Workflows step names. A user step is `step:<name>`, so no step name a Pipeline
36
+ * chooses can be the handler's: the handler's step has no `:`-prefix of that
37
+ * form, and Workflows caches a step's result by its name.
38
+ */
39
+ const stepName = (name) => `step:${name}`;
40
+ const HANDLER_STEP_NAME = 'onExhausted';
41
+ /**
42
+ * HOW A STEP BODY TELLS `run()` WHY IT STOPPED. A terminal outcome and a
43
+ * result that is too large are thrown from inside `step.do` as a
44
+ * `NonRetryableError`, so Workflows does not retry them. Locally, `run()`
45
+ * catches a plain `Error` whose message is `NonRetryableError: <message>`
46
+ * (docs/platform-facts.md, "Under the test pool"), so the class is lost and
47
+ * the message is all that arrives. The marker is therefore searched for
48
+ * anywhere in the message, and the reason code is URI-encoded so that it
49
+ * holds no space.
50
+ *
51
+ * NOT MEASURED DEPLOYED: what message `run()` catches there, and what a
52
+ * replay of a failed `step.do` throws. If the marker does not survive, a
53
+ * terminal step is reported to the handler as `retries-exhausted`. It is
54
+ * still not retried.
55
+ */
56
+ const MARKER = 'anatta-pipelines:';
57
+ const MARKED = /anatta-pipelines:(terminal|result-too-large):(\S*)/;
58
+ const mark = (cause, reasonCode = '') => `${MARKER}${cause}:${encodeURIComponent(reasonCode)}`;
59
+ function exhaustionOf(step, error) {
60
+ const message = error instanceof Error ? error.message : String(error);
61
+ const m = MARKED.exec(message);
62
+ if (m?.[1] === 'terminal') {
63
+ return {
64
+ step,
65
+ cause: 'terminal',
66
+ reasonCode: decodeURIComponent(m[2] ?? ''),
67
+ };
68
+ }
69
+ if (m?.[1] === 'result-too-large') {
70
+ return { step, cause: 'result-too-large' };
71
+ }
72
+ return { step, cause: 'retries-exhausted' };
73
+ }
74
+ const bytes = (json) => new TextEncoder().encode(json).byteLength;
75
+ /**
76
+ * `create()` with an id that Workflows still retains. Deployed, the message
77
+ * is `(instance.already_exists) Instance already exists` (PR #89,
78
+ * docs/platform-facts.md "Deployed"). The test pool's miniflare does not
79
+ * throw at all, so only the unit test in workflow-pipelines.spec.ts shows this mapping.
80
+ */
81
+ const alreadyExists = (e) => e instanceof Error && e.message.includes('instance.already_exists');
82
+ /**
83
+ * `get()` for an id that Workflows has no instance for. Locally the message
84
+ * is `instance.not_found`; deployed it is `(instance.not_found) Instance not
85
+ * found` (PR #89).
86
+ *
87
+ * THE RISK, ACCEPTED ON #71: locally, `get()` turns every failure to read an
88
+ * instance's status into this same error, so a fault reading an instance
89
+ * that exists reads as `unknown`. Deployed, no fault could be induced, so
90
+ * whether a read fault can also arrive as `instance.not_found` is not
91
+ * measured. If it can, `status` reports `unknown` for an instance that
92
+ * exists. Any other error is a fault, and throws (rule 8).
93
+ */
94
+ const notFound = (e) => e instanceof Error && e.message.includes('instance.not_found');
95
+ /**
96
+ * Unpacks one registration. The generic callback is the only place the
97
+ * definition's own types are known, so each run closes over them there and
98
+ * builds the deps itself, inside the `step.do` that runs the step.
99
+ */
100
+ function unpack(registration) {
101
+ return registration((definition, deps) => {
102
+ const typed = (base) => ({
103
+ ...base,
104
+ input: base.input,
105
+ results: base.results,
106
+ deps: deps(),
107
+ });
108
+ const handler = definition.onExhausted;
109
+ return {
110
+ name: definition.name,
111
+ key: (input) => definition.key(input),
112
+ steps: definition.steps.map((s) => ({
113
+ name: s.name,
114
+ retries: s.retries,
115
+ timeoutSeconds: s.timeoutSeconds,
116
+ run: async (base) => s.run(typed(base)),
117
+ })),
118
+ onExhausted: handler === undefined
119
+ ? undefined
120
+ : async (base, exhaustion) => handler({ ...typed(base), exhaustion }),
121
+ };
122
+ });
123
+ }
124
+ /**
125
+ * Every registration, by name. Throws for a name that breaks the rule or is
126
+ * registered twice, and for a Pipeline with two steps of the same name: each is a
127
+ * defect in the definition, found when the executor is built (rule 7,
128
+ * `PipelineDefinition.name`, `Step`). A repeated step name would also give two `step.do`
129
+ * calls one name, and Workflows caches a step's result by its name.
130
+ */
131
+ function registry(registrations) {
132
+ const pipelines = new Map();
133
+ for (const registration of registrations) {
134
+ const pipeline = unpack(registration);
135
+ if (!NAME.test(pipeline.name)) {
136
+ throw new LimitExceeded(TOOL, `Pipeline name ${JSON.stringify(pipeline.name)} must be 1 to 64 characters of [A-Za-z0-9_]`);
137
+ }
138
+ const stepNames = new Set();
139
+ for (const step of pipeline.steps) {
140
+ if (stepNames.has(step.name)) {
141
+ throw new Misconfigured(TOOL, `Pipeline ${pipeline.name} has two steps named ${JSON.stringify(step.name)}`);
142
+ }
143
+ stepNames.add(step.name);
144
+ }
145
+ if (pipelines.has(pipeline.name)) {
146
+ throw new Misconfigured(TOOL, `Pipeline name ${pipeline.name} is registered twice`);
147
+ }
148
+ pipelines.set(pipeline.name, pipeline);
149
+ }
150
+ return pipelines;
151
+ }
152
+ /** The contract's retries, in Workflows' words. Both count retries. */
153
+ const stepConfig = (s) => ({
154
+ retries: {
155
+ limit: s.retries.limit,
156
+ delay: s.retries.delaySeconds * 1000,
157
+ backoff: s.retries.backoff,
158
+ },
159
+ timeout: s.timeoutSeconds * 1000,
160
+ });
161
+ /**
162
+ * One attempt of one step, inside its `step.do`. The step-result limit is
163
+ * checked here, before the result is returned to Workflows (rule 7): locally
164
+ * Workflows accepts a result above 1 MiB (docs/platform-facts.md), so the
165
+ * platform cannot be left to refuse it.
166
+ */
167
+ async function attempt(s, base, maxBytes) {
168
+ const outcome = await s.run(base);
169
+ if (outcome.status === 'terminal') {
170
+ throw new NonRetryableError(mark('terminal', outcome.reasonCode));
171
+ }
172
+ if (bytes(JSON.stringify(outcome.result)) > maxBytes) {
173
+ throw new NonRetryableError(mark('result-too-large'));
174
+ }
175
+ return outcome.result;
176
+ }
177
+ /**
178
+ * The generic Workflow class. `registrations` is called with the Worker's
179
+ * `env` in each invocation, so a deps builder can close over the bindings:
180
+ *
181
+ * export const PipelinesWorkflow = workflowPipelinesEntrypoint(
182
+ * (env: Env) => [
183
+ * (register) => register(selfSignUp, () => createSignUpDeps(env)),
184
+ * ],
185
+ * { toolkit: (env: Env) => toolkitFor(env) },
186
+ * )
187
+ *
188
+ * It must return the same registrations `createWorkflowPipelines` was given.
189
+ */
190
+ export function workflowPipelinesEntrypoint(registrations, options) {
191
+ const maxBytes = options.stepResultMaxBytes ?? CLOUDFLARE_MANIFEST.stepResultMaxBytes;
192
+ return class PipelinesEntrypoint extends WorkflowEntrypoint {
193
+ async run(event, step) {
194
+ const id = event.instanceId;
195
+ const name = id.slice(0, Math.max(0, id.indexOf('-')));
196
+ const pipeline = registry(registrations(this.env)).get(name);
197
+ if (pipeline === undefined) {
198
+ throw new NonRetryableError(`${TOOL}: no Pipeline is registered for ${id}`);
199
+ }
200
+ const base = {
201
+ instanceId: id,
202
+ runId: event.payload.runId,
203
+ unitKey: id.slice(name.length + 1),
204
+ input: event.payload.input,
205
+ toolkit: options.toolkit(this.env),
206
+ };
207
+ const results = {};
208
+ // `step.do`'s `Rpc.Serializable<T>` check recurses without end on the
209
+ // recursive `JsonValue`, so the call is typed here instead. A JSON value
210
+ // is serializable by construction. `step` is an RPC stub, so its method
211
+ // is called on it, not bound.
212
+ const steps = step;
213
+ let exhaustion;
214
+ for (const s of pipeline.steps) {
215
+ const context = { ...base, results: { ...results } };
216
+ try {
217
+ results[s.name] = await steps.do(stepName(s.name), stepConfig(s), async () => attempt(s, context, maxBytes));
218
+ }
219
+ catch (error) {
220
+ exhaustion = exhaustionOf(s.name, error);
221
+ break;
222
+ }
223
+ }
224
+ if (exhaustion === undefined) {
225
+ return null;
226
+ }
227
+ const handler = pipeline.onExhausted;
228
+ const failed = exhaustion;
229
+ if (handler !== undefined) {
230
+ const context = { ...base, results: { ...results } };
231
+ await step.do(HANDLER_STEP_NAME, HANDLER_STEP, async () => {
232
+ await handler(context, failed);
233
+ return null;
234
+ });
235
+ }
236
+ // The instance ends `errored`, which `status` reports as `failed`.
237
+ throw new NonRetryableError(`${TOOL}: ${id} stopped at step ${failed.step}: ${failed.cause}`);
238
+ }
239
+ };
240
+ }
241
+ /**
242
+ * `Pipelines` over the Workflow binding that `workflowPipelinesEntrypoint`'s class is
243
+ * bound to. Throws when it is built if a registration's name breaks the rule.
244
+ */
245
+ export function createWorkflowPipelines(options) {
246
+ return new WorkflowPipelines(options.workflow, registry(options.registrations));
247
+ }
248
+ class WorkflowPipelines {
249
+ workflow;
250
+ pipelines;
251
+ constructor(workflow, pipelines) {
252
+ this.workflow = workflow;
253
+ this.pipelines = pipelines;
254
+ }
255
+ async dispatch(definition, input, options) {
256
+ const pipeline = this.pipelines.get(definition.name);
257
+ if (pipeline === undefined) {
258
+ throw new Misconfigured(TOOL, `Pipeline ${definition.name} is not registered with this executor`);
259
+ }
260
+ const key = pipeline.key(input);
261
+ const id = `${pipeline.name}-${key}`;
262
+ if (!KEY.test(key) || id.length > ID_MAX) {
263
+ throw new LimitExceeded(TOOL, `key ${JSON.stringify(key)} must be [A-Za-z0-9_-], at least one character, and fit an id of ${ID_MAX}`);
264
+ }
265
+ const params = { input, runId: options.runId };
266
+ if (bytes(JSON.stringify(params)) > PARAMS_MAX_BYTES) {
267
+ throw new LimitExceeded(TOOL, `the input of ${id} is above Workflows' ${PARAMS_MAX_BYTES}-byte event payload`);
268
+ }
269
+ try {
270
+ await this.workflow.create({ id, params });
271
+ }
272
+ catch (e) {
273
+ if (alreadyExists(e)) {
274
+ return { status: 'already-started', id };
275
+ }
276
+ throw toFault(TOOL, 'create', e);
277
+ }
278
+ return { status: 'started', id };
279
+ }
280
+ async status(id) {
281
+ const name = id.slice(0, Math.max(0, id.indexOf('-')));
282
+ // An id that breaks the rule, or names no registered Pipeline, was never
283
+ // started here. The platform is not asked.
284
+ if (!ID.test(id) || id.length > ID_MAX || !this.pipelines.has(name)) {
285
+ return { status: 'unknown' };
286
+ }
287
+ let instance;
288
+ try {
289
+ instance = await this.workflow.get(id);
290
+ }
291
+ catch (e) {
292
+ if (notFound(e)) {
293
+ return { status: 'unknown' };
294
+ }
295
+ throw toFault(TOOL, 'get', e);
296
+ }
297
+ let current;
298
+ try {
299
+ current = await instance.status();
300
+ }
301
+ catch (e) {
302
+ throw toFault(TOOL, 'status', e);
303
+ }
304
+ switch (current.status) {
305
+ case 'complete':
306
+ return { status: 'completed' };
307
+ // `terminated` is an operator's stop. The handler did not run, but the
308
+ // instance has ended and will run nothing more.
309
+ case 'errored':
310
+ case 'terminated':
311
+ return { status: 'failed' };
312
+ case 'queued':
313
+ case 'running':
314
+ case 'paused':
315
+ case 'waiting':
316
+ case 'waitingForPause':
317
+ return { status: 'running' };
318
+ default:
319
+ // Workflows' own `unknown`, or a status newer than these types.
320
+ throw new Unavailable(TOOL, `Workflows reported status ${JSON.stringify(current.status)} for ${id}`);
321
+ }
322
+ }
323
+ }