@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,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 { createCloudflareJobs } from './jobs.js';
5
+ export type { CloudflareJobs, CloudflareJobsOptions } from './jobs.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-jobs.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 { createCloudflareJobs } from './jobs.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-jobs.js';
@@ -0,0 +1,97 @@
1
+ import type { Instant, JobInstanceId, JobRegistration, Jobs, Toolkit } from '../../contracts/index.js';
2
+ import type { InstanceChange, InstanceRow, Interrupt, ReferenceStore, WakeUp } from '../reference-executor.js';
3
+ import type { QueueMessageBatch } from './bindings.js';
4
+ import type { Envelope } from './queue.js';
5
+ /** Exported so the spec can ask SQLite which index serves each read. */
6
+ export declare const JOB_QUERIES: {
7
+ readonly insert: "\n INSERT INTO job_instances\n (instance_id, job, input, run_id, unit_key, status, cause, reason_code,\n current_step, attempts, version, lease_expires_at, next_wake_at,\n created_at, ended_at)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)\n ON CONFLICT(instance_id) DO NOTHING\n RETURNING instance_id\n ";
8
+ readonly get: "SELECT * FROM job_instances WHERE instance_id = ?1";
9
+ readonly removeSteps: "\n DELETE FROM job_steps WHERE instance_id = ?1 AND EXISTS (\n SELECT 1 FROM job_instances WHERE instance_id = ?1 AND ended_at <= ?2\n )\n ";
10
+ readonly removeInstance: "\n DELETE FROM job_instances WHERE instance_id = ?1 AND ended_at <= ?2\n ";
11
+ readonly storeResult: "\n INSERT INTO job_steps (instance_id, step_index, result, completed_at)\n VALUES (?1, ?2, ?3, ?4)\n ON CONFLICT(instance_id, step_index) DO NOTHING\n ";
12
+ readonly results: "\n SELECT step_index, result FROM job_steps WHERE instance_id = ?1\n ";
13
+ readonly due: "\n SELECT * FROM job_instances\n WHERE status IN ('running', 'failing')\n AND next_wake_at <= ?1\n AND (lease_expires_at IS NULL OR lease_expires_at <= ?1)\n ORDER BY next_wake_at\n ";
14
+ readonly removeEndedSteps: "\n DELETE FROM job_steps WHERE instance_id IN (\n SELECT instance_id FROM job_instances WHERE ended_at <= ?1\n )\n ";
15
+ readonly removeEndedInstances: "DELETE FROM job_instances WHERE ended_at <= ?1";
16
+ };
17
+ export type D1JobStoreOptions = {
18
+ readonly db: D1Database;
19
+ };
20
+ /**
21
+ * `job_instances` and `job_steps` (decision 0006) in D1. Each method is one
22
+ * statement of the protocol, except the two deletes, whose order is chosen so
23
+ * that a crash between them is harmless. No method reads the clock: every
24
+ * time comes from the executor, which reads the injected `Clock`.
25
+ */
26
+ export declare class D1JobStore implements ReferenceStore {
27
+ #private;
28
+ private readonly o;
29
+ constructor(o: D1JobStoreOptions);
30
+ insert(row: InstanceRow): Promise<'inserted' | 'exists'>;
31
+ get(id: JobInstanceId): Promise<InstanceRow | undefined>;
32
+ /**
33
+ * `UPDATE … WHERE instance_id = ? AND version = ?`. `RETURNING` says
34
+ * whether the row matched, so the outcome does not depend on how D1 reports
35
+ * a changed-row count.
36
+ */
37
+ update(id: JobInstanceId, version: number, change: InstanceChange): Promise<boolean>;
38
+ remove(id: JobInstanceId, cutoff: Instant): Promise<void>;
39
+ storeResult(id: JobInstanceId, stepIndex: number, result: string, completedAt: Instant): Promise<void>;
40
+ results(id: JobInstanceId): Promise<ReadonlyMap<number, string>>;
41
+ due(now: Instant): Promise<readonly InstanceRow[]>;
42
+ removeEndedBefore(cutoff: Instant): Promise<void>;
43
+ }
44
+ /**
45
+ * THE REFERENCE EXECUTOR ON CLOUDFLARE: D1 for the step state, Queues for the
46
+ * wake-ups, and a Cron Trigger for the sweeper. The algorithm is the one in
47
+ * `reference-executor.ts`, shared with the memory adapter. Only the storage
48
+ * and the delivery are this adapter's.
49
+ *
50
+ * The Worker wires the two entry points the platform calls:
51
+ *
52
+ * export default {
53
+ * async queue(batch, env) { await jobsFor(env).consume(batch) },
54
+ * async scheduled(_controller, env) { await jobsFor(env).sweep() },
55
+ * }
56
+ */
57
+ export type CloudflareJobs = Jobs & {
58
+ /**
59
+ * THE QUEUE CONSUMER. Give it the batches of the queue that the toolkit's
60
+ * `queue` sends the wake-ups to, and no other messages: it reads every
61
+ * body as a wake-up.
62
+ *
63
+ * Each message is acknowledged or retried on its own. A message the
64
+ * executor left for redelivery, because a D1 call failed, is retried here
65
+ * explicitly, so it comes back whatever the platform does with a message
66
+ * that is neither.
67
+ */
68
+ consume(batch: QueueMessageBatch<Envelope<WakeUp>>): Promise<void>;
69
+ /**
70
+ * THE SWEEPER. Call it from the Worker's `scheduled` handler, on a Cron
71
+ * Trigger. It sends a wake-up for every running or failing instance whose
72
+ * `next_wake_at` has passed and whose lease has expired, which covers a
73
+ * lost wake-up and a backoff longer than `queueDelayMaxSeconds`, and it
74
+ * deletes ended instances whose retention has passed (decision 0006).
75
+ */
76
+ sweep(): Promise<void>;
77
+ };
78
+ export type CloudflareJobsOptions = {
79
+ readonly registrations: readonly JobRegistration[];
80
+ /**
81
+ * TEST SEAMS. A restarted process is a second executor over the same
82
+ * store, and `interrupt` parks a consumer between two writes. An app
83
+ * passes neither.
84
+ */
85
+ readonly store?: ReferenceStore;
86
+ readonly interrupt?: Interrupt;
87
+ };
88
+ /**
89
+ * Builds the executor. It throws when a registration is refused, as for a
90
+ * Job name outside `[A-Za-z0-9_]{1,64}`.
91
+ *
92
+ * The step state lives in `env.DB`, in the tables of
93
+ * `migrations/0007_create_job_tables.sql`. The toolkit supplies the clock
94
+ * (rule 3), the logger (rule 4), the journal the Step rows go to, and the
95
+ * queue the wake-ups go on (decision 0006, Amendment).
96
+ */
97
+ export declare function createCloudflareJobs(env: Pick<Env, 'DB'>, toolkit: Pick<Toolkit<WakeUp>, 'clock' | 'logger' | 'journal' | 'queue'>, options: CloudflareJobsOptions): CloudflareJobs;
@@ -0,0 +1,218 @@
1
+ import { fromEpochMs } from '../../contracts/index.js';
2
+ import { ReferenceExecutor } from '../reference-executor.js';
3
+ import { toFault } from './faults.js';
4
+ import { CLOUDFLARE_MANIFEST } from './manifest.js';
5
+ import { toQueueBatch } from './queue.js';
6
+ const TOOL = 'jobs';
7
+ /**
8
+ * Every query the store runs, in one place, with every value bound. The one
9
+ * statement assembled at run time is the conditional UPDATE, and only its
10
+ * column list is: the names come from `COLUMNS`, never from a caller.
11
+ */
12
+ const Q = {
13
+ // ON CONFLICT DO NOTHING, so a taken id is an empty RETURNING (an outcome)
14
+ // and not a constraint error (a fault).
15
+ insert: `
16
+ INSERT INTO job_instances
17
+ (instance_id, job, input, run_id, unit_key, status, cause, reason_code,
18
+ current_step, attempts, version, lease_expires_at, next_wake_at,
19
+ created_at, ended_at)
20
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)
21
+ ON CONFLICT(instance_id) DO NOTHING
22
+ RETURNING instance_id
23
+ `,
24
+ get: `SELECT * FROM job_instances WHERE instance_id = ?1`,
25
+ // job_steps first, and only while the instance has ended at or before the
26
+ // cutoff (ReferenceStore). A crash between the two statements leaves an
27
+ // ended instance with no stored results, which the next removal deletes.
28
+ // The other order could leave results with no instance, and a new instance
29
+ // with the same id would then read the old one's results as its own. The
30
+ // condition is on ended_at, not version, so a late removal cannot delete a
31
+ // newer instance's results: it has not ended, or ended after the cutoff.
32
+ removeSteps: `
33
+ DELETE FROM job_steps WHERE instance_id = ?1 AND EXISTS (
34
+ SELECT 1 FROM job_instances WHERE instance_id = ?1 AND ended_at <= ?2
35
+ )
36
+ `,
37
+ removeInstance: `
38
+ DELETE FROM job_instances WHERE instance_id = ?1 AND ended_at <= ?2
39
+ `,
40
+ // The first result stored for a step is the one that stays (0006).
41
+ storeResult: `
42
+ INSERT INTO job_steps (instance_id, step_index, result, completed_at)
43
+ VALUES (?1, ?2, ?3, ?4)
44
+ ON CONFLICT(instance_id, step_index) DO NOTHING
45
+ `,
46
+ results: `
47
+ SELECT step_index, result FROM job_steps WHERE instance_id = ?1
48
+ `,
49
+ due: `
50
+ SELECT * FROM job_instances
51
+ WHERE status IN ('running', 'failing')
52
+ AND next_wake_at <= ?1
53
+ AND (lease_expires_at IS NULL OR lease_expires_at <= ?1)
54
+ ORDER BY next_wake_at
55
+ `,
56
+ // The same order as remove, for the same reason.
57
+ removeEndedSteps: `
58
+ DELETE FROM job_steps WHERE instance_id IN (
59
+ SELECT instance_id FROM job_instances WHERE ended_at <= ?1
60
+ )
61
+ `,
62
+ removeEndedInstances: `DELETE FROM job_instances WHERE ended_at <= ?1`,
63
+ };
64
+ /** Exported so the spec can ask SQLite which index serves each read. */
65
+ export const JOB_QUERIES = Q;
66
+ /** `InstanceChange` field to `job_instances` column. */
67
+ const COLUMNS = {
68
+ status: 'status',
69
+ cause: 'cause',
70
+ reasonCode: 'reason_code',
71
+ currentStep: 'current_step',
72
+ attempts: 'attempts',
73
+ leaseExpiresAt: 'lease_expires_at',
74
+ nextWakeAt: 'next_wake_at',
75
+ endedAt: 'ended_at',
76
+ };
77
+ const instantOrNull = (ms) => ms === null ? null : fromEpochMs(ms);
78
+ const fromRow = (r) => ({
79
+ instanceId: r.instance_id,
80
+ job: r.job,
81
+ input: r.input,
82
+ runId: r.run_id,
83
+ unitKey: r.unit_key,
84
+ status: r.status,
85
+ cause: r.cause,
86
+ reasonCode: r.reason_code,
87
+ currentStep: r.current_step,
88
+ attempts: r.attempts,
89
+ version: r.version,
90
+ leaseExpiresAt: instantOrNull(r.lease_expires_at),
91
+ nextWakeAt: instantOrNull(r.next_wake_at),
92
+ createdAt: fromEpochMs(r.created_at),
93
+ endedAt: instantOrNull(r.ended_at),
94
+ });
95
+ /**
96
+ * `job_instances` and `job_steps` (decision 0006) in D1. Each method is one
97
+ * statement of the protocol, except the two deletes, whose order is chosen so
98
+ * that a crash between them is harmless. No method reads the clock: every
99
+ * time comes from the executor, which reads the injected `Clock`.
100
+ */
101
+ export class D1JobStore {
102
+ o;
103
+ constructor(o) {
104
+ this.o = o;
105
+ }
106
+ async insert(row) {
107
+ const inserted = await this.#call('insert', async () => this.o.db
108
+ .prepare(Q.insert)
109
+ .bind(row.instanceId, row.job, row.input, row.runId, row.unitKey, row.status, row.cause, row.reasonCode, row.currentStep, row.attempts, row.version, row.leaseExpiresAt, row.nextWakeAt, row.createdAt, row.endedAt)
110
+ .first());
111
+ return inserted === null ? 'exists' : 'inserted';
112
+ }
113
+ async get(id) {
114
+ const row = await this.#call('get', async () => this.o.db.prepare(Q.get).bind(id).first());
115
+ return row === null ? undefined : fromRow(row);
116
+ }
117
+ /**
118
+ * `UPDATE … WHERE instance_id = ? AND version = ?`. `RETURNING` says
119
+ * whether the row matched, so the outcome does not depend on how D1 reports
120
+ * a changed-row count.
121
+ */
122
+ async update(id, version, change) {
123
+ const fields = Object.keys(change).filter((field) => change[field] !== undefined);
124
+ const sets = fields.map((field, i) => `${COLUMNS[field]} = ?${i + 3}`);
125
+ const sql = `
126
+ UPDATE job_instances SET ${['version = version + 1', ...sets].join(', ')}
127
+ WHERE instance_id = ?1 AND version = ?2
128
+ RETURNING version
129
+ `;
130
+ const won = await this.#call('update', async () => this.o.db
131
+ .prepare(sql)
132
+ .bind(id, version, ...fields.map((field) => change[field] ?? null))
133
+ .first());
134
+ return won !== null;
135
+ }
136
+ async remove(id, cutoff) {
137
+ await this.#call('remove', async () => this.o.db.prepare(Q.removeSteps).bind(id, cutoff).run());
138
+ await this.#call('remove', async () => this.o.db.prepare(Q.removeInstance).bind(id, cutoff).run());
139
+ }
140
+ async storeResult(id, stepIndex, result, completedAt) {
141
+ await this.#call('storeResult', async () => this.o.db
142
+ .prepare(Q.storeResult)
143
+ .bind(id, stepIndex, result, completedAt)
144
+ .run());
145
+ }
146
+ async results(id) {
147
+ const { results } = await this.#call('results', async () => this.o.db
148
+ .prepare(Q.results)
149
+ .bind(id)
150
+ .all());
151
+ return new Map(results.map((r) => [r.step_index, r.result]));
152
+ }
153
+ async due(now) {
154
+ const { results } = await this.#call('due', async () => this.o.db.prepare(Q.due).bind(now).all());
155
+ return results.map(fromRow);
156
+ }
157
+ async removeEndedBefore(cutoff) {
158
+ await this.#call('removeEndedBefore', async () => this.o.db.prepare(Q.removeEndedSteps).bind(cutoff).run());
159
+ await this.#call('removeEndedBefore', async () => this.o.db.prepare(Q.removeEndedInstances).bind(cutoff).run());
160
+ }
161
+ async #call(operation, f) {
162
+ try {
163
+ return await f();
164
+ }
165
+ catch (e) {
166
+ throw toFault(TOOL, operation, e);
167
+ }
168
+ }
169
+ }
170
+ /**
171
+ * Builds the executor. It throws when a registration is refused, as for a
172
+ * Job name outside `[A-Za-z0-9_]{1,64}`.
173
+ *
174
+ * The step state lives in `env.DB`, in the tables of
175
+ * `migrations/0007_create_job_tables.sql`. The toolkit supplies the clock
176
+ * (rule 3), the logger (rule 4), the journal the Step rows go to, and the
177
+ * queue the wake-ups go on (decision 0006, Amendment).
178
+ */
179
+ export function createCloudflareJobs(env, toolkit, options) {
180
+ const executor = new ReferenceExecutor({
181
+ registrations: options.registrations,
182
+ store: options.store ?? new D1JobStore({ db: env.DB }),
183
+ queue: toolkit.queue,
184
+ clock: toolkit.clock,
185
+ logger: toolkit.logger,
186
+ journal: toolkit.journal,
187
+ manifest: CLOUDFLARE_MANIFEST,
188
+ ...(options.interrupt === undefined
189
+ ? {}
190
+ : { interrupt: options.interrupt }),
191
+ });
192
+ return {
193
+ dispatch: async (definition, input, dispatchOptions) => executor.dispatch(definition, input, dispatchOptions),
194
+ status: async (id) => executor.status(id),
195
+ sweep: async () => executor.sweep(),
196
+ async consume(batch) {
197
+ const platform = toQueueBatch(batch);
198
+ const answered = new Set();
199
+ const tracked = {
200
+ messages: platform.messages,
201
+ ack: (id) => {
202
+ answered.add(id);
203
+ platform.ack(id);
204
+ },
205
+ retry: (id, retryOptions) => {
206
+ answered.add(id);
207
+ platform.retry(id, retryOptions);
208
+ },
209
+ };
210
+ await executor.consume(tracked);
211
+ for (const message of platform.messages) {
212
+ if (!answered.has(message.id)) {
213
+ platform.retry(message.id);
214
+ }
215
+ }
216
+ },
217
+ };
218
+ }
@@ -0,0 +1,107 @@
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
+ * deadTasksByAction webhook_tasks_action_state
22
+ * stuckTasks webhook_tasks_state
23
+ */
24
+ declare const Q: {
25
+ 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 ";
26
+ readonly finishRun: "UPDATE journal_runs SET ended_at = ?2 WHERE run_id = ?1";
27
+ 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 ";
28
+ readonly clearCalls: "DELETE FROM journal_calls WHERE run_id = ?1 AND unit_key = ?2";
29
+ 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 ";
30
+ 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 ";
31
+ readonly unitsForRun: "\n SELECT * FROM journal_units\n WHERE run_id = ?1 ORDER BY unit_key LIMIT ?2\n ";
32
+ readonly unit: "SELECT * FROM journal_units WHERE run_id = ?1 AND unit_key = ?2";
33
+ readonly stepsForUnit: "\n SELECT * FROM journal_steps\n WHERE run_id = ?1 AND unit_key = ?2 ORDER BY recorded_at, seq\n ";
34
+ readonly callsForUnit: "\n SELECT * FROM journal_calls\n WHERE run_id = ?1 AND unit_key = ?2 ORDER BY seq\n ";
35
+ readonly latestForUnit: "\n SELECT * FROM journal_units\n WHERE unit_key = ?1 ORDER BY recorded_at DESC LIMIT 1\n ";
36
+ 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 ";
37
+ readonly recentRuns: "SELECT * FROM journal_runs ORDER BY started_at DESC LIMIT ?1";
38
+ 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 ";
39
+ readonly recordTask: "\n INSERT INTO webhook_tasks (delivery_id, action, state, updated_at)\n VALUES (?1, ?2, 'received', ?3)\n ON CONFLICT(delivery_id, action) DO NOTHING\n ";
40
+ readonly moveTask: "\n UPDATE webhook_tasks SET state = ?3, updated_at = ?4, reason_code = ?9\n WHERE delivery_id = ?1 AND action = ?2 AND state IN (?5, ?6, ?7, ?8)\n ";
41
+ readonly delivery: "SELECT * FROM webhook_deliveries WHERE delivery_id = ?1";
42
+ readonly tasksForDelivery: "\n SELECT * FROM webhook_tasks WHERE delivery_id = ?1 ORDER BY action\n ";
43
+ readonly deadTasks: "\n SELECT * FROM webhook_tasks\n WHERE state = 'dead' AND (updated_at, delivery_id, action) > (?1, ?2, ?3)\n ORDER BY updated_at, delivery_id, action LIMIT ?4\n ";
44
+ readonly deadTasksByAction: "\n SELECT * FROM webhook_tasks\n WHERE action = ?5 AND state = 'dead'\n AND (updated_at, delivery_id, action) > (?1, ?2, ?3)\n ORDER BY updated_at, delivery_id LIMIT ?4\n ";
45
+ readonly stuckTasks: "\n SELECT * FROM webhook_tasks\n WHERE state IN ('received', 'processing') AND updated_at < ?1\n ORDER BY updated_at, delivery_id, action LIMIT ?2\n ";
46
+ };
47
+ export type CloudflareJournalOptions = {
48
+ readonly db: D1Database;
49
+ /**
50
+ * Where a failed step-row write goes, because `recordStep` must not reject.
51
+ * Required: without it the failure would go nowhere, and a journal that
52
+ * loses a row without saying so is the silence plan §9.3 calls a defect.
53
+ */
54
+ readonly logger: Logger;
55
+ };
56
+ export declare class CloudflareJournal implements Journal {
57
+ #private;
58
+ private readonly o;
59
+ constructor(o: CloudflareJournalOptions);
60
+ startRun(row: RunRow): Promise<void>;
61
+ finishRun(runId: RunId, endedAt: Instant): Promise<void>;
62
+ /**
63
+ * One write, not one per step.
64
+ *
65
+ * `D1.batch` sends the unit and every one of its calls in a single round trip
66
+ * and runs them in one implicit transaction, so a unit is never half
67
+ * recorded. A loop of awaits would be N round trips and N chances to leave a
68
+ * unit with some of its calls.
69
+ *
70
+ * One statement per call rather than one multi-row INSERT: D1 binds at most
71
+ * 100 parameters per query, and nine columns means a batch of twelve calls
72
+ * would already be over the limit.
73
+ */
74
+ recordUnit(unit: UnitRow, calls: readonly CallRow[]): Promise<void>;
75
+ /**
76
+ * One statement, not batched with the unit: it is written after each
77
+ * attempt, while the unit row is written once at the end.
78
+ *
79
+ * Catches every failure and logs it, as the contract requires. The fault is
80
+ * mapped first, so the log line names the same tool, operation and fault
81
+ * kind a rejection would have, and the vendor message stays in `cause`.
82
+ */
83
+ recordStep(step: StepRow): Promise<void>;
84
+ unitsForRun(runId: RunId, limit?: number): Promise<readonly UnitRow[]>;
85
+ unit(runId: RunId, unitKey: UnitKey): Promise<{
86
+ unit: UnitRow;
87
+ steps: readonly StepRow[];
88
+ calls: readonly CallRow[];
89
+ } | undefined>;
90
+ latestForUnit(unitKey: UnitKey): Promise<UnitRow | undefined>;
91
+ failuresByReason(since: Instant): Promise<readonly ReasonCount[]>;
92
+ recentRuns(limit?: number): Promise<readonly RunRow[]>;
93
+ /** One `D1.batch`, so the delivery and its tasks land together or not at all. */
94
+ recordDelivery(delivery: DeliveryRow, actions: readonly string[]): Promise<void>;
95
+ moveTask(deliveryId: string, action: string, to: Exclude<TaskState, 'received'>, at: Instant, reasonCode?: string): Promise<boolean>;
96
+ delivery(deliveryId: string): Promise<{
97
+ delivery: DeliveryRow;
98
+ tasks: readonly TaskRow[];
99
+ } | undefined>;
100
+ deadTasks({ action, after, limit, }?: {
101
+ readonly action?: string;
102
+ readonly after?: TaskCursor;
103
+ readonly limit?: number;
104
+ }): Promise<readonly TaskRow[]>;
105
+ stuckTasks(before: Instant, limit?: number): Promise<readonly TaskRow[]>;
106
+ }
107
+ export { Q as JOURNAL_QUERIES };