@anatta.io/tva 0.1.0 → 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.
- package/README.md +1 -1
- package/dist/adapters/cloudflare/index.d.ts +3 -3
- package/dist/adapters/cloudflare/index.js +2 -2
- package/dist/adapters/cloudflare/journal.d.ts +14 -11
- package/dist/adapters/cloudflare/journal.js +43 -23
- package/dist/adapters/cloudflare/{jobs.d.ts → pipelines.d.ts} +23 -23
- package/dist/adapters/cloudflare/{jobs.js → pipelines.js} +21 -21
- package/dist/adapters/cloudflare/workflow-pipelines.d.ts +66 -0
- package/dist/adapters/cloudflare/{workflow-jobs.js → workflow-pipelines.js} +46 -42
- package/dist/adapters/journal-records.d.ts +2 -1
- package/dist/adapters/journal-records.js +3 -2
- package/dist/adapters/memory/index.d.ts +1 -1
- package/dist/adapters/memory/index.js +1 -1
- package/dist/adapters/memory/journal.d.ts +5 -4
- package/dist/adapters/memory/journal.js +32 -13
- package/dist/adapters/memory/manifest.d.ts +1 -1
- package/dist/adapters/memory/manifest.js +1 -1
- package/dist/adapters/memory/{jobs.d.ts → pipelines.d.ts} +16 -16
- package/dist/adapters/memory/{jobs.js → pipelines.js} +6 -6
- package/dist/adapters/postgres/journal.d.ts +14 -11
- package/dist/adapters/postgres/journal.js +46 -23
- package/dist/adapters/postgres/manifest.d.ts +1 -1
- package/dist/adapters/postgres/manifest.js +1 -1
- package/dist/adapters/reference-executor.d.ts +26 -26
- package/dist/adapters/reference-executor.js +62 -57
- package/dist/contracts/index.d.ts +1 -1
- package/dist/contracts/index.js +1 -1
- package/dist/contracts/journal.d.ts +26 -16
- package/dist/contracts/manifest.d.ts +2 -2
- package/dist/contracts/{jobs.d.ts → pipelines.d.ts} +64 -51
- package/dist/pipelines/index.d.ts +1 -0
- package/dist/pipelines/index.js +2 -0
- package/dist/pipelines/pipeline.d.ts +142 -0
- package/dist/pipelines/pipeline.js +140 -0
- package/dist/pipelines/use-case-step.d.ts +24 -0
- package/dist/pipelines/use-case-step.js +34 -0
- package/dist/use-cases/index.d.ts +3 -0
- package/dist/use-cases/index.js +3 -0
- package/dist/use-cases/run-use-case.d.ts +33 -0
- package/dist/{actions/run-action.js → use-cases/run-use-case.js} +22 -18
- package/dist/{actions/action-consumer.d.ts → use-cases/use-case-consumer.d.ts} +11 -12
- package/dist/use-cases/use-case-consumer.js +98 -0
- package/dist/use-cases/use-case.d.ts +116 -0
- package/dist/use-cases/use-case.js +75 -0
- package/dist/webhooks/create-webhook-handler.d.ts +6 -6
- package/dist/webhooks/create-webhook-handler.js +32 -25
- package/dist/webhooks/dead-letter-consumer.d.ts +1 -1
- package/dist/webhooks/dead-letter-consumer.js +5 -5
- package/dist/webhooks/define-registry.d.ts +13 -13
- package/dist/webhooks/define-registry.js +15 -15
- package/dist/webhooks/once.d.ts +3 -3
- package/dist/webhooks/once.js +5 -5
- package/dist/webhooks/redact-customer-bodies.d.ts +1 -1
- package/dist/webhooks/redact-customer-bodies.js +1 -1
- package/dist/webhooks/replay-webhooks.d.ts +8 -8
- package/dist/webhooks/replay-webhooks.js +29 -26
- package/dist/webhooks/sweep-stuck-tasks.d.ts +32 -0
- package/dist/webhooks/sweep-stuck-tasks.js +73 -0
- package/dist/webhooks/webhook-consumer.d.ts +19 -18
- package/dist/webhooks/webhook-consumer.js +29 -24
- package/migrations/0012_rename_webhook_task_action_to_use_case.sql +11 -0
- package/migrations/0013_rename_job_tables_to_pipeline.sql +24 -0
- package/migrations/0016_add_webhook_task_requeues.sql +3 -0
- package/migrations/postgres/0012_rename_webhook_task_action_to_use_case.sql +5 -0
- package/migrations/postgres/0013_rename_job_tables_to_pipeline.sql +22 -0
- package/migrations/postgres/0016_add_webhook_task_requeues.sql +3 -0
- package/package.json +13 -6
- package/dist/actions/action-consumer.js +0 -90
- package/dist/actions/action.d.ts +0 -67
- package/dist/actions/action.js +0 -12
- package/dist/actions/index.d.ts +0 -3
- package/dist/actions/index.js +0 -4
- package/dist/actions/run-action.d.ts +0 -31
- package/dist/adapters/cloudflare/workflow-jobs.d.ts +0 -57
- /package/dist/contracts/{jobs.js → pipelines.js} +0 -0
|
@@ -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,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,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>>;
|
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
// Private, so a RunScope built by hand, which skipped startRun, cannot run
|
|
2
|
-
//
|
|
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
3
|
const openRuns = new WeakMap();
|
|
4
4
|
/**
|
|
5
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.
|
|
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.
|
|
7
9
|
*
|
|
8
10
|
* A failed `startRun` rejects before `fn` runs. A failed `finishRun` is logged,
|
|
9
11
|
* not thrown: the units are already recorded, and a rejection here would make
|
|
@@ -38,22 +40,24 @@ export async function withRun(deps, run, fn) {
|
|
|
38
40
|
}
|
|
39
41
|
}
|
|
40
42
|
/**
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
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.
|
|
50
54
|
*/
|
|
51
|
-
export async function
|
|
55
|
+
export async function runUnit(useCase, input, scope, deps, invoke) {
|
|
52
56
|
const open = openRuns.get(scope);
|
|
53
57
|
if (open === undefined) {
|
|
54
|
-
throw new TypeError('
|
|
58
|
+
throw new TypeError('a use case needs a run that withRun has open');
|
|
55
59
|
}
|
|
56
|
-
const unitKey =
|
|
60
|
+
const unitKey = useCase.key(input);
|
|
57
61
|
if (open.units.has(unitKey)) {
|
|
58
62
|
throw new TypeError(`unit ${unitKey} has already run in ${scope.runId}`);
|
|
59
63
|
}
|
|
@@ -62,9 +66,9 @@ export async function runAction(action, input, scope, deps) {
|
|
|
62
66
|
const { runId } = scope;
|
|
63
67
|
const startedAt = clock.now();
|
|
64
68
|
const calls = [];
|
|
65
|
-
const decision = await
|
|
69
|
+
const decision = await invoke({
|
|
66
70
|
deps,
|
|
67
|
-
logger: withFields(logger, {
|
|
71
|
+
logger: withFields(logger, { useCase: useCase.name, runId, unitKey }),
|
|
68
72
|
async track(system, operation, fn) {
|
|
69
73
|
const callStartedAt = clock.now();
|
|
70
74
|
const call = (status) => calls.push({
|
|
@@ -90,7 +94,7 @@ export async function runAction(action, input, scope, deps) {
|
|
|
90
94
|
await journal.recordUnit({
|
|
91
95
|
runId,
|
|
92
96
|
unitKey,
|
|
93
|
-
unitType:
|
|
97
|
+
unitType: useCase.unitType,
|
|
94
98
|
recordedAt,
|
|
95
99
|
outcome: decision.outcome,
|
|
96
100
|
durationMs: recordedAt - startedAt,
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import type { QueueBatch, QueueConsumer, QueueMessage } from '../contracts/index.js';
|
|
2
|
-
import { type
|
|
3
|
-
import { type JournalDeps } from './run-
|
|
4
|
-
export type
|
|
2
|
+
import { type UseCase } from './use-case.js';
|
|
3
|
+
import { type JournalDeps } from './run-use-case.js';
|
|
4
|
+
export type UseCaseConsumerOptions<Deps> = {
|
|
5
5
|
/** Writes the journal and the fault log. A `Toolkit` is one. */
|
|
6
6
|
readonly toolkit: JournalDeps;
|
|
7
7
|
readonly deps: Deps;
|
|
8
|
-
/** The `job` of each message's run
|
|
9
|
-
readonly job
|
|
8
|
+
/** The `job` of each message's run. Defaults to `queue.<name>`, for example `queue.order-tagger`. */
|
|
9
|
+
readonly job?: string;
|
|
10
10
|
/**
|
|
11
11
|
* The first retry's delay, doubled on each attempt after it, up to a day.
|
|
12
12
|
* Required: a redelivery with no delay meets a throttled API at once.
|
|
@@ -21,25 +21,24 @@ export type ActionConsumerOptions<Deps> = {
|
|
|
21
21
|
readonly maxAttempts: number;
|
|
22
22
|
};
|
|
23
23
|
/**
|
|
24
|
-
* The queue transport for
|
|
24
|
+
* The queue transport for a use case: one message, one run, one unit.
|
|
25
25
|
*
|
|
26
26
|
* A decision is acked unless it is `retryable`. A throw, a failed journal
|
|
27
27
|
* write among them, is logged and retried. Either way the message is settled
|
|
28
28
|
* on its own, and the rest of the batch is not run again.
|
|
29
29
|
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
* `runAction`'s one-unit-per-run rule and spend a retry.
|
|
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.
|
|
33
32
|
*/
|
|
34
|
-
export declare function
|
|
33
|
+
export declare function createUseCaseConsumer<Input, Reason extends string, Deps>(useCase: UseCase<Input, Reason, Deps>, options: UseCaseConsumerOptions<Deps>): QueueConsumer<Input>;
|
|
35
34
|
/**
|
|
36
|
-
* Runs `
|
|
35
|
+
* Runs `useCase` on one message and settles it. On the last attempt a
|
|
37
36
|
* retryable decision or a throw is recorded as `failed`, `retries-exhausted`,
|
|
38
37
|
* and the message is still retried, so the queue dead-letters it.
|
|
39
38
|
*
|
|
40
39
|
* Resolves to why it retried: the last retryable reason code, or `fault` for
|
|
41
40
|
* a throw. Undefined when it acked.
|
|
42
41
|
*/
|
|
43
|
-
export declare function
|
|
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>;
|
|
44
43
|
/** The delay before `attempt`'s retry: `retryDelaySeconds` doubled per attempt, up to a day. */
|
|
45
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
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import type { Logger, RunId, RunRow, UnitKey } from '../contracts/index.js';
|
|
2
|
+
import { type JournalDeps } from './run-use-case.js';
|
|
3
|
+
/**
|
|
4
|
+
* A USE CASE IS ONE UNIT OF WORK WITH ONE OBSERVABLE OUTCOME, whatever
|
|
5
|
+
* triggered it. It takes typed input and returns a Decision: what the system
|
|
6
|
+
* chose to do with one unit, and why. Name it VerbNoun in the business's
|
|
7
|
+
* words, for example `TagOrder`. It orchestrates; the pure decision logic it
|
|
8
|
+
* calls is a Rule. Extend this class and write `run`; it never writes to the
|
|
9
|
+
* journal. `execute` is the only way to call it: it opens the use case's own
|
|
10
|
+
* journal run and records the decision in it, so the record does not depend
|
|
11
|
+
* on the author or the trigger remembering to write it (#94, decision 0013).
|
|
12
|
+
* `run` is protected, so no caller can skip `execute`.
|
|
13
|
+
*
|
|
14
|
+
* Hold no per-call state on `this`: one instance serves every message, and
|
|
15
|
+
* concurrent ones share it. Per-call state lives in `run`'s locals and its
|
|
16
|
+
* `UseCaseContext`. For a one-off use case, `defineUseCase` takes a plain object.
|
|
17
|
+
*
|
|
18
|
+
* A use case runs inline and reaches one outcome per unit. Work that needs
|
|
19
|
+
* retries between its steps, or must survive a restart part way through, is a
|
|
20
|
+
* `PipelineDefinition`.
|
|
21
|
+
*
|
|
22
|
+
* Cleanup happens inside `run`: free what it claimed, then return the
|
|
23
|
+
* decision.
|
|
24
|
+
*/
|
|
25
|
+
export declare abstract class UseCase<Input, Reason extends string, Deps> {
|
|
26
|
+
/** Added to every log line the use case writes. */
|
|
27
|
+
abstract readonly name: string;
|
|
28
|
+
/** The journal's `unitType`, for example `order`. */
|
|
29
|
+
abstract readonly unitType: string;
|
|
30
|
+
constructor();
|
|
31
|
+
/** The journal's unit key. A pure function of the input. */
|
|
32
|
+
abstract key(input: Input): UnitKey;
|
|
33
|
+
/** The domain logic: decide what to do with one unit. */
|
|
34
|
+
protected abstract run(input: Input, context: UseCaseContext<Deps>): Promise<Decision<Reason>>;
|
|
35
|
+
/**
|
|
36
|
+
* Runs the use case in a journal run of its own: starts the run, times the
|
|
37
|
+
* unit, collects the calls it tracks, records its decision and finishes the
|
|
38
|
+
* run. One call, one run, one unit.
|
|
39
|
+
*
|
|
40
|
+
* A throw from `run` records no unit and is rethrown: a fault is not a
|
|
41
|
+
* decision, and the trigger decides what it means. A rejected `startRun` or
|
|
42
|
+
* `recordUnit` reaches the caller too, so a queue consumer retries the
|
|
43
|
+
* message. A rejected `finishRun` is logged, not thrown: the decision is
|
|
44
|
+
* already recorded.
|
|
45
|
+
*/
|
|
46
|
+
execute(input: Input, options: ExecuteOptions<Deps>): Promise<Decision<Reason>>;
|
|
47
|
+
}
|
|
48
|
+
/** A one-off use case as a plain object, for `defineUseCase`. */
|
|
49
|
+
export type UseCaseDefinition<Input, Reason extends string, Deps> = {
|
|
50
|
+
readonly name: string;
|
|
51
|
+
readonly unitType: string;
|
|
52
|
+
readonly key: (input: Input) => UnitKey;
|
|
53
|
+
readonly run: (input: Input, context: UseCaseContext<Deps>) => Promise<Decision<Reason>>;
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* A use case from a plain object, for one that is not worth a class: a test,
|
|
57
|
+
* or a unit whose decision is already made. Its `run` is still reachable only
|
|
58
|
+
* through `execute`.
|
|
59
|
+
*/
|
|
60
|
+
export declare function defineUseCase<Input, Reason extends string, Deps>(definition: UseCaseDefinition<Input, Reason, Deps>): UseCase<Input, Reason, Deps>;
|
|
61
|
+
/** What `execute` needs to open the use case's run, and the use case's deps. */
|
|
62
|
+
export type ExecuteOptions<Deps> = {
|
|
63
|
+
/** Writes the run, the unit and the log lines. A `Toolkit` is one. */
|
|
64
|
+
readonly toolkit: JournalDeps;
|
|
65
|
+
/** What started this call: a route, a queue message, a schedule, a replay. */
|
|
66
|
+
readonly trigger: RunRow['trigger'];
|
|
67
|
+
/** Passed to `run` as `context.deps`. */
|
|
68
|
+
readonly deps: Deps;
|
|
69
|
+
/** The run's `job`. Defaults to `<trigger>.<name>`, for example `queue.order-tagger`. */
|
|
70
|
+
readonly job?: string;
|
|
71
|
+
/** The run's id. Defaults to a new UUID; pass one to log it before the run starts. */
|
|
72
|
+
readonly runId?: RunId;
|
|
73
|
+
/** Defaults to `live`. */
|
|
74
|
+
readonly mode?: RunRow['mode'];
|
|
75
|
+
};
|
|
76
|
+
export type UseCaseContext<Deps> = {
|
|
77
|
+
readonly deps: Deps;
|
|
78
|
+
/** Adds `useCase`, `runId` and `unitKey` to every line. */
|
|
79
|
+
readonly logger: Logger;
|
|
80
|
+
/**
|
|
81
|
+
* Calls `fn` and records it as an `ok` or `failed` call with its duration.
|
|
82
|
+
* Returns what `fn` returns, and rethrows what it throws. A property, not a
|
|
83
|
+
* method, so a use case can destructure it from the context.
|
|
84
|
+
*/
|
|
85
|
+
readonly track: <T>(system: string, operation: string, fn: () => Promise<T>) => Promise<T>;
|
|
86
|
+
};
|
|
87
|
+
type DecisionExtras = {
|
|
88
|
+
readonly externalIds?: Readonly<Record<string, string>>;
|
|
89
|
+
};
|
|
90
|
+
type RetryableExtras = DecisionExtras & {
|
|
91
|
+
/**
|
|
92
|
+
* Try the unit again later: a queue retries the message, and an HTTP
|
|
93
|
+
* transport answers 500. Same word as `ToolFault.retryable`.
|
|
94
|
+
*/
|
|
95
|
+
readonly retryable?: boolean;
|
|
96
|
+
};
|
|
97
|
+
/**
|
|
98
|
+
* Every outcome but `written` carries a reason code from the domain's closed
|
|
99
|
+
* list, and only `failed` and `skipped` can be retryable: an `unchanged` unit
|
|
100
|
+
* has nothing left to do. A throw is not a decision: it is a fault, it records
|
|
101
|
+
* nothing, and the transport retries it.
|
|
102
|
+
*/
|
|
103
|
+
export type Decision<Reason extends string> = ({
|
|
104
|
+
readonly outcome: 'written';
|
|
105
|
+
} & DecisionExtras) | ({
|
|
106
|
+
readonly outcome: 'failed' | 'skipped';
|
|
107
|
+
readonly reasonCode: Reason;
|
|
108
|
+
} & RetryableExtras) | ({
|
|
109
|
+
readonly outcome: 'unchanged' | 'would-write';
|
|
110
|
+
readonly reasonCode: Reason;
|
|
111
|
+
} & DecisionExtras);
|
|
112
|
+
export declare function written(extras?: DecisionExtras): Decision<never>;
|
|
113
|
+
export declare function skipped<R extends string>(reasonCode: R, extras?: RetryableExtras): Decision<R>;
|
|
114
|
+
export declare function failed<R extends string>(reasonCode: R, extras?: RetryableExtras): Decision<R>;
|
|
115
|
+
export declare function unchanged<R extends string>(reasonCode: R, extras?: DecisionExtras): Decision<R>;
|
|
116
|
+
export {};
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { runUseCase } from './run-use-case.js';
|
|
2
|
+
/**
|
|
3
|
+
* A USE CASE IS ONE UNIT OF WORK WITH ONE OBSERVABLE OUTCOME, whatever
|
|
4
|
+
* triggered it. It takes typed input and returns a Decision: what the system
|
|
5
|
+
* chose to do with one unit, and why. Name it VerbNoun in the business's
|
|
6
|
+
* words, for example `TagOrder`. It orchestrates; the pure decision logic it
|
|
7
|
+
* calls is a Rule. Extend this class and write `run`; it never writes to the
|
|
8
|
+
* journal. `execute` is the only way to call it: it opens the use case's own
|
|
9
|
+
* journal run and records the decision in it, so the record does not depend
|
|
10
|
+
* on the author or the trigger remembering to write it (#94, decision 0013).
|
|
11
|
+
* `run` is protected, so no caller can skip `execute`.
|
|
12
|
+
*
|
|
13
|
+
* Hold no per-call state on `this`: one instance serves every message, and
|
|
14
|
+
* concurrent ones share it. Per-call state lives in `run`'s locals and its
|
|
15
|
+
* `UseCaseContext`. For a one-off use case, `defineUseCase` takes a plain object.
|
|
16
|
+
*
|
|
17
|
+
* A use case runs inline and reaches one outcome per unit. Work that needs
|
|
18
|
+
* retries between its steps, or must survive a restart part way through, is a
|
|
19
|
+
* `PipelineDefinition`.
|
|
20
|
+
*
|
|
21
|
+
* Cleanup happens inside `run`: free what it claimed, then return the
|
|
22
|
+
* decision.
|
|
23
|
+
*/
|
|
24
|
+
export class UseCase {
|
|
25
|
+
constructor() {
|
|
26
|
+
// TypeScript has no `final`. An override of `execute` could skip the
|
|
27
|
+
// journal, which is what this class exists to prevent.
|
|
28
|
+
if (this.execute !== UseCase.prototype.execute) {
|
|
29
|
+
throw new TypeError(`${new.target.name} must not override execute`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Runs the use case in a journal run of its own: starts the run, times the
|
|
34
|
+
* unit, collects the calls it tracks, records its decision and finishes the
|
|
35
|
+
* run. One call, one run, one unit.
|
|
36
|
+
*
|
|
37
|
+
* A throw from `run` records no unit and is rethrown: a fault is not a
|
|
38
|
+
* decision, and the trigger decides what it means. A rejected `startRun` or
|
|
39
|
+
* `recordUnit` reaches the caller too, so a queue consumer retries the
|
|
40
|
+
* message. A rejected `finishRun` is logged, not thrown: the decision is
|
|
41
|
+
* already recorded.
|
|
42
|
+
*/
|
|
43
|
+
async execute(input, options) {
|
|
44
|
+
return runUseCase(this, input, options, async (context) => this.run(input, context));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* A use case from a plain object, for one that is not worth a class: a test,
|
|
49
|
+
* or a unit whose decision is already made. Its `run` is still reachable only
|
|
50
|
+
* through `execute`.
|
|
51
|
+
*/
|
|
52
|
+
export function defineUseCase(definition) {
|
|
53
|
+
return new (class extends UseCase {
|
|
54
|
+
name = definition.name;
|
|
55
|
+
unitType = definition.unitType;
|
|
56
|
+
key(input) {
|
|
57
|
+
return definition.key(input);
|
|
58
|
+
}
|
|
59
|
+
async run(input, context) {
|
|
60
|
+
return definition.run(input, context);
|
|
61
|
+
}
|
|
62
|
+
})();
|
|
63
|
+
}
|
|
64
|
+
export function written(extras = {}) {
|
|
65
|
+
return { outcome: 'written', ...extras };
|
|
66
|
+
}
|
|
67
|
+
export function skipped(reasonCode, extras = {}) {
|
|
68
|
+
return { outcome: 'skipped', reasonCode, ...extras };
|
|
69
|
+
}
|
|
70
|
+
export function failed(reasonCode, extras = {}) {
|
|
71
|
+
return { outcome: 'failed', reasonCode, ...extras };
|
|
72
|
+
}
|
|
73
|
+
export function unchanged(reasonCode, extras = {}) {
|
|
74
|
+
return { outcome: 'unchanged', reasonCode, ...extras };
|
|
75
|
+
}
|