@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,140 @@
1
+ var _a;
2
+ import { UseCase } from '../use-cases/index.js';
3
+ import { fromDecision } from './use-case-step.js';
4
+ /**
5
+ * The library's step settings, under every Pipeline's own `stepDefaults`.
6
+ * Three retries, 10, 20 then 40 seconds apart (`limit` counts retries, not
7
+ * attempts: four attempts in all), and a minute per attempt.
8
+ */
9
+ export const DEFAULT_STEP_OPTIONS = {
10
+ retries: { limit: 3, delaySeconds: 10, backoff: 'exponential' },
11
+ timeoutSeconds: 60,
12
+ };
13
+ /**
14
+ * A PIPELINE AS A CLASS. Extend it, name it, key it, and list its steps with
15
+ * `this.step`. Export one instance; routes, tests and the executor's
16
+ * registrations all use it.
17
+ *
18
+ * export class Demo extends Pipeline<DemoInput, DemoResults, DemoDeps> {
19
+ * static override stepDefaults: StepOverrides = { timeoutSeconds: 30 }
20
+ *
21
+ * readonly name = 'demo'
22
+ *
23
+ * key(input: DemoInput): UnitKey {
24
+ * return input.ref
25
+ * }
26
+ *
27
+ * readonly steps = [
28
+ * this.step('start', async ({ deps }) => done({ at: toIso(deps.clock.now()) })),
29
+ * this.step('finish', { retries: { limit: 5 } }, async ({ results }) => …),
30
+ * ]
31
+ * }
32
+ *
33
+ * export const demo = new Demo()
34
+ *
35
+ * The executors are unchanged: `register` and `dispatch` hand them the plain
36
+ * `PipelineDefinition` they already run, built once from the instance. Every
37
+ * rule of `PipelineDefinition` and `Step` holds, in particular: all I/O in a
38
+ * step, no code between steps, and a step safe when two attempts overlap.
39
+ *
40
+ * HOLD NO STATE ON `this`. One instance serves every dispatch, every attempt
41
+ * and every executor in the process, and a step that runs after a restart
42
+ * runs on a new instance. State lives in the input, the step results and the
43
+ * deps. (decision 0015)
44
+ */
45
+ export class Pipeline {
46
+ /**
47
+ * This Pipeline's step settings, over `DEFAULT_STEP_OPTIONS`, under each
48
+ * step's own overrides. Each layer may be partial.
49
+ *
50
+ * STATIC, NOT AN INSTANCE FIELD. Class fields are set in the order they are
51
+ * written, after the base constructor, so an instance field written below
52
+ * `steps` is not set yet when `steps` calls `this.step`, and would be
53
+ * ignored without an error. A static field is set when the class is.
54
+ */
55
+ static stepDefaults = {};
56
+ #definition;
57
+ step(name, overridesOrRun, maybeRun) {
58
+ if (overridesOrRun instanceof UseCase) {
59
+ return this.#useCaseStep(name, overridesOrRun, typeof maybeRun === 'function' ? {} : (maybeRun ?? {}));
60
+ }
61
+ const overrides = typeof overridesOrRun === 'function' ? {} : overridesOrRun;
62
+ const run = typeof overridesOrRun === 'function' ? overridesOrRun : maybeRun;
63
+ if (typeof run !== 'function') {
64
+ throw new TypeError(`${this.constructor.name}: step ${name} has no body`);
65
+ }
66
+ return { name, ...this.#settings(overrides), run };
67
+ }
68
+ /**
69
+ * This Pipeline with the builder for its deps, for the executor's
70
+ * registrations. Replaces `(register) => register(definition, deps)`.
71
+ */
72
+ register(deps) {
73
+ const definition = this.#toDefinition();
74
+ return (register) => register(definition, deps);
75
+ }
76
+ /**
77
+ * Starts an instance on `pipelines`. The same outcomes as
78
+ * `Pipelines.dispatch`, which it calls.
79
+ */
80
+ async dispatch(input, { pipelines, ...options }) {
81
+ return pipelines.dispatch(this.#toDefinition(), input, options);
82
+ }
83
+ #useCaseStep(name, useCase, wiring) {
84
+ const input = 'input' in wiring ? wiring.input : undefined;
85
+ const deps = 'deps' in wiring ? wiring.deps : undefined;
86
+ return {
87
+ name,
88
+ ...this.#settings(wiring),
89
+ run: async (context) => {
90
+ const decision = await useCase.execute(input === undefined ? context.input : input(context), {
91
+ toolkit: context.toolkit,
92
+ trigger: 'pipeline',
93
+ job: `pipeline.${this.name}.${name}`,
94
+ deps: deps === undefined ? context.deps : deps(context),
95
+ });
96
+ // The overloads checked that Results[Name] is this use case's
97
+ // Decision, so its outcome is this step's.
98
+ return fromDecision(useCase.name, decision);
99
+ },
100
+ };
101
+ }
102
+ #settings(overrides) {
103
+ const own = this.constructor.stepDefaults;
104
+ return {
105
+ retries: {
106
+ ...DEFAULT_STEP_OPTIONS.retries,
107
+ ...own.retries,
108
+ ...overrides.retries,
109
+ },
110
+ timeoutSeconds: overrides.timeoutSeconds ??
111
+ own.timeoutSeconds ??
112
+ DEFAULT_STEP_OPTIONS.timeoutSeconds,
113
+ };
114
+ }
115
+ // Built on first use, not in the constructor: a subclass's fields (`name`,
116
+ // `steps`) are not set while the base constructor runs.
117
+ #toDefinition() {
118
+ if (this.#definition === undefined) {
119
+ const onExhausted = this.onExhausted?.bind(this);
120
+ this.#definition = {
121
+ name: this.name,
122
+ key: (input) => this.key(input),
123
+ steps: this.steps,
124
+ ...(onExhausted !== undefined && { onExhausted }),
125
+ };
126
+ }
127
+ return this.#definition;
128
+ }
129
+ }
130
+ _a = Pipeline;
131
+ /** A step's result: the step is done, and later steps read `result`. */
132
+ export const done = (result) => ({ status: 'done', result });
133
+ /**
134
+ * No retry can succeed. The Pipeline stops, and `onExhausted` runs with the
135
+ * reason code, from the domain's closed list.
136
+ */
137
+ export const terminal = (reasonCode) => ({
138
+ status: 'terminal',
139
+ reasonCode,
140
+ });
@@ -0,0 +1,24 @@
1
+ import type { PipelineStepOutcome } from '../contracts/index.js';
2
+ import type { Decision } from '../use-cases/index.js';
3
+ /**
4
+ * A use case's retryable decision, thrown from its step so the executor
5
+ * retries the step with its own retries. Its message carries the reason code,
6
+ * so the step row and the log say why.
7
+ */
8
+ export declare class RetryableDecision extends Error {
9
+ readonly decision: Decision<string>;
10
+ constructor(useCase: string, decision: Decision<string>);
11
+ }
12
+ /**
13
+ * A use case's decision as its step's outcome. Library-internal: an app
14
+ * passes the use case to `this.step`, and never calls this.
15
+ *
16
+ * - `failed` or `skipped` with `retryable: true`: throws, so the step retries.
17
+ * - `failed`: `terminal(reasonCode)`, so the Pipeline stops and
18
+ * `onExhausted` runs.
19
+ * - Anything else: `done(decision)`. The decision is the step's stored
20
+ * result, which later steps read from `results`.
21
+ *
22
+ * A throw from the use case is a fault, and reaches the executor unchanged.
23
+ */
24
+ export declare function fromDecision<Reason extends string>(useCase: string, decision: Decision<Reason>): PipelineStepOutcome<Decision<Reason>>;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * A use case's retryable decision, thrown from its step so the executor
3
+ * retries the step with its own retries. Its message carries the reason code,
4
+ * so the step row and the log say why.
5
+ */
6
+ export class RetryableDecision extends Error {
7
+ decision;
8
+ constructor(useCase, decision) {
9
+ super(`${useCase}: retryable ${decision.outcome}${'reasonCode' in decision ? ` (${decision.reasonCode})` : ''}`);
10
+ this.name = 'RetryableDecision';
11
+ this.decision = decision;
12
+ }
13
+ }
14
+ /**
15
+ * A use case's decision as its step's outcome. Library-internal: an app
16
+ * passes the use case to `this.step`, and never calls this.
17
+ *
18
+ * - `failed` or `skipped` with `retryable: true`: throws, so the step retries.
19
+ * - `failed`: `terminal(reasonCode)`, so the Pipeline stops and
20
+ * `onExhausted` runs.
21
+ * - Anything else: `done(decision)`. The decision is the step's stored
22
+ * result, which later steps read from `results`.
23
+ *
24
+ * A throw from the use case is a fault, and reaches the executor unchanged.
25
+ */
26
+ export function fromDecision(useCase, decision) {
27
+ if ('retryable' in decision && decision.retryable === true) {
28
+ throw new RetryableDecision(useCase, decision);
29
+ }
30
+ if (decision.outcome === 'failed') {
31
+ return { status: 'terminal', reasonCode: decision.reasonCode };
32
+ }
33
+ return { status: 'done', result: decision };
34
+ }
@@ -0,0 +1,40 @@
1
+ import type { RunId, Toolkit, ToolManifest } from '../contracts/index.js';
2
+ export type ScheduledTask = {
3
+ /** Part of the Ledger key and the Journal's `job`. No ':'. */
4
+ readonly name: string;
5
+ readonly everySeconds: number;
6
+ /** `runId` is this run's Journal run, for a task that records its own units. */
7
+ readonly run: (context: {
8
+ readonly runId: RunId;
9
+ }) => Promise<void>;
10
+ };
11
+ /** Made only by `defineSchedule`, so every schedule has been checked. */
12
+ export type Schedule = {
13
+ readonly tasks: readonly ScheduledTask[];
14
+ readonly __schedule: true;
15
+ };
16
+ /** A toolkit has all four, so a toolkit can be passed as it is. */
17
+ export type ScheduleDeps = Pick<Toolkit, 'ledger' | 'journal' | 'clock' | 'logger'>;
18
+ export type TaskOutcome = 'ran' | 'failed' | 'skipped';
19
+ export type TaskResult = {
20
+ readonly name: string;
21
+ readonly outcome: TaskOutcome;
22
+ };
23
+ export declare function defineSchedule(manifest: Pick<ToolManifest, 'scheduleMinIntervalSeconds'>, tasks: readonly ScheduledTask[]): Schedule;
24
+ /**
25
+ * One tick. Each task runs at most once per slot, `floor(now / everySeconds)`,
26
+ * across every ticker, because the slot is claimed in the Ledger first. A slot
27
+ * the tickers missed is not run later. Tasks run in turn, and one that throws
28
+ * is journaled as failed without stopping the others.
29
+ */
30
+ export declare function runDueTasks(schedule: Schedule, deps: ScheduleDeps): Promise<readonly TaskResult[]>;
31
+ export type SchedulerOptions = {
32
+ readonly tickSeconds: number;
33
+ readonly signal: AbortSignal;
34
+ };
35
+ /**
36
+ * The Node target's ticker: tick, sleep `tickSeconds`, repeat, until `signal`
37
+ * aborts. Resolves once it has stopped. It reads no time itself; the slot comes
38
+ * from `deps.clock`. A tick longer than the shortest interval misses slots.
39
+ */
40
+ export declare function startScheduler(schedule: Schedule, deps: ScheduleDeps, { tickSeconds, signal }: SchedulerOptions): Promise<void>;
@@ -0,0 +1,135 @@
1
+ export function defineSchedule(manifest, tasks) {
2
+ const names = new Set();
3
+ for (const { name, everySeconds } of tasks) {
4
+ if (name.includes(':')) {
5
+ throw new TypeError(`task name must not contain ':': ${name}`);
6
+ }
7
+ if (names.has(name)) {
8
+ throw new TypeError(`duplicate task name: ${name}`);
9
+ }
10
+ names.add(name);
11
+ if (!Number.isInteger(everySeconds)) {
12
+ throw new RangeError(`${name}: everySeconds must be a whole number, not ${everySeconds}`);
13
+ }
14
+ if (everySeconds < manifest.scheduleMinIntervalSeconds) {
15
+ throw new RangeError(`${name}: everySeconds must be at least ${manifest.scheduleMinIntervalSeconds} on this target, not ${everySeconds}`);
16
+ }
17
+ }
18
+ return { tasks, __schedule: true };
19
+ }
20
+ /**
21
+ * One tick. Each task runs at most once per slot, `floor(now / everySeconds)`,
22
+ * across every ticker, because the slot is claimed in the Ledger first. A slot
23
+ * the tickers missed is not run later. Tasks run in turn, and one that throws
24
+ * is journaled as failed without stopping the others.
25
+ */
26
+ export async function runDueTasks(schedule, deps) {
27
+ const now = deps.clock.now();
28
+ const results = [];
29
+ for (const task of schedule.tasks) {
30
+ const slot = Math.floor(now / 1000 / task.everySeconds);
31
+ let outcome;
32
+ try {
33
+ outcome = await runSlot(task, slot, deps);
34
+ }
35
+ catch (error) {
36
+ // A Ledger or Journal fault. The tick goes on to the next task.
37
+ deps.logger.error('schedule: slot faulted', {
38
+ task: task.name,
39
+ slot,
40
+ error: String(error),
41
+ });
42
+ outcome = 'failed';
43
+ }
44
+ results.push({ name: task.name, outcome });
45
+ }
46
+ return results;
47
+ }
48
+ async function runSlot(task, slot, { ledger, journal, clock, logger }) {
49
+ const key = `schedule:${task.name}:${slot}`;
50
+ // A ticker that dies mid-run frees the slot for another once the lease ends.
51
+ const claim = await ledger.claim(key, task.everySeconds);
52
+ if (claim.status !== 'claimed') {
53
+ return 'skipped';
54
+ }
55
+ const runId = crypto.randomUUID();
56
+ const startedAt = clock.now();
57
+ // The journal is not on the correctness path: a write it loses is logged,
58
+ // and the task runs anyway.
59
+ const record = async (write) => {
60
+ try {
61
+ await write();
62
+ }
63
+ catch (error) {
64
+ logger.error('schedule: journal write failed', {
65
+ task: task.name,
66
+ slot,
67
+ error: String(error),
68
+ });
69
+ }
70
+ };
71
+ let failed = false;
72
+ await record(async () => journal.startRun({
73
+ runId,
74
+ job: task.name,
75
+ trigger: 'schedule',
76
+ mode: 'live',
77
+ startedAt,
78
+ identity: logger.identity,
79
+ }));
80
+ try {
81
+ await task.run({ runId });
82
+ }
83
+ catch (error) {
84
+ failed = true;
85
+ logger.error('schedule: task failed', {
86
+ task: task.name,
87
+ slot,
88
+ error: String(error),
89
+ });
90
+ }
91
+ // Completed on failure too: the next slot retries it, not every tick of this one.
92
+ await ledger.complete(key, task.everySeconds);
93
+ const endedAt = clock.now();
94
+ await record(async () => journal.recordUnit({
95
+ runId,
96
+ unitKey: key,
97
+ unitType: 'schedule-slot',
98
+ recordedAt: endedAt,
99
+ outcome: failed ? 'failed' : 'written',
100
+ ...(failed ? { reasonCode: 'task-threw' } : {}),
101
+ durationMs: endedAt - startedAt,
102
+ }, []));
103
+ await record(async () => journal.finishRun(runId, endedAt));
104
+ return failed ? 'failed' : 'ran';
105
+ }
106
+ /**
107
+ * The Node target's ticker: tick, sleep `tickSeconds`, repeat, until `signal`
108
+ * aborts. Resolves once it has stopped. It reads no time itself; the slot comes
109
+ * from `deps.clock`. A tick longer than the shortest interval misses slots.
110
+ */
111
+ export async function startScheduler(schedule, deps, { tickSeconds, signal }) {
112
+ if (!(tickSeconds > 0)) {
113
+ throw new RangeError(`tickSeconds must be a positive number, not ${tickSeconds}`);
114
+ }
115
+ while (!signal.aborted) {
116
+ await runDueTasks(schedule, deps);
117
+ await sleep(tickSeconds * 1000, signal);
118
+ }
119
+ }
120
+ async function sleep(ms, signal) {
121
+ return new Promise((resolve) => {
122
+ // An abort during the tick has already fired its event.
123
+ if (signal.aborted) {
124
+ resolve();
125
+ return;
126
+ }
127
+ const wake = () => {
128
+ clearTimeout(timer);
129
+ signal.removeEventListener('abort', wake);
130
+ resolve();
131
+ };
132
+ const timer = setTimeout(wake, ms);
133
+ signal.addEventListener('abort', wake);
134
+ });
135
+ }
@@ -0,0 +1,3 @@
1
+ export { UseCase, defineUseCase, failed, skipped, unchanged, written, type UseCaseContext, type UseCaseDefinition, type Decision, type ExecuteOptions, } from './use-case.js';
2
+ export type { JournalDeps } from './run-use-case.js';
3
+ export { createUseCaseConsumer, type UseCaseConsumerOptions, } from './use-case-consumer.js';
@@ -0,0 +1,3 @@
1
+ // The `@anatta.io/tva/use-cases` entry point.
2
+ export { UseCase, defineUseCase, failed, skipped, unchanged, written, } from './use-case.js';
3
+ export { createUseCaseConsumer, } from './use-case-consumer.js';
@@ -0,0 +1,33 @@
1
+ import type { RunId, RunRow, Toolkit } from '../contracts/index.js';
2
+ import type { UseCase, UseCaseContext, Decision, ExecuteOptions } from './use-case.js';
3
+ /** What the runner writes with. A `Toolkit` is one. */
4
+ export type JournalDeps = Pick<Toolkit, 'journal' | 'clock' | 'logger'>;
5
+ /** A started run. Only `withRun` makes one. Library-internal. */
6
+ export type RunScope = {
7
+ readonly runId: RunId;
8
+ };
9
+ /**
10
+ * Starts a run, calls `fn` with it, and finishes the run when `fn` settles.
11
+ * The run id is the caller's, or a new UUID. Library-internal: an app's use
12
+ * case opens its own run in `execute`. Replay uses it to put several units
13
+ * in one run.
14
+ *
15
+ * A failed `startRun` rejects before `fn` runs. A failed `finishRun` is logged,
16
+ * not thrown: the units are already recorded, and a rejection here would make
17
+ * a transport retry work that is done, for the sake of an end time.
18
+ */
19
+ export declare function withRun<T>(deps: JournalDeps, run: Pick<RunRow, 'job' | 'trigger' | 'mode'> & {
20
+ readonly runId?: RunId;
21
+ }, fn: (scope: RunScope) => Promise<T>): Promise<T>;
22
+ /**
23
+ * `UseCase.execute`'s body: opens the use case's own run, records one unit in
24
+ * it, and finishes it. Library-internal, so an app reaches it only through
25
+ * `execute`. `invoke` calls the use case's `run`; the queue consumer wraps it
26
+ * on a message's last attempt.
27
+ */
28
+ export declare function runUseCase<Input, Reason extends string, Deps>(useCase: Pick<UseCase<Input, string, Deps>, 'name' | 'unitType' | 'key'>, input: Input, { toolkit, trigger, deps, job, runId, mode, }: ExecuteOptions<Deps>, invoke: (context: UseCaseContext<Deps>) => Promise<Decision<Reason>>): Promise<Decision<Reason>>;
29
+ /**
30
+ * Records one unit in a run that `withRun` has open. Library-internal.
31
+ * `invoke` decides the unit; its decision and tracked calls are recorded.
32
+ */
33
+ export declare function runUnit<Input, Reason extends string, Deps>(useCase: Pick<UseCase<Input, string, Deps>, 'name' | 'unitType' | 'key'>, input: Input, scope: RunScope, deps: Deps, invoke: (context: UseCaseContext<Deps>) => Promise<Decision<Reason>>): Promise<Decision<Reason>>;
@@ -0,0 +1,117 @@
1
+ // Private, so a RunScope built by hand, which skipped startRun, cannot run a
2
+ // use case: a unit row with no run never shows in `recentRuns`.
3
+ const openRuns = new WeakMap();
4
+ /**
5
+ * Starts a run, calls `fn` with it, and finishes the run when `fn` settles.
6
+ * The run id is the caller's, or a new UUID. Library-internal: an app's use
7
+ * case opens its own run in `execute`. Replay uses it to put several units
8
+ * in one run.
9
+ *
10
+ * A failed `startRun` rejects before `fn` runs. A failed `finishRun` is logged,
11
+ * not thrown: the units are already recorded, and a rejection here would make
12
+ * a transport retry work that is done, for the sake of an end time.
13
+ */
14
+ export async function withRun(deps, run, fn) {
15
+ const runId = run.runId ?? crypto.randomUUID();
16
+ await deps.journal.startRun({
17
+ runId,
18
+ job: run.job,
19
+ trigger: run.trigger,
20
+ mode: run.mode,
21
+ startedAt: deps.clock.now(),
22
+ identity: deps.logger.identity,
23
+ });
24
+ const scope = { runId };
25
+ openRuns.set(scope, { deps, units: new Set() });
26
+ try {
27
+ return await fn(scope);
28
+ }
29
+ finally {
30
+ openRuns.delete(scope);
31
+ try {
32
+ await deps.journal.finishRun(runId, deps.clock.now());
33
+ }
34
+ catch (error) {
35
+ deps.logger.error('journal run not finished', {
36
+ runId,
37
+ error: String(error),
38
+ });
39
+ }
40
+ }
41
+ }
42
+ /**
43
+ * `UseCase.execute`'s body: opens the use case's own run, records one unit in
44
+ * it, and finishes it. Library-internal, so an app reaches it only through
45
+ * `execute`. `invoke` calls the use case's `run`; the queue consumer wraps it
46
+ * on a message's last attempt.
47
+ */
48
+ export async function runUseCase(useCase, input, { toolkit, trigger, deps, job = `${trigger}.${useCase.name}`, runId, mode = 'live', }, invoke) {
49
+ return withRun(toolkit, { job, trigger, mode, ...(runId !== undefined && { runId }) }, async (scope) => runUnit(useCase, input, scope, deps, invoke));
50
+ }
51
+ /**
52
+ * Records one unit in a run that `withRun` has open. Library-internal.
53
+ * `invoke` decides the unit; its decision and tracked calls are recorded.
54
+ */
55
+ export async function runUnit(useCase, input, scope, deps, invoke) {
56
+ const open = openRuns.get(scope);
57
+ if (open === undefined) {
58
+ throw new TypeError('a use case needs a run that withRun has open');
59
+ }
60
+ const unitKey = useCase.key(input);
61
+ if (open.units.has(unitKey)) {
62
+ throw new TypeError(`unit ${unitKey} has already run in ${scope.runId}`);
63
+ }
64
+ open.units.add(unitKey);
65
+ const { journal, clock, logger } = open.deps;
66
+ const { runId } = scope;
67
+ const startedAt = clock.now();
68
+ const calls = [];
69
+ const decision = await invoke({
70
+ deps,
71
+ logger: withFields(logger, { useCase: useCase.name, runId, unitKey }),
72
+ async track(system, operation, fn) {
73
+ const callStartedAt = clock.now();
74
+ const call = (status) => calls.push({
75
+ runId,
76
+ unitKey,
77
+ system,
78
+ operation,
79
+ status,
80
+ durationMs: clock.now() - callStartedAt,
81
+ });
82
+ try {
83
+ const result = await fn();
84
+ call('ok');
85
+ return result;
86
+ }
87
+ catch (error) {
88
+ call('failed');
89
+ throw error;
90
+ }
91
+ },
92
+ });
93
+ const recordedAt = clock.now();
94
+ await journal.recordUnit({
95
+ runId,
96
+ unitKey,
97
+ unitType: useCase.unitType,
98
+ recordedAt,
99
+ outcome: decision.outcome,
100
+ durationMs: recordedAt - startedAt,
101
+ ...(decision.outcome !== 'written' && {
102
+ reasonCode: decision.reasonCode,
103
+ }),
104
+ ...(decision.externalIds && { externalIds: decision.externalIds }),
105
+ }, calls);
106
+ return decision;
107
+ }
108
+ function withFields(logger, fields) {
109
+ return {
110
+ identity: logger.identity,
111
+ correlationId: logger.correlationId,
112
+ info: (message, more) => logger.info(message, { ...fields, ...more }),
113
+ warn: (message, more) => logger.warn(message, { ...fields, ...more }),
114
+ error: (message, more) => logger.error(message, { ...fields, ...more }),
115
+ child: (correlationId) => withFields(logger.child(correlationId), fields),
116
+ };
117
+ }
@@ -0,0 +1,44 @@
1
+ import type { QueueBatch, QueueConsumer, QueueMessage } from '../contracts/index.js';
2
+ import { type UseCase } from './use-case.js';
3
+ import { type JournalDeps } from './run-use-case.js';
4
+ export type UseCaseConsumerOptions<Deps> = {
5
+ /** Writes the journal and the fault log. A `Toolkit` is one. */
6
+ readonly toolkit: JournalDeps;
7
+ readonly deps: Deps;
8
+ /** The `job` of each message's run. Defaults to `queue.<name>`, for example `queue.order-tagger`. */
9
+ readonly job?: string;
10
+ /**
11
+ * The first retry's delay, doubled on each attempt after it, up to a day.
12
+ * Required: a redelivery with no delay meets a throttled API at once.
13
+ */
14
+ readonly retryDelaySeconds: number;
15
+ /**
16
+ * The queue's own limit, so the last attempt is known: Postgres
17
+ * `maxAttempts` (5 by default), Cloudflare `max_retries` + 1. Set it
18
+ * higher and a webhook task the queue dead-letters stays `failed`, where
19
+ * neither `deadTasks` nor `stuckTasks` finds it.
20
+ */
21
+ readonly maxAttempts: number;
22
+ };
23
+ /**
24
+ * The queue transport for a use case: one message, one run, one unit.
25
+ *
26
+ * A decision is acked unless it is `retryable`. A throw, a failed journal
27
+ * write among them, is logged and retried. Either way the message is settled
28
+ * on its own, and the rest of the batch is not run again.
29
+ *
30
+ * Each message's use case opens a run of its own (decision 0013). A body that
31
+ * `toInput` cannot parse is a fault: logged and retried, with no run.
32
+ */
33
+ export declare function createUseCaseConsumer<Input, Reason extends string, Deps>(useCase: UseCase<Input, Reason, Deps>, options: UseCaseConsumerOptions<Deps>): QueueConsumer<Input>;
34
+ /**
35
+ * Runs `useCase` on one message and settles it. On the last attempt a
36
+ * retryable decision or a throw is recorded as `failed`, `retries-exhausted`,
37
+ * and the message is still retried, so the queue dead-letters it.
38
+ *
39
+ * Resolves to why it retried: the last retryable reason code, or `fault` for
40
+ * a throw. Undefined when it acked.
41
+ */
42
+ export declare function settleUseCaseMessage<Body, Input, Reason extends string, Deps>(batch: QueueBatch<Body>, message: QueueMessage<Body>, useCase: UseCase<Input, Reason, Deps>, toInput: (body: Body) => Input | Promise<Input>, { toolkit, deps, job, retryDelaySeconds, maxAttempts, }: UseCaseConsumerOptions<Deps>): Promise<string | undefined>;
43
+ /** The delay before `attempt`'s retry: `retryDelaySeconds` doubled per attempt, up to a day. */
44
+ export declare const retryDelayFor: (attempt: number, retryDelaySeconds: number) => number;
@@ -0,0 +1,98 @@
1
+ import { failed, } from './use-case.js';
2
+ import { runUseCase } from './run-use-case.js';
3
+ // Cloudflare's queueDelayMaxSeconds, the lowest of the adapters'.
4
+ const MAX_RETRY_DELAY_SECONDS = 86_400;
5
+ /**
6
+ * The queue transport for a use case: one message, one run, one unit.
7
+ *
8
+ * A decision is acked unless it is `retryable`. A throw, a failed journal
9
+ * write among them, is logged and retried. Either way the message is settled
10
+ * on its own, and the rest of the batch is not run again.
11
+ *
12
+ * Each message's use case opens a run of its own (decision 0013). A body that
13
+ * `toInput` cannot parse is a fault: logged and retried, with no run.
14
+ */
15
+ export function createUseCaseConsumer(useCase, options) {
16
+ return async (batch) => {
17
+ for (const message of batch.messages) {
18
+ await settleUseCaseMessage(batch, message, useCase, (body) => body, options);
19
+ }
20
+ };
21
+ }
22
+ /**
23
+ * Runs `useCase` on one message and settles it. On the last attempt a
24
+ * retryable decision or a throw is recorded as `failed`, `retries-exhausted`,
25
+ * and the message is still retried, so the queue dead-letters it.
26
+ *
27
+ * Resolves to why it retried: the last retryable reason code, or `fault` for
28
+ * a throw. Undefined when it acked.
29
+ */
30
+ export async function settleUseCaseMessage(batch, message, useCase, toInput, { toolkit, deps, job, retryDelaySeconds, maxAttempts, }) {
31
+ const runId = crypto.randomUUID();
32
+ const exhausted = { yes: false };
33
+ const retry = () => {
34
+ batch.retry(message.id, {
35
+ delaySeconds: retryDelayFor(message.attempt, retryDelaySeconds),
36
+ });
37
+ };
38
+ try {
39
+ // Parsed outside the run: a body that cannot become input is a fault of
40
+ // the message, not a unit of work, so it opens no run.
41
+ const input = await toInput(message.body);
42
+ const options = {
43
+ toolkit,
44
+ trigger: 'queue',
45
+ deps,
46
+ runId,
47
+ ...(job !== undefined && { job }),
48
+ };
49
+ const decision = message.attempt >= maxAttempts
50
+ ? await runUseCase(useCase, input, options, exhaustRetries(useCase, input, exhausted))
51
+ : await useCase.execute(input, options);
52
+ if (exhausted.yes) {
53
+ retry();
54
+ return exhausted.reason;
55
+ }
56
+ if ('retryable' in decision && decision.retryable === true) {
57
+ retry();
58
+ return decision.reasonCode;
59
+ }
60
+ batch.ack(message.id);
61
+ return undefined;
62
+ }
63
+ catch (error) {
64
+ toolkit.logger.error('use case failed', {
65
+ useCase: useCase.name,
66
+ runId,
67
+ messageId: message.id,
68
+ error: String(error),
69
+ });
70
+ retry();
71
+ return 'fault';
72
+ }
73
+ }
74
+ /** The delay before `attempt`'s retry: `retryDelaySeconds` doubled per attempt, up to a day. */
75
+ export const retryDelayFor = (attempt, retryDelaySeconds) => Math.min(retryDelaySeconds * 2 ** (attempt - 1), MAX_RETRY_DELAY_SECONDS);
76
+ /** `useCase`'s `run`, with a retryable decision or a throw turned into `retries-exhausted`. */
77
+ function exhaustRetries(useCase, input, exhausted) {
78
+ return async (context) => {
79
+ let lastReason;
80
+ try {
81
+ // Bracket access reaches the protected `run`: the library's one caller
82
+ // outside `execute`, and it still records through `runUseCase`.
83
+ const decision = await useCase['run'](input, context);
84
+ if (!('retryable' in decision && decision.retryable === true)) {
85
+ return decision;
86
+ }
87
+ lastReason = decision.reasonCode;
88
+ exhausted.reason = decision.reasonCode;
89
+ }
90
+ catch (error) {
91
+ lastReason = String(error);
92
+ exhausted.reason = 'fault';
93
+ }
94
+ exhausted.yes = true;
95
+ context.logger.error('retries exhausted', { lastReason });
96
+ return failed('retries-exhausted');
97
+ };
98
+ }