@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
|
@@ -17,8 +17,9 @@ const TOOL = 'journal';
|
|
|
17
17
|
* failuresByReason journal_units_recorded_at
|
|
18
18
|
* delivery webhook_deliveries_pkey, webhook_tasks_pkey
|
|
19
19
|
* deadTasks webhook_tasks_state
|
|
20
|
-
*
|
|
20
|
+
* deadTasksByUseCase webhook_tasks_use_case_state
|
|
21
21
|
* stuckTasks webhook_tasks_state
|
|
22
|
+
* reclaimStuckTask webhook_tasks_pkey or webhook_tasks_action_state
|
|
22
23
|
*/
|
|
23
24
|
const Q = {
|
|
24
25
|
startRun: `
|
|
@@ -100,34 +101,46 @@ const Q = {
|
|
|
100
101
|
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
|
101
102
|
ON CONFLICT (delivery_id) DO NOTHING
|
|
102
103
|
)
|
|
103
|
-
INSERT INTO webhook_tasks (delivery_id,
|
|
104
|
-
SELECT $1,
|
|
105
|
-
ON CONFLICT (delivery_id,
|
|
104
|
+
INSERT INTO webhook_tasks (delivery_id, use_case, state, updated_at)
|
|
105
|
+
SELECT $1, use_case, 'received', $7 FROM unnest($8::text[]) AS use_case
|
|
106
|
+
ON CONFLICT (delivery_id, use_case) DO NOTHING
|
|
106
107
|
`,
|
|
107
108
|
// $5 is the states TASK_TRANSITIONS allows the move from.
|
|
108
109
|
moveTask: `
|
|
109
|
-
UPDATE webhook_tasks SET state = $3, updated_at = $4, reason_code = $6
|
|
110
|
-
|
|
110
|
+
UPDATE webhook_tasks SET state = $3, updated_at = $4, reason_code = $6,
|
|
111
|
+
requeues = CASE WHEN $3 = 'replayed' THEN 0 ELSE requeues END
|
|
112
|
+
WHERE delivery_id = $1 AND use_case = $2 AND state = ANY($5::text[])
|
|
111
113
|
`,
|
|
112
114
|
delivery: `SELECT * FROM webhook_deliveries WHERE delivery_id = $1`,
|
|
113
115
|
tasksForDelivery: `
|
|
114
|
-
SELECT * FROM webhook_tasks WHERE delivery_id = $1 ORDER BY
|
|
116
|
+
SELECT * FROM webhook_tasks WHERE delivery_id = $1 ORDER BY use_case
|
|
115
117
|
`,
|
|
116
118
|
deadTasks: `
|
|
117
119
|
SELECT * FROM webhook_tasks
|
|
118
|
-
WHERE state = 'dead' AND (updated_at, delivery_id,
|
|
119
|
-
ORDER BY updated_at, delivery_id,
|
|
120
|
+
WHERE state = 'dead' AND (updated_at, delivery_id, use_case) > ($1, $2, $3)
|
|
121
|
+
ORDER BY updated_at, delivery_id, use_case LIMIT $4
|
|
120
122
|
`,
|
|
121
|
-
|
|
123
|
+
deadTasksByUseCase: `
|
|
122
124
|
SELECT * FROM webhook_tasks
|
|
123
|
-
WHERE
|
|
124
|
-
AND (updated_at, delivery_id,
|
|
125
|
+
WHERE use_case = $5 AND state = 'dead'
|
|
126
|
+
AND (updated_at, delivery_id, use_case) > ($1, $2, $3)
|
|
125
127
|
ORDER BY updated_at, delivery_id LIMIT $4
|
|
126
128
|
`,
|
|
127
129
|
stuckTasks: `
|
|
128
130
|
SELECT * FROM webhook_tasks
|
|
129
|
-
WHERE state IN ('received', 'processing') AND updated_at < $1
|
|
130
|
-
ORDER BY updated_at, delivery_id,
|
|
131
|
+
WHERE state IN ('received', 'processing', 'replayed') AND updated_at < $1
|
|
132
|
+
ORDER BY updated_at, delivery_id, use_case LIMIT $2
|
|
133
|
+
`,
|
|
134
|
+
// The state and updated_at the sweeper read are re-checked in the write, so
|
|
135
|
+
// a task that moved since, or another sweeper's claim, makes it change no row.
|
|
136
|
+
reclaimStuckTask: `
|
|
137
|
+
UPDATE webhook_tasks SET
|
|
138
|
+
updated_at = $5,
|
|
139
|
+
state = CASE WHEN $4 = 'dead' THEN 'dead' ELSE state END,
|
|
140
|
+
reason_code = CASE WHEN $4 = 'dead' THEN 'stuck' ELSE reason_code END,
|
|
141
|
+
requeues = CASE WHEN $4 = 'dead' THEN requeues ELSE requeues + 1 END
|
|
142
|
+
WHERE delivery_id = $1 AND use_case = $2 AND updated_at = $3
|
|
143
|
+
AND state IN ('received', 'processing', 'replayed')
|
|
131
144
|
`,
|
|
132
145
|
};
|
|
133
146
|
export class PostgresJournal {
|
|
@@ -255,7 +268,7 @@ export class PostgresJournal {
|
|
|
255
268
|
const { rows } = await this.#call('recentRuns', async () => this.o.pool.query(Q.recentRuns, [limit]));
|
|
256
269
|
return rows.map(toRunRow);
|
|
257
270
|
}
|
|
258
|
-
async recordDelivery(delivery,
|
|
271
|
+
async recordDelivery(delivery, useCases) {
|
|
259
272
|
await this.#call('recordDelivery', async () => this.o.pool.query(Q.recordDelivery, [
|
|
260
273
|
delivery.deliveryId,
|
|
261
274
|
delivery.source,
|
|
@@ -264,13 +277,13 @@ export class PostgresJournal {
|
|
|
264
277
|
delivery.webhookId,
|
|
265
278
|
delivery.bodyKey,
|
|
266
279
|
delivery.receivedAt,
|
|
267
|
-
|
|
280
|
+
useCases,
|
|
268
281
|
]));
|
|
269
282
|
}
|
|
270
|
-
async moveTask(deliveryId,
|
|
283
|
+
async moveTask(deliveryId, useCase, to, at, reasonCode) {
|
|
271
284
|
const { rowCount } = await this.#call('moveTask', async () => this.o.pool.query(Q.moveTask, [
|
|
272
285
|
deliveryId,
|
|
273
|
-
|
|
286
|
+
useCase,
|
|
274
287
|
to,
|
|
275
288
|
at,
|
|
276
289
|
TASK_TRANSITIONS[to],
|
|
@@ -288,13 +301,13 @@ export class PostgresJournal {
|
|
|
288
301
|
? undefined
|
|
289
302
|
: { delivery: toDeliveryRow(record), tasks: tasks.rows.map(toTaskRow) };
|
|
290
303
|
}
|
|
291
|
-
async deadTasks({
|
|
292
|
-
const cursor = [after.updatedAt, after.deliveryId, after.
|
|
293
|
-
const { rows } = await this.#call('deadTasks', async () =>
|
|
304
|
+
async deadTasks({ useCase, after = FIRST_TASK, limit = DEFAULT_UNIT_LIMIT, } = {}) {
|
|
305
|
+
const cursor = [after.updatedAt, after.deliveryId, after.useCase, limit];
|
|
306
|
+
const { rows } = await this.#call('deadTasks', async () => useCase === undefined
|
|
294
307
|
? this.o.pool.query(Q.deadTasks, cursor)
|
|
295
|
-
: this.o.pool.query(Q.
|
|
308
|
+
: this.o.pool.query(Q.deadTasksByUseCase, [
|
|
296
309
|
...cursor,
|
|
297
|
-
|
|
310
|
+
useCase,
|
|
298
311
|
]));
|
|
299
312
|
return rows.map(toTaskRow);
|
|
300
313
|
}
|
|
@@ -302,6 +315,16 @@ export class PostgresJournal {
|
|
|
302
315
|
const { rows } = await this.#call('stuckTasks', async () => this.o.pool.query(Q.stuckTasks, [before, limit]));
|
|
303
316
|
return rows.map(toTaskRow);
|
|
304
317
|
}
|
|
318
|
+
async reclaimStuckTask(task, at, to) {
|
|
319
|
+
const { rowCount } = await this.#call('reclaimStuckTask', async () => this.o.pool.query(Q.reclaimStuckTask, [
|
|
320
|
+
task.deliveryId,
|
|
321
|
+
task.useCase,
|
|
322
|
+
task.updatedAt,
|
|
323
|
+
to,
|
|
324
|
+
at,
|
|
325
|
+
]));
|
|
326
|
+
return rowCount === 1;
|
|
327
|
+
}
|
|
305
328
|
async #call(operation, f) {
|
|
306
329
|
try {
|
|
307
330
|
return await f();
|
|
@@ -43,7 +43,7 @@ export declare const POSTGRES_MANIFEST: {
|
|
|
43
43
|
readonly scheduleMinIntervalSeconds: 1;
|
|
44
44
|
/**
|
|
45
45
|
* 1 MiB, the same as Workflows and the memory adapter. This target has no
|
|
46
|
-
*
|
|
46
|
+
* Pipelines executor yet. When it has one, a result is TEXT like every JSON
|
|
47
47
|
* column here (decision 0007), which holds about 1 GB, so this is the
|
|
48
48
|
* library's limit, not Postgres's. A larger one would let a step pass on
|
|
49
49
|
* Postgres and fail on Workflows.
|
|
@@ -44,7 +44,7 @@ export const POSTGRES_MANIFEST = {
|
|
|
44
44
|
scheduleMinIntervalSeconds: 1,
|
|
45
45
|
/**
|
|
46
46
|
* 1 MiB, the same as Workflows and the memory adapter. This target has no
|
|
47
|
-
*
|
|
47
|
+
* Pipelines executor yet. When it has one, a result is TEXT like every JSON
|
|
48
48
|
* column here (decision 0007), which holds about 1 GB, so this is the
|
|
49
49
|
* library's limit, not Postgres's. A larger one would let a step pass on
|
|
50
50
|
* Postgres and fail on Workflows.
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import type { Clock, DispatchOptions, DispatchResult, Exhaustion, Instant,
|
|
1
|
+
import type { Clock, DispatchOptions, DispatchResult, Exhaustion, Instant, PipelineDefinition, PipelineInstanceId, PipelineRegistration, PipelineStatus, Pipelines, Journal, JsonValue, Logger, Queue, QueueBatch, ToolManifest } from '../contracts/index.js';
|
|
2
2
|
/**
|
|
3
3
|
* THE REFERENCE EXECUTOR'S ALGORITHM, ONCE, FOR EVERY ADAPTER THAT SHIPS IT.
|
|
4
4
|
*
|
|
5
5
|
* docs/decisions/0006 is the specification. This file is that protocol and
|
|
6
|
-
* nothing else: every adapter that runs
|
|
6
|
+
* nothing else: every adapter that runs Pipelines without a native executor (the
|
|
7
7
|
* memory adapter, D1 on Cloudflare, Postgres later) builds this class over its
|
|
8
8
|
* own `ReferenceStore` and its own queue. Two executors that share a name but
|
|
9
9
|
* not an algorithm double the bugs (#69), so the storage is the only thing an
|
|
@@ -14,14 +14,14 @@ import type { Clock, DispatchOptions, DispatchResult, Exhaustion, Instant, Job,
|
|
|
14
14
|
*/
|
|
15
15
|
/** A wake-up. The state tables are the truth; a message only says "look". */
|
|
16
16
|
export type WakeUp = {
|
|
17
|
-
readonly instanceId:
|
|
17
|
+
readonly instanceId: PipelineInstanceId;
|
|
18
18
|
readonly stepIndex: number;
|
|
19
19
|
};
|
|
20
|
-
/** The `status` column of `
|
|
20
|
+
/** The `status` column of `pipeline_instances` (decision 0006). */
|
|
21
21
|
export type InstanceState = 'running' | 'failing' | 'completed' | 'failed';
|
|
22
22
|
/**
|
|
23
|
-
* One row of `
|
|
24
|
-
* `Clock`. `input` is the
|
|
23
|
+
* One row of `pipeline_instances`. Times are epoch milliseconds from the injected
|
|
24
|
+
* `Clock`. `input` is the Pipeline input as JSON.
|
|
25
25
|
*
|
|
26
26
|
* `cause` is not one of decision 0006's columns. Without it the exhaustion
|
|
27
27
|
* handler cannot be told whether a step was terminal, ran out of retries or
|
|
@@ -29,8 +29,8 @@ export type InstanceState = 'running' | 'failing' | 'completed' | 'failed';
|
|
|
29
29
|
* only when the cause is `terminal`.
|
|
30
30
|
*/
|
|
31
31
|
export type InstanceRow = {
|
|
32
|
-
readonly instanceId:
|
|
33
|
-
readonly
|
|
32
|
+
readonly instanceId: PipelineInstanceId;
|
|
33
|
+
readonly pipeline: string;
|
|
34
34
|
readonly input: string;
|
|
35
35
|
readonly runId: string;
|
|
36
36
|
readonly unitKey: string;
|
|
@@ -49,15 +49,15 @@ export type InstanceRow = {
|
|
|
49
49
|
export type InstanceChange = Partial<Pick<InstanceRow, 'status' | 'cause' | 'reasonCode' | 'currentStep' | 'attempts' | 'leaseExpiresAt' | 'nextWakeAt' | 'endedAt'>>;
|
|
50
50
|
/**
|
|
51
51
|
* THE ONLY THING AN ADAPTER IMPLEMENTS. The two tables of decision 0006,
|
|
52
|
-
* `
|
|
52
|
+
* `pipeline_instances` and `pipeline_steps`, behind the writes the protocol makes.
|
|
53
53
|
*
|
|
54
54
|
* This is not a tool and has no conformance suite of its own: 0006 rejected a
|
|
55
|
-
* `
|
|
55
|
+
* `PipelineStore` tool, and the Pipelines suite tests it through the executor. It is
|
|
56
56
|
* the seam that keeps the algorithm in one place.
|
|
57
57
|
*
|
|
58
58
|
* NO ADAPTER NEEDS A TRANSACTION. Every method but two writes one table.
|
|
59
59
|
* `remove` and `removeEndedBefore` write both, and each one deletes in a fixed
|
|
60
|
-
* order: the `
|
|
60
|
+
* order: the `pipeline_steps` rows first, then the `pipeline_instances` row, both only
|
|
61
61
|
* for an instance whose `ended_at` is at or before the cutoff. A crash between
|
|
62
62
|
* the two deletes leaves an ended instance with no stored results, which the
|
|
63
63
|
* next removal deletes. A new instance cannot take the id while the old
|
|
@@ -68,35 +68,35 @@ export type InstanceChange = Partial<Pick<InstanceRow, 'status' | 'cause' | 'rea
|
|
|
68
68
|
export interface ReferenceStore {
|
|
69
69
|
/** Inserts the row, or reports that its id is already taken. */
|
|
70
70
|
insert(row: InstanceRow): Promise<'inserted' | 'exists'>;
|
|
71
|
-
get(id:
|
|
71
|
+
get(id: PipelineInstanceId): Promise<InstanceRow | undefined>;
|
|
72
72
|
/**
|
|
73
73
|
* `UPDATE … WHERE instance_id = ? AND version = ?`, which also sets
|
|
74
74
|
* `version = version + 1`. Exactly one more: the executor computes the
|
|
75
75
|
* row's next version itself and conditions its next write on it. False
|
|
76
76
|
* when the version did not match: another consumer won.
|
|
77
77
|
*/
|
|
78
|
-
update(id:
|
|
78
|
+
update(id: PipelineInstanceId, version: number, change: InstanceChange): Promise<boolean>;
|
|
79
79
|
/**
|
|
80
80
|
* Deletes the instance and its stored results if it ended at or before
|
|
81
|
-
* `cutoff`: the `
|
|
81
|
+
* `cutoff`: the `pipeline_steps` rows first, then the instance row (above). Used
|
|
82
82
|
* only for an instance whose retention has passed.
|
|
83
83
|
*/
|
|
84
|
-
remove(id:
|
|
84
|
+
remove(id: PipelineInstanceId, cutoff: Instant): Promise<void>;
|
|
85
85
|
/**
|
|
86
|
-
* `INSERT OR IGNORE` into `
|
|
86
|
+
* `INSERT OR IGNORE` into `pipeline_steps`: the first result stored for a step
|
|
87
87
|
* is the one that stays. `result` is the step result as JSON.
|
|
88
88
|
*/
|
|
89
|
-
storeResult(id:
|
|
89
|
+
storeResult(id: PipelineInstanceId, stepIndex: number, result: string, completedAt: Instant): Promise<void>;
|
|
90
90
|
/** The stored results of the instance, as JSON, by step index. */
|
|
91
|
-
results(id:
|
|
91
|
+
results(id: PipelineInstanceId): Promise<ReadonlyMap<number, string>>;
|
|
92
92
|
/**
|
|
93
93
|
* `status IN ('running', 'failing') AND next_wake_at <= now AND
|
|
94
94
|
* (lease_expires_at IS NULL OR lease_expires_at <= now)`.
|
|
95
95
|
*/
|
|
96
96
|
due(now: Instant): Promise<readonly InstanceRow[]>;
|
|
97
97
|
/**
|
|
98
|
-
* Instances with `ended_at <= cutoff`, with their `
|
|
99
|
-
* `
|
|
98
|
+
* Instances with `ended_at <= cutoff`, with their `pipeline_steps` rows: the
|
|
99
|
+
* `pipeline_steps` rows first, then the instance rows (above).
|
|
100
100
|
*/
|
|
101
101
|
removeEndedBefore(cutoff: Instant): Promise<void>;
|
|
102
102
|
}
|
|
@@ -112,11 +112,11 @@ export type ExecutorWindow = 'after-dispatch-insert' | 'before-result-stored' |
|
|
|
112
112
|
* code passes nothing.
|
|
113
113
|
*/
|
|
114
114
|
export type Interrupt = (window: ExecutorWindow, at: {
|
|
115
|
-
readonly instanceId:
|
|
115
|
+
readonly instanceId: PipelineInstanceId;
|
|
116
116
|
readonly stepIndex: number;
|
|
117
117
|
}) => Promise<void> | undefined;
|
|
118
118
|
export type ReferenceExecutorOptions = {
|
|
119
|
-
readonly registrations: readonly
|
|
119
|
+
readonly registrations: readonly PipelineRegistration[];
|
|
120
120
|
readonly store: ReferenceStore;
|
|
121
121
|
readonly queue: Queue<WakeUp>;
|
|
122
122
|
readonly clock: Clock;
|
|
@@ -145,16 +145,16 @@ export declare const HANDLER_LEASE_MS: number;
|
|
|
145
145
|
*/
|
|
146
146
|
export declare const HANDLER_RETRY_MS = 60000;
|
|
147
147
|
/**
|
|
148
|
-
* `
|
|
148
|
+
* `Pipelines` over a `ReferenceStore` and a queue of wake-ups, by the protocol of
|
|
149
149
|
* docs/decisions/0006. The adapter delivers the queue's batches to `consume`
|
|
150
150
|
* and calls `sweep` on a schedule.
|
|
151
151
|
*/
|
|
152
|
-
export declare class ReferenceExecutor implements
|
|
152
|
+
export declare class ReferenceExecutor implements Pipelines {
|
|
153
153
|
#private;
|
|
154
154
|
private readonly o;
|
|
155
155
|
constructor(o: ReferenceExecutorOptions);
|
|
156
|
-
dispatch<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps>(definition:
|
|
157
|
-
status(id:
|
|
156
|
+
dispatch<Input extends JsonValue, Results extends Record<string, JsonValue>, Deps>(definition: PipelineDefinition<Input, Results, Deps>, input: Input, options: DispatchOptions): Promise<DispatchResult>;
|
|
157
|
+
status(id: PipelineInstanceId): Promise<PipelineStatus>;
|
|
158
158
|
/**
|
|
159
159
|
* THE QUEUE CONSUMER. Each message is acknowledged or retried on its own.
|
|
160
160
|
* A message whose handling throws is neither, so the queue redelivers it:
|
|
@@ -62,68 +62,68 @@ function backoffMs(retries, n) {
|
|
|
62
62
|
* `Infinity`, would set `next_wake_at` to a value no sweep ever reaches, and
|
|
63
63
|
* the instance would stay `running` for ever.
|
|
64
64
|
*/
|
|
65
|
-
function checkSteps(
|
|
65
|
+
function checkSteps(pipeline) {
|
|
66
66
|
const names = new Set();
|
|
67
|
-
for (const step of
|
|
68
|
-
const where = `
|
|
67
|
+
for (const step of pipeline.steps) {
|
|
68
|
+
const where = `Pipeline ${pipeline.name}, step ${JSON.stringify(step.name)}`;
|
|
69
69
|
if (names.has(step.name)) {
|
|
70
|
-
throw new Misconfigured('
|
|
70
|
+
throw new Misconfigured('pipelines', `${where}: the name is used twice`);
|
|
71
71
|
}
|
|
72
72
|
names.add(step.name);
|
|
73
73
|
const { limit, delaySeconds } = step.retries;
|
|
74
74
|
if (!Number.isInteger(limit) || limit < 0) {
|
|
75
|
-
throw new Misconfigured('
|
|
75
|
+
throw new Misconfigured('pipelines', `${where}: retries.limit must be an integer of 0 or more`);
|
|
76
76
|
}
|
|
77
77
|
if (!Number.isFinite(delaySeconds) || delaySeconds < 0) {
|
|
78
|
-
throw new Misconfigured('
|
|
78
|
+
throw new Misconfigured('pipelines', `${where}: retries.delaySeconds must be a finite number of 0 or more`);
|
|
79
79
|
}
|
|
80
80
|
if (limit > 0 && !Number.isFinite(backoffMs(step.retries, limit))) {
|
|
81
|
-
throw new Misconfigured('
|
|
81
|
+
throw new Misconfigured('pipelines', `${where}: the backoff before retry ${limit} is not a finite delay`);
|
|
82
82
|
}
|
|
83
83
|
if (!Number.isFinite(step.timeoutSeconds) || step.timeoutSeconds <= 0) {
|
|
84
|
-
throw new Misconfigured('
|
|
84
|
+
throw new Misconfigured('pipelines', `${where}: timeoutSeconds must be a finite number above 0`);
|
|
85
85
|
}
|
|
86
86
|
}
|
|
87
87
|
}
|
|
88
88
|
const bytes = (json) => new TextEncoder().encode(json).byteLength;
|
|
89
89
|
/**
|
|
90
|
-
* `
|
|
90
|
+
* `Pipelines` over a `ReferenceStore` and a queue of wake-ups, by the protocol of
|
|
91
91
|
* docs/decisions/0006. The adapter delivers the queue's batches to `consume`
|
|
92
92
|
* and calls `sweep` on a schedule.
|
|
93
93
|
*/
|
|
94
94
|
export class ReferenceExecutor {
|
|
95
95
|
o;
|
|
96
|
-
#
|
|
96
|
+
#pipelines = new Map();
|
|
97
97
|
constructor(o) {
|
|
98
98
|
this.o = o;
|
|
99
99
|
for (const registration of o.registrations) {
|
|
100
|
-
const
|
|
100
|
+
const pipeline = unpack(registration);
|
|
101
101
|
// Refused when the executor is built, not at the first dispatch: a bad
|
|
102
|
-
// name is a defect in the definition (rule 7, `
|
|
103
|
-
if (!NAME.test(
|
|
104
|
-
throw new LimitExceeded('
|
|
102
|
+
// name is a defect in the definition (rule 7, `PipelineDefinition.name`).
|
|
103
|
+
if (!NAME.test(pipeline.name)) {
|
|
104
|
+
throw new LimitExceeded('pipelines', `Pipeline name ${JSON.stringify(pipeline.name)} must be 1 to 64 characters of [A-Za-z0-9_]`);
|
|
105
105
|
}
|
|
106
|
-
if (this.#
|
|
107
|
-
throw new Misconfigured('
|
|
106
|
+
if (this.#pipelines.has(pipeline.name)) {
|
|
107
|
+
throw new Misconfigured('pipelines', `Pipeline name ${pipeline.name} is registered twice`);
|
|
108
108
|
}
|
|
109
|
-
checkSteps(
|
|
110
|
-
this.#
|
|
109
|
+
checkSteps(pipeline);
|
|
110
|
+
this.#pipelines.set(pipeline.name, pipeline);
|
|
111
111
|
}
|
|
112
112
|
}
|
|
113
113
|
async dispatch(definition, input, options) {
|
|
114
|
-
const
|
|
115
|
-
if (
|
|
116
|
-
throw new Misconfigured('
|
|
114
|
+
const pipeline = this.#pipelines.get(definition.name);
|
|
115
|
+
if (pipeline === undefined) {
|
|
116
|
+
throw new Misconfigured('pipelines', `Pipeline ${definition.name} is not registered with this executor`);
|
|
117
117
|
}
|
|
118
|
-
const key =
|
|
119
|
-
const id = `${
|
|
118
|
+
const key = pipeline.key(input);
|
|
119
|
+
const id = `${pipeline.name}-${key}`;
|
|
120
120
|
if (!KEY.test(key) || id.length > ID_MAX) {
|
|
121
|
-
throw new LimitExceeded('
|
|
121
|
+
throw new LimitExceeded('pipelines', `key ${JSON.stringify(key)} must be [A-Za-z0-9_-], at least one character, and fit an id of ${ID_MAX}`);
|
|
122
122
|
}
|
|
123
123
|
const now = this.o.clock.now();
|
|
124
124
|
const row = {
|
|
125
125
|
instanceId: id,
|
|
126
|
-
|
|
126
|
+
pipeline: pipeline.name,
|
|
127
127
|
input: JSON.stringify(input),
|
|
128
128
|
runId: options.runId,
|
|
129
129
|
unitKey: key,
|
|
@@ -183,7 +183,7 @@ export class ReferenceExecutor {
|
|
|
183
183
|
}
|
|
184
184
|
}
|
|
185
185
|
catch (error) {
|
|
186
|
-
this.o.logger.error('
|
|
186
|
+
this.o.logger.error('pipelines: wake-up failed, left for redelivery', {
|
|
187
187
|
instanceId: message.body.instanceId,
|
|
188
188
|
stepIndex: message.body.stepIndex,
|
|
189
189
|
error: String(error),
|
|
@@ -246,15 +246,15 @@ export class ReferenceExecutor {
|
|
|
246
246
|
if (row.leaseExpiresAt !== null && row.leaseExpiresAt > now) {
|
|
247
247
|
return undefined;
|
|
248
248
|
}
|
|
249
|
-
const
|
|
250
|
-
if (
|
|
251
|
-
this.o.logger.error('
|
|
249
|
+
const pipeline = this.#pipelines.get(row.pipeline);
|
|
250
|
+
if (pipeline === undefined) {
|
|
251
|
+
this.o.logger.error('pipelines: no registration for an instance', {
|
|
252
252
|
instanceId,
|
|
253
|
-
|
|
253
|
+
pipeline: row.pipeline,
|
|
254
254
|
});
|
|
255
255
|
return undefined;
|
|
256
256
|
}
|
|
257
|
-
const step =
|
|
257
|
+
const step = pipeline.steps[row.currentStep];
|
|
258
258
|
const leaseMs = row.status === 'failing' || step === undefined
|
|
259
259
|
? HANDLER_LEASE_MS
|
|
260
260
|
: (step.timeoutSeconds + 60) * 1000;
|
|
@@ -271,18 +271,18 @@ export class ReferenceExecutor {
|
|
|
271
271
|
return undefined;
|
|
272
272
|
}
|
|
273
273
|
if (leased.status === 'failing') {
|
|
274
|
-
await this.#runHandler(
|
|
274
|
+
await this.#runHandler(pipeline, leased);
|
|
275
275
|
}
|
|
276
276
|
else {
|
|
277
|
-
await this.#runStep(
|
|
277
|
+
await this.#runStep(pipeline, leased);
|
|
278
278
|
}
|
|
279
279
|
return undefined;
|
|
280
280
|
}
|
|
281
|
-
async #base(row,
|
|
281
|
+
async #base(row, pipeline) {
|
|
282
282
|
const stored = await this.o.store.results(row.instanceId);
|
|
283
283
|
const results = {};
|
|
284
284
|
for (const [index, json] of [...stored].sort(([a], [b]) => a - b)) {
|
|
285
|
-
const name =
|
|
285
|
+
const name = pipeline.steps[index]?.name;
|
|
286
286
|
if (name !== undefined && index < row.currentStep) {
|
|
287
287
|
results[name] = JSON.parse(json);
|
|
288
288
|
}
|
|
@@ -293,24 +293,29 @@ export class ReferenceExecutor {
|
|
|
293
293
|
unitKey: row.unitKey,
|
|
294
294
|
input: JSON.parse(row.input),
|
|
295
295
|
results,
|
|
296
|
+
toolkit: {
|
|
297
|
+
journal: this.o.journal,
|
|
298
|
+
clock: this.o.clock,
|
|
299
|
+
logger: this.o.logger,
|
|
300
|
+
},
|
|
296
301
|
};
|
|
297
302
|
}
|
|
298
|
-
async #runStep(
|
|
303
|
+
async #runStep(pipeline, row) {
|
|
299
304
|
const index = row.currentStep;
|
|
300
|
-
const step =
|
|
305
|
+
const step = pipeline.steps[index];
|
|
301
306
|
if (step === undefined) {
|
|
302
|
-
// A
|
|
303
|
-
await this.#advance(
|
|
307
|
+
// A Pipeline with no steps left completes. Only an empty Pipeline gets here.
|
|
308
|
+
await this.#advance(pipeline, row, undefined);
|
|
304
309
|
return;
|
|
305
310
|
}
|
|
306
311
|
// The step completed but the instance did not advance: a crash between
|
|
307
312
|
// the result write and the advance. Do not run it again.
|
|
308
313
|
const stored = (await this.o.store.results(row.instanceId)).get(index);
|
|
309
314
|
if (stored !== undefined) {
|
|
310
|
-
await this.#advance(
|
|
315
|
+
await this.#advance(pipeline, row, undefined);
|
|
311
316
|
return;
|
|
312
317
|
}
|
|
313
|
-
const base = await this.#base(row,
|
|
318
|
+
const base = await this.#base(row, pipeline);
|
|
314
319
|
const started = this.o.clock.now();
|
|
315
320
|
const attempt = await this.#attempt(step, base, started);
|
|
316
321
|
const durationMs = this.o.clock.now() - started;
|
|
@@ -321,7 +326,7 @@ export class ReferenceExecutor {
|
|
|
321
326
|
await this.o.interrupt?.('before-result-stored', window);
|
|
322
327
|
await this.o.store.storeResult(row.instanceId, index, attempt.result, this.o.clock.now());
|
|
323
328
|
await this.o.interrupt?.('after-result-stored', window);
|
|
324
|
-
await this.#advance(
|
|
329
|
+
await this.#advance(pipeline, row, record);
|
|
325
330
|
return;
|
|
326
331
|
}
|
|
327
332
|
case 'fault': {
|
|
@@ -337,7 +342,7 @@ export class ReferenceExecutor {
|
|
|
337
342
|
return;
|
|
338
343
|
}
|
|
339
344
|
await record('retry', attempt.reasonCode);
|
|
340
|
-
this.o.logger.warn('
|
|
345
|
+
this.o.logger.warn('pipelines: step faulted, retrying', {
|
|
341
346
|
instanceId: row.instanceId,
|
|
342
347
|
step: step.name,
|
|
343
348
|
attempt: row.attempts,
|
|
@@ -399,7 +404,7 @@ export class ReferenceExecutor {
|
|
|
399
404
|
if (size > this.o.manifest.stepResultMaxBytes) {
|
|
400
405
|
// Rule 7: the executor enforces the manifest. The same input gives the
|
|
401
406
|
// same result, so this is terminal, not a fault.
|
|
402
|
-
const error = new LimitExceeded('
|
|
407
|
+
const error = new LimitExceeded('pipelines', `step ${step.name} returned ${size} bytes, above stepResultMaxBytes ${this.o.manifest.stepResultMaxBytes}`);
|
|
403
408
|
this.o.logger.error(error.message, { instanceId: base.instanceId });
|
|
404
409
|
return {
|
|
405
410
|
kind: 'exhausted',
|
|
@@ -412,9 +417,9 @@ export class ReferenceExecutor {
|
|
|
412
417
|
* Write 2 of a success: advance, or complete on the last step. Then the
|
|
413
418
|
* next wake-up. `record` is set when this consumer ran the step.
|
|
414
419
|
*/
|
|
415
|
-
async #advance(
|
|
420
|
+
async #advance(pipeline, row, record) {
|
|
416
421
|
const index = row.currentStep;
|
|
417
|
-
const last = index + 1 >=
|
|
422
|
+
const last = index + 1 >= pipeline.steps.length;
|
|
418
423
|
const now = this.o.clock.now();
|
|
419
424
|
const won = await this.o.store.update(row.instanceId, row.version, last
|
|
420
425
|
? {
|
|
@@ -430,12 +435,12 @@ export class ReferenceExecutor {
|
|
|
430
435
|
nextWakeAt: now,
|
|
431
436
|
});
|
|
432
437
|
if (!won) {
|
|
433
|
-
await this.#superseded(row,
|
|
438
|
+
await this.#superseded(row, pipeline.steps[index]?.name ?? '', record);
|
|
434
439
|
return;
|
|
435
440
|
}
|
|
436
441
|
await record?.('ok');
|
|
437
442
|
if (last) {
|
|
438
|
-
this.o.logger.info('
|
|
443
|
+
this.o.logger.info('pipelines: instance completed', {
|
|
439
444
|
instanceId: row.instanceId,
|
|
440
445
|
});
|
|
441
446
|
return;
|
|
@@ -465,7 +470,7 @@ export class ReferenceExecutor {
|
|
|
465
470
|
}
|
|
466
471
|
const reasonCode = exhaustion.cause === 'terminal' ? exhaustion.reasonCode : exhaustion.cause;
|
|
467
472
|
await record('failed', reasonCode);
|
|
468
|
-
this.o.logger.error('
|
|
473
|
+
this.o.logger.error('pipelines: step failed, running the exhaustion handler', {
|
|
469
474
|
instanceId: row.instanceId,
|
|
470
475
|
step,
|
|
471
476
|
cause: exhaustion.cause,
|
|
@@ -485,21 +490,21 @@ export class ReferenceExecutor {
|
|
|
485
490
|
* `failed`. A crash before that write runs the handler again, so it runs
|
|
486
491
|
* at least once and never after `failed`.
|
|
487
492
|
*/
|
|
488
|
-
async #runHandler(
|
|
489
|
-
const step =
|
|
493
|
+
async #runHandler(pipeline, row) {
|
|
494
|
+
const step = pipeline.steps[row.currentStep]?.name ?? '';
|
|
490
495
|
const exhaustion = row.cause === 'terminal'
|
|
491
496
|
? { step, cause: 'terminal', reasonCode: row.reasonCode ?? '' }
|
|
492
497
|
: { step, cause: row.cause ?? 'retries-exhausted' };
|
|
493
|
-
if (
|
|
498
|
+
if (pipeline.onExhausted !== undefined) {
|
|
494
499
|
try {
|
|
495
|
-
await
|
|
500
|
+
await pipeline.onExhausted(await this.#base(row, pipeline), exhaustion);
|
|
496
501
|
}
|
|
497
502
|
catch (error) {
|
|
498
503
|
const won = await this.o.store.update(row.instanceId, row.version, {
|
|
499
504
|
leaseExpiresAt: null,
|
|
500
505
|
nextWakeAt: fromEpochMs(this.o.clock.now() + HANDLER_RETRY_MS),
|
|
501
506
|
});
|
|
502
|
-
this.o.logger.error('
|
|
507
|
+
this.o.logger.error('pipelines: exhaustion handler threw, running it again', {
|
|
503
508
|
instanceId: row.instanceId,
|
|
504
509
|
attempt: row.attempts,
|
|
505
510
|
error: String(error),
|
|
@@ -517,7 +522,7 @@ export class ReferenceExecutor {
|
|
|
517
522
|
leaseExpiresAt: null,
|
|
518
523
|
});
|
|
519
524
|
if (won) {
|
|
520
|
-
this.o.logger.info('
|
|
525
|
+
this.o.logger.info('pipelines: instance failed', {
|
|
521
526
|
instanceId: row.instanceId,
|
|
522
527
|
});
|
|
523
528
|
}
|
|
@@ -528,7 +533,7 @@ export class ReferenceExecutor {
|
|
|
528
533
|
*/
|
|
529
534
|
async #superseded(row, step, record) {
|
|
530
535
|
await record?.('superseded', 'superseded');
|
|
531
|
-
this.o.logger.info('
|
|
536
|
+
this.o.logger.info('pipelines: superseded by another consumer', {
|
|
532
537
|
instanceId: row.instanceId,
|
|
533
538
|
step,
|
|
534
539
|
});
|
|
@@ -554,7 +559,7 @@ export class ReferenceExecutor {
|
|
|
554
559
|
});
|
|
555
560
|
}
|
|
556
561
|
catch (error) {
|
|
557
|
-
this.o.logger.warn('
|
|
562
|
+
this.o.logger.warn('pipelines: step row not written', {
|
|
558
563
|
instanceId: row.instanceId,
|
|
559
564
|
step,
|
|
560
565
|
error: String(error),
|
|
@@ -8,7 +8,7 @@ export * from './ledger.js';
|
|
|
8
8
|
export * from './cache.js';
|
|
9
9
|
export * from './blob-store.js';
|
|
10
10
|
export * from './journal.js';
|
|
11
|
-
export * from './
|
|
11
|
+
export * from './pipelines.js';
|
|
12
12
|
export * from './logger.js';
|
|
13
13
|
export * from './session-storage.js';
|
|
14
14
|
export * from './toolkit.js';
|
package/dist/contracts/index.js
CHANGED
|
@@ -9,7 +9,7 @@ export * from './ledger.js';
|
|
|
9
9
|
export * from './cache.js';
|
|
10
10
|
export * from './blob-store.js';
|
|
11
11
|
export * from './journal.js';
|
|
12
|
-
export * from './
|
|
12
|
+
export * from './pipelines.js';
|
|
13
13
|
export * from './logger.js';
|
|
14
14
|
export * from './session-storage.js';
|
|
15
15
|
export * from './toolkit.js';
|