@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
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# TVA Library
|
|
2
2
|
|
|
3
|
-
**The platform primitives a Shopify React Router app does not come with** — caching, blob storage, queues, durable
|
|
3
|
+
**The platform primitives a Shopify React Router app does not come with** — caching, blob storage, queues, durable pipelines, an idempotency ledger, and a run journal you can actually read — behind interfaces that survive changing platform.
|
|
4
4
|
|
|
5
5
|
**Status: early. Built alongside a real engagement, not ahead of one.**
|
|
6
6
|
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
export * from './blob-store.js';
|
|
2
2
|
export * from './cache.js';
|
|
3
3
|
export * from './faults.js';
|
|
4
|
-
export {
|
|
5
|
-
export type {
|
|
4
|
+
export { createCloudflarePipelines } from './pipelines.js';
|
|
5
|
+
export type { CloudflarePipelines, CloudflarePipelinesOptions, } from './pipelines.js';
|
|
6
6
|
export type { WakeUp } from '../reference-executor.js';
|
|
7
7
|
export * from './journal.js';
|
|
8
8
|
export * from './ledger.js';
|
|
@@ -12,4 +12,4 @@ export * from './queue.js';
|
|
|
12
12
|
export * from './retention.js';
|
|
13
13
|
export * from './session-storage.js';
|
|
14
14
|
export * from './toolkit.js';
|
|
15
|
-
export * from './workflow-
|
|
15
|
+
export * from './workflow-pipelines.js';
|
|
@@ -4,7 +4,7 @@ export * from './faults.js';
|
|
|
4
4
|
// The executor's factory and its types, and not its store: the step state
|
|
5
5
|
// tables have no interface, and nothing outside the executor reads or writes
|
|
6
6
|
// them (docs/decisions/0006).
|
|
7
|
-
export {
|
|
7
|
+
export { createCloudflarePipelines } from './pipelines.js';
|
|
8
8
|
export * from './journal.js';
|
|
9
9
|
export * from './ledger.js';
|
|
10
10
|
export * from './logger.js';
|
|
@@ -13,4 +13,4 @@ export * from './queue.js';
|
|
|
13
13
|
export * from './retention.js';
|
|
14
14
|
export * from './session-storage.js';
|
|
15
15
|
export * from './toolkit.js';
|
|
16
|
-
export * from './workflow-
|
|
16
|
+
export * from './workflow-pipelines.js';
|
|
@@ -18,8 +18,9 @@ import { type CallRow, type DeliveryRow, type Instant, type Journal, type Logger
|
|
|
18
18
|
* failuresByReason journal_units_recorded_at
|
|
19
19
|
* delivery webhook_deliveries and webhook_tasks primary keys
|
|
20
20
|
* deadTasks webhook_tasks_state
|
|
21
|
-
*
|
|
21
|
+
* deadTasksByUseCase webhook_tasks_use_case_state
|
|
22
22
|
* stuckTasks webhook_tasks_state
|
|
23
|
+
* reclaimStuckTask sqlite_autoindex_webhook_tasks_1
|
|
23
24
|
*/
|
|
24
25
|
declare const Q: {
|
|
25
26
|
readonly startRun: "\n INSERT INTO journal_runs\n (run_id, job, trigger, mode, started_at, identity)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6)\n ON CONFLICT(run_id) DO UPDATE SET\n job = ?2, trigger = ?3, mode = ?4, started_at = ?5, identity = ?6\n ";
|
|
@@ -36,13 +37,14 @@ declare const Q: {
|
|
|
36
37
|
readonly failuresByReason: "\n SELECT reason_code AS reasonCode, COUNT(*) AS count\n FROM journal_units\n WHERE recorded_at >= ?1\n AND reason_code IS NOT NULL\n AND outcome != 'written'\n GROUP BY reason_code\n ORDER BY count DESC, reason_code ASC\n ";
|
|
37
38
|
readonly recentRuns: "SELECT * FROM journal_runs ORDER BY started_at DESC LIMIT ?1";
|
|
38
39
|
readonly recordDelivery: "\n INSERT INTO webhook_deliveries\n (delivery_id, source, topic, shop, webhook_id, body_key, received_at)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)\n ON CONFLICT(delivery_id) DO NOTHING\n ";
|
|
39
|
-
readonly recordTask: "\n INSERT INTO webhook_tasks (delivery_id,
|
|
40
|
-
readonly moveTask: "\n UPDATE webhook_tasks SET state = ?3, updated_at = ?4, reason_code = ?9\n WHERE delivery_id = ?1 AND
|
|
40
|
+
readonly recordTask: "\n INSERT INTO webhook_tasks (delivery_id, use_case, state, updated_at)\n VALUES (?1, ?2, 'received', ?3)\n ON CONFLICT(delivery_id, use_case) DO NOTHING\n ";
|
|
41
|
+
readonly moveTask: "\n UPDATE webhook_tasks SET state = ?3, updated_at = ?4, reason_code = ?9,\n requeues = CASE WHEN ?3 = 'replayed' THEN 0 ELSE requeues END\n WHERE delivery_id = ?1 AND use_case = ?2 AND state IN (?5, ?6, ?7, ?8)\n ";
|
|
41
42
|
readonly delivery: "SELECT * FROM webhook_deliveries WHERE delivery_id = ?1";
|
|
42
|
-
readonly tasksForDelivery: "\n SELECT * FROM webhook_tasks WHERE delivery_id = ?1 ORDER BY
|
|
43
|
-
readonly deadTasks: "\n SELECT * FROM webhook_tasks\n WHERE state = 'dead' AND (updated_at, delivery_id,
|
|
44
|
-
readonly
|
|
45
|
-
readonly stuckTasks: "\n SELECT * FROM webhook_tasks\n WHERE state IN ('received', 'processing') AND updated_at < ?1\n ORDER BY updated_at, delivery_id,
|
|
43
|
+
readonly tasksForDelivery: "\n SELECT * FROM webhook_tasks WHERE delivery_id = ?1 ORDER BY use_case\n ";
|
|
44
|
+
readonly deadTasks: "\n SELECT * FROM webhook_tasks\n WHERE state = 'dead' AND (updated_at, delivery_id, use_case) > (?1, ?2, ?3)\n ORDER BY updated_at, delivery_id, use_case LIMIT ?4\n ";
|
|
45
|
+
readonly deadTasksByUseCase: "\n SELECT * FROM webhook_tasks\n WHERE use_case = ?5 AND state = 'dead'\n AND (updated_at, delivery_id, use_case) > (?1, ?2, ?3)\n ORDER BY updated_at, delivery_id LIMIT ?4\n ";
|
|
46
|
+
readonly stuckTasks: "\n SELECT * FROM webhook_tasks\n WHERE state IN ('received', 'processing', 'replayed') AND updated_at < ?1\n ORDER BY updated_at, delivery_id, use_case LIMIT ?2\n ";
|
|
47
|
+
readonly reclaimStuckTask: "\n UPDATE webhook_tasks SET\n updated_at = ?5,\n state = CASE WHEN ?4 = 'dead' THEN 'dead' ELSE state END,\n reason_code = CASE WHEN ?4 = 'dead' THEN 'stuck' ELSE reason_code END,\n requeues = CASE WHEN ?4 = 'dead' THEN requeues ELSE requeues + 1 END\n WHERE delivery_id = ?1 AND use_case = ?2 AND updated_at = ?3\n AND state IN ('received', 'processing', 'replayed')\n ";
|
|
46
48
|
};
|
|
47
49
|
export type CloudflareJournalOptions = {
|
|
48
50
|
readonly db: D1Database;
|
|
@@ -91,17 +93,18 @@ export declare class CloudflareJournal implements Journal {
|
|
|
91
93
|
failuresByReason(since: Instant): Promise<readonly ReasonCount[]>;
|
|
92
94
|
recentRuns(limit?: number): Promise<readonly RunRow[]>;
|
|
93
95
|
/** One `D1.batch`, so the delivery and its tasks land together or not at all. */
|
|
94
|
-
recordDelivery(delivery: DeliveryRow,
|
|
95
|
-
moveTask(deliveryId: string,
|
|
96
|
+
recordDelivery(delivery: DeliveryRow, useCases: readonly string[]): Promise<void>;
|
|
97
|
+
moveTask(deliveryId: string, useCase: string, to: Exclude<TaskState, 'received'>, at: Instant, reasonCode?: string): Promise<boolean>;
|
|
96
98
|
delivery(deliveryId: string): Promise<{
|
|
97
99
|
delivery: DeliveryRow;
|
|
98
100
|
tasks: readonly TaskRow[];
|
|
99
101
|
} | undefined>;
|
|
100
|
-
deadTasks({
|
|
101
|
-
readonly
|
|
102
|
+
deadTasks({ useCase, after, limit, }?: {
|
|
103
|
+
readonly useCase?: string;
|
|
102
104
|
readonly after?: TaskCursor;
|
|
103
105
|
readonly limit?: number;
|
|
104
106
|
}): Promise<readonly TaskRow[]>;
|
|
105
107
|
stuckTasks(before: Instant, limit?: number): Promise<readonly TaskRow[]>;
|
|
108
|
+
reclaimStuckTask(task: Pick<TaskRow, 'deliveryId' | 'useCase' | 'updatedAt'>, at: Instant, to: 'requeued' | 'dead'): Promise<boolean>;
|
|
106
109
|
}
|
|
107
110
|
export { Q as JOURNAL_QUERIES };
|
|
@@ -29,8 +29,9 @@ const fromStates = (to) => {
|
|
|
29
29
|
* failuresByReason journal_units_recorded_at
|
|
30
30
|
* delivery webhook_deliveries and webhook_tasks primary keys
|
|
31
31
|
* deadTasks webhook_tasks_state
|
|
32
|
-
*
|
|
32
|
+
* deadTasksByUseCase webhook_tasks_use_case_state
|
|
33
33
|
* stuckTasks webhook_tasks_state
|
|
34
|
+
* reclaimStuckTask sqlite_autoindex_webhook_tasks_1
|
|
34
35
|
*/
|
|
35
36
|
const Q = {
|
|
36
37
|
startRun: `
|
|
@@ -106,35 +107,47 @@ const Q = {
|
|
|
106
107
|
ON CONFLICT(delivery_id) DO NOTHING
|
|
107
108
|
`,
|
|
108
109
|
recordTask: `
|
|
109
|
-
INSERT INTO webhook_tasks (delivery_id,
|
|
110
|
+
INSERT INTO webhook_tasks (delivery_id, use_case, state, updated_at)
|
|
110
111
|
VALUES (?1, ?2, 'received', ?3)
|
|
111
|
-
ON CONFLICT(delivery_id,
|
|
112
|
+
ON CONFLICT(delivery_id, use_case) DO NOTHING
|
|
112
113
|
`,
|
|
113
114
|
// ?5 to ?8 are the states TASK_TRANSITIONS allows the move from, the
|
|
114
115
|
// list padded by repeating its first, so the statement never changes.
|
|
115
116
|
moveTask: `
|
|
116
|
-
UPDATE webhook_tasks SET state = ?3, updated_at = ?4, reason_code = ?9
|
|
117
|
-
|
|
117
|
+
UPDATE webhook_tasks SET state = ?3, updated_at = ?4, reason_code = ?9,
|
|
118
|
+
requeues = CASE WHEN ?3 = 'replayed' THEN 0 ELSE requeues END
|
|
119
|
+
WHERE delivery_id = ?1 AND use_case = ?2 AND state IN (?5, ?6, ?7, ?8)
|
|
118
120
|
`,
|
|
119
121
|
delivery: `SELECT * FROM webhook_deliveries WHERE delivery_id = ?1`,
|
|
120
122
|
tasksForDelivery: `
|
|
121
|
-
SELECT * FROM webhook_tasks WHERE delivery_id = ?1 ORDER BY
|
|
123
|
+
SELECT * FROM webhook_tasks WHERE delivery_id = ?1 ORDER BY use_case
|
|
122
124
|
`,
|
|
123
125
|
deadTasks: `
|
|
124
126
|
SELECT * FROM webhook_tasks
|
|
125
|
-
WHERE state = 'dead' AND (updated_at, delivery_id,
|
|
126
|
-
ORDER BY updated_at, delivery_id,
|
|
127
|
+
WHERE state = 'dead' AND (updated_at, delivery_id, use_case) > (?1, ?2, ?3)
|
|
128
|
+
ORDER BY updated_at, delivery_id, use_case LIMIT ?4
|
|
127
129
|
`,
|
|
128
|
-
|
|
130
|
+
deadTasksByUseCase: `
|
|
129
131
|
SELECT * FROM webhook_tasks
|
|
130
|
-
WHERE
|
|
131
|
-
AND (updated_at, delivery_id,
|
|
132
|
+
WHERE use_case = ?5 AND state = 'dead'
|
|
133
|
+
AND (updated_at, delivery_id, use_case) > (?1, ?2, ?3)
|
|
132
134
|
ORDER BY updated_at, delivery_id LIMIT ?4
|
|
133
135
|
`,
|
|
134
136
|
stuckTasks: `
|
|
135
137
|
SELECT * FROM webhook_tasks
|
|
136
|
-
WHERE state IN ('received', 'processing') AND updated_at < ?1
|
|
137
|
-
ORDER BY updated_at, delivery_id,
|
|
138
|
+
WHERE state IN ('received', 'processing', 'replayed') AND updated_at < ?1
|
|
139
|
+
ORDER BY updated_at, delivery_id, use_case LIMIT ?2
|
|
140
|
+
`,
|
|
141
|
+
// The state and updated_at the sweeper read are re-checked in the write, so
|
|
142
|
+
// a task that moved since, or another sweeper's claim, makes it change no row.
|
|
143
|
+
reclaimStuckTask: `
|
|
144
|
+
UPDATE webhook_tasks SET
|
|
145
|
+
updated_at = ?5,
|
|
146
|
+
state = CASE WHEN ?4 = 'dead' THEN 'dead' ELSE state END,
|
|
147
|
+
reason_code = CASE WHEN ?4 = 'dead' THEN 'stuck' ELSE reason_code END,
|
|
148
|
+
requeues = CASE WHEN ?4 = 'dead' THEN requeues ELSE requeues + 1 END
|
|
149
|
+
WHERE delivery_id = ?1 AND use_case = ?2 AND updated_at = ?3
|
|
150
|
+
AND state IN ('received', 'processing', 'replayed')
|
|
138
151
|
`,
|
|
139
152
|
};
|
|
140
153
|
export class CloudflareJournal {
|
|
@@ -246,20 +259,20 @@ export class CloudflareJournal {
|
|
|
246
259
|
return results.map(toRunRow);
|
|
247
260
|
}
|
|
248
261
|
/** One `D1.batch`, so the delivery and its tasks land together or not at all. */
|
|
249
|
-
async recordDelivery(delivery,
|
|
262
|
+
async recordDelivery(delivery, useCases) {
|
|
250
263
|
await this.#call('recordDelivery', async () => this.o.db.batch([
|
|
251
264
|
this.o.db
|
|
252
265
|
.prepare(Q.recordDelivery)
|
|
253
266
|
.bind(delivery.deliveryId, delivery.source, delivery.topic, delivery.shop, delivery.webhookId, delivery.bodyKey, delivery.receivedAt),
|
|
254
|
-
...
|
|
267
|
+
...useCases.map((useCase) => this.o.db
|
|
255
268
|
.prepare(Q.recordTask)
|
|
256
|
-
.bind(delivery.deliveryId,
|
|
269
|
+
.bind(delivery.deliveryId, useCase, delivery.receivedAt)),
|
|
257
270
|
]));
|
|
258
271
|
}
|
|
259
|
-
async moveTask(deliveryId,
|
|
272
|
+
async moveTask(deliveryId, useCase, to, at, reasonCode) {
|
|
260
273
|
const { meta } = await this.#call('moveTask', async () => this.o.db
|
|
261
274
|
.prepare(Q.moveTask)
|
|
262
|
-
.bind(deliveryId,
|
|
275
|
+
.bind(deliveryId, useCase, to, at, ...fromStates(to), reasonCode ?? null)
|
|
263
276
|
.run());
|
|
264
277
|
return meta.changes === 1;
|
|
265
278
|
}
|
|
@@ -276,16 +289,16 @@ export class CloudflareJournal {
|
|
|
276
289
|
tasks: tasks.results.map(toTaskRow),
|
|
277
290
|
};
|
|
278
291
|
}
|
|
279
|
-
async deadTasks({
|
|
280
|
-
const cursor = [after.updatedAt, after.deliveryId, after.
|
|
281
|
-
const { results } = await this.#call('deadTasks', async () =>
|
|
292
|
+
async deadTasks({ useCase, after = FIRST_TASK, limit = DEFAULT_UNIT_LIMIT, } = {}) {
|
|
293
|
+
const cursor = [after.updatedAt, after.deliveryId, after.useCase, limit];
|
|
294
|
+
const { results } = await this.#call('deadTasks', async () => useCase === undefined
|
|
282
295
|
? this.o.db
|
|
283
296
|
.prepare(Q.deadTasks)
|
|
284
297
|
.bind(...cursor)
|
|
285
298
|
.all()
|
|
286
299
|
: this.o.db
|
|
287
|
-
.prepare(Q.
|
|
288
|
-
.bind(...cursor,
|
|
300
|
+
.prepare(Q.deadTasksByUseCase)
|
|
301
|
+
.bind(...cursor, useCase)
|
|
289
302
|
.all());
|
|
290
303
|
return results.map(toTaskRow);
|
|
291
304
|
}
|
|
@@ -293,6 +306,13 @@ export class CloudflareJournal {
|
|
|
293
306
|
const { results } = await this.#call('stuckTasks', async () => this.o.db.prepare(Q.stuckTasks).bind(before, limit).all());
|
|
294
307
|
return results.map(toTaskRow);
|
|
295
308
|
}
|
|
309
|
+
async reclaimStuckTask(task, at, to) {
|
|
310
|
+
const { meta } = await this.#call('reclaimStuckTask', async () => this.o.db
|
|
311
|
+
.prepare(Q.reclaimStuckTask)
|
|
312
|
+
.bind(task.deliveryId, task.useCase, task.updatedAt, to, at)
|
|
313
|
+
.run());
|
|
314
|
+
return meta.changes === 1;
|
|
315
|
+
}
|
|
296
316
|
async #call(operation, f) {
|
|
297
317
|
try {
|
|
298
318
|
return await f();
|
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
import type { Instant,
|
|
1
|
+
import type { Instant, PipelineInstanceId, PipelineRegistration, Pipelines, Toolkit } from '../../contracts/index.js';
|
|
2
2
|
import type { InstanceChange, InstanceRow, Interrupt, ReferenceStore, WakeUp } from '../reference-executor.js';
|
|
3
3
|
import type { QueueMessageBatch } from './bindings.js';
|
|
4
4
|
import type { Envelope } from './queue.js';
|
|
5
5
|
/** Exported so the spec can ask SQLite which index serves each read. */
|
|
6
6
|
export declare const JOB_QUERIES: {
|
|
7
|
-
readonly insert: "\n INSERT INTO
|
|
8
|
-
readonly get: "SELECT * FROM
|
|
9
|
-
readonly removeSteps: "\n DELETE FROM
|
|
10
|
-
readonly removeInstance: "\n DELETE FROM
|
|
11
|
-
readonly storeResult: "\n INSERT INTO
|
|
12
|
-
readonly results: "\n SELECT step_index, result FROM
|
|
13
|
-
readonly due: "\n SELECT * FROM
|
|
14
|
-
readonly removeEndedSteps: "\n DELETE FROM
|
|
15
|
-
readonly removeEndedInstances: "DELETE FROM
|
|
7
|
+
readonly insert: "\n INSERT INTO pipeline_instances\n (instance_id, pipeline, input, run_id, unit_key, status, cause, reason_code,\n current_step, attempts, version, lease_expires_at, next_wake_at,\n created_at, ended_at)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)\n ON CONFLICT(instance_id) DO NOTHING\n RETURNING instance_id\n ";
|
|
8
|
+
readonly get: "SELECT * FROM pipeline_instances WHERE instance_id = ?1";
|
|
9
|
+
readonly removeSteps: "\n DELETE FROM pipeline_steps WHERE instance_id = ?1 AND EXISTS (\n SELECT 1 FROM pipeline_instances WHERE instance_id = ?1 AND ended_at <= ?2\n )\n ";
|
|
10
|
+
readonly removeInstance: "\n DELETE FROM pipeline_instances WHERE instance_id = ?1 AND ended_at <= ?2\n ";
|
|
11
|
+
readonly storeResult: "\n INSERT INTO pipeline_steps (instance_id, step_index, result, completed_at)\n VALUES (?1, ?2, ?3, ?4)\n ON CONFLICT(instance_id, step_index) DO NOTHING\n ";
|
|
12
|
+
readonly results: "\n SELECT step_index, result FROM pipeline_steps WHERE instance_id = ?1\n ";
|
|
13
|
+
readonly due: "\n SELECT * FROM pipeline_instances\n WHERE status IN ('running', 'failing')\n AND next_wake_at <= ?1\n AND (lease_expires_at IS NULL OR lease_expires_at <= ?1)\n ORDER BY next_wake_at\n ";
|
|
14
|
+
readonly removeEndedSteps: "\n DELETE FROM pipeline_steps WHERE instance_id IN (\n SELECT instance_id FROM pipeline_instances WHERE ended_at <= ?1\n )\n ";
|
|
15
|
+
readonly removeEndedInstances: "DELETE FROM pipeline_instances WHERE ended_at <= ?1";
|
|
16
16
|
};
|
|
17
17
|
export type D1JobStoreOptions = {
|
|
18
18
|
readonly db: D1Database;
|
|
19
19
|
};
|
|
20
20
|
/**
|
|
21
|
-
* `
|
|
21
|
+
* `pipeline_instances` and `pipeline_steps` (decision 0006) in D1. Each method is one
|
|
22
22
|
* statement of the protocol, except the two deletes, whose order is chosen so
|
|
23
23
|
* that a crash between them is harmless. No method reads the clock: every
|
|
24
24
|
* time comes from the executor, which reads the injected `Clock`.
|
|
@@ -28,16 +28,16 @@ export declare class D1JobStore implements ReferenceStore {
|
|
|
28
28
|
private readonly o;
|
|
29
29
|
constructor(o: D1JobStoreOptions);
|
|
30
30
|
insert(row: InstanceRow): Promise<'inserted' | 'exists'>;
|
|
31
|
-
get(id:
|
|
31
|
+
get(id: PipelineInstanceId): Promise<InstanceRow | undefined>;
|
|
32
32
|
/**
|
|
33
33
|
* `UPDATE … WHERE instance_id = ? AND version = ?`. `RETURNING` says
|
|
34
34
|
* whether the row matched, so the outcome does not depend on how D1 reports
|
|
35
35
|
* a changed-row count.
|
|
36
36
|
*/
|
|
37
|
-
update(id:
|
|
38
|
-
remove(id:
|
|
39
|
-
storeResult(id:
|
|
40
|
-
results(id:
|
|
37
|
+
update(id: PipelineInstanceId, version: number, change: InstanceChange): Promise<boolean>;
|
|
38
|
+
remove(id: PipelineInstanceId, cutoff: Instant): Promise<void>;
|
|
39
|
+
storeResult(id: PipelineInstanceId, stepIndex: number, result: string, completedAt: Instant): Promise<void>;
|
|
40
|
+
results(id: PipelineInstanceId): Promise<ReadonlyMap<number, string>>;
|
|
41
41
|
due(now: Instant): Promise<readonly InstanceRow[]>;
|
|
42
42
|
removeEndedBefore(cutoff: Instant): Promise<void>;
|
|
43
43
|
}
|
|
@@ -50,11 +50,11 @@ export declare class D1JobStore implements ReferenceStore {
|
|
|
50
50
|
* The Worker wires the two entry points the platform calls:
|
|
51
51
|
*
|
|
52
52
|
* export default {
|
|
53
|
-
* async queue(batch, env) { await
|
|
54
|
-
* async scheduled(_controller, env) { await
|
|
53
|
+
* async queue(batch, env) { await pipelinesFor(env).consume(batch) },
|
|
54
|
+
* async scheduled(_controller, env) { await pipelinesFor(env).sweep() },
|
|
55
55
|
* }
|
|
56
56
|
*/
|
|
57
|
-
export type
|
|
57
|
+
export type CloudflarePipelines = Pipelines & {
|
|
58
58
|
/**
|
|
59
59
|
* THE QUEUE CONSUMER. Give it the batches of the queue that the toolkit's
|
|
60
60
|
* `queue` sends the wake-ups to, and no other messages: it reads every
|
|
@@ -75,8 +75,8 @@ export type CloudflareJobs = Jobs & {
|
|
|
75
75
|
*/
|
|
76
76
|
sweep(): Promise<void>;
|
|
77
77
|
};
|
|
78
|
-
export type
|
|
79
|
-
readonly registrations: readonly
|
|
78
|
+
export type CloudflarePipelinesOptions = {
|
|
79
|
+
readonly registrations: readonly PipelineRegistration[];
|
|
80
80
|
/**
|
|
81
81
|
* TEST SEAMS. A restarted process is a second executor over the same
|
|
82
82
|
* store, and `interrupt` parks a consumer between two writes. An app
|
|
@@ -87,11 +87,11 @@ export type CloudflareJobsOptions = {
|
|
|
87
87
|
};
|
|
88
88
|
/**
|
|
89
89
|
* Builds the executor. It throws when a registration is refused, as for a
|
|
90
|
-
*
|
|
90
|
+
* Pipeline name outside `[A-Za-z0-9_]{1,64}`.
|
|
91
91
|
*
|
|
92
92
|
* The step state lives in `env.DB`, in the tables of
|
|
93
93
|
* `migrations/0007_create_job_tables.sql`. The toolkit supplies the clock
|
|
94
94
|
* (rule 3), the logger (rule 4), the journal the Step rows go to, and the
|
|
95
95
|
* queue the wake-ups go on (decision 0006, Amendment).
|
|
96
96
|
*/
|
|
97
|
-
export declare function
|
|
97
|
+
export declare function createCloudflarePipelines(env: Pick<Env, 'DB'>, toolkit: Pick<Toolkit<WakeUp>, 'clock' | 'logger' | 'journal' | 'queue'>, options: CloudflarePipelinesOptions): CloudflarePipelines;
|
|
@@ -3,7 +3,7 @@ import { ReferenceExecutor } from '../reference-executor.js';
|
|
|
3
3
|
import { toFault } from './faults.js';
|
|
4
4
|
import { CLOUDFLARE_MANIFEST } from './manifest.js';
|
|
5
5
|
import { toQueueBatch } from './queue.js';
|
|
6
|
-
const TOOL = '
|
|
6
|
+
const TOOL = 'pipelines';
|
|
7
7
|
/**
|
|
8
8
|
* Every query the store runs, in one place, with every value bound. The one
|
|
9
9
|
* statement assembled at run time is the conditional UPDATE, and only its
|
|
@@ -13,16 +13,16 @@ const Q = {
|
|
|
13
13
|
// ON CONFLICT DO NOTHING, so a taken id is an empty RETURNING (an outcome)
|
|
14
14
|
// and not a constraint error (a fault).
|
|
15
15
|
insert: `
|
|
16
|
-
INSERT INTO
|
|
17
|
-
(instance_id,
|
|
16
|
+
INSERT INTO pipeline_instances
|
|
17
|
+
(instance_id, pipeline, input, run_id, unit_key, status, cause, reason_code,
|
|
18
18
|
current_step, attempts, version, lease_expires_at, next_wake_at,
|
|
19
19
|
created_at, ended_at)
|
|
20
20
|
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)
|
|
21
21
|
ON CONFLICT(instance_id) DO NOTHING
|
|
22
22
|
RETURNING instance_id
|
|
23
23
|
`,
|
|
24
|
-
get: `SELECT * FROM
|
|
25
|
-
//
|
|
24
|
+
get: `SELECT * FROM pipeline_instances WHERE instance_id = ?1`,
|
|
25
|
+
// pipeline_steps first, and only while the instance has ended at or before the
|
|
26
26
|
// cutoff (ReferenceStore). A crash between the two statements leaves an
|
|
27
27
|
// ended instance with no stored results, which the next removal deletes.
|
|
28
28
|
// The other order could leave results with no instance, and a new instance
|
|
@@ -30,24 +30,24 @@ const Q = {
|
|
|
30
30
|
// condition is on ended_at, not version, so a late removal cannot delete a
|
|
31
31
|
// newer instance's results: it has not ended, or ended after the cutoff.
|
|
32
32
|
removeSteps: `
|
|
33
|
-
DELETE FROM
|
|
34
|
-
SELECT 1 FROM
|
|
33
|
+
DELETE FROM pipeline_steps WHERE instance_id = ?1 AND EXISTS (
|
|
34
|
+
SELECT 1 FROM pipeline_instances WHERE instance_id = ?1 AND ended_at <= ?2
|
|
35
35
|
)
|
|
36
36
|
`,
|
|
37
37
|
removeInstance: `
|
|
38
|
-
DELETE FROM
|
|
38
|
+
DELETE FROM pipeline_instances WHERE instance_id = ?1 AND ended_at <= ?2
|
|
39
39
|
`,
|
|
40
40
|
// The first result stored for a step is the one that stays (0006).
|
|
41
41
|
storeResult: `
|
|
42
|
-
INSERT INTO
|
|
42
|
+
INSERT INTO pipeline_steps (instance_id, step_index, result, completed_at)
|
|
43
43
|
VALUES (?1, ?2, ?3, ?4)
|
|
44
44
|
ON CONFLICT(instance_id, step_index) DO NOTHING
|
|
45
45
|
`,
|
|
46
46
|
results: `
|
|
47
|
-
SELECT step_index, result FROM
|
|
47
|
+
SELECT step_index, result FROM pipeline_steps WHERE instance_id = ?1
|
|
48
48
|
`,
|
|
49
49
|
due: `
|
|
50
|
-
SELECT * FROM
|
|
50
|
+
SELECT * FROM pipeline_instances
|
|
51
51
|
WHERE status IN ('running', 'failing')
|
|
52
52
|
AND next_wake_at <= ?1
|
|
53
53
|
AND (lease_expires_at IS NULL OR lease_expires_at <= ?1)
|
|
@@ -55,15 +55,15 @@ const Q = {
|
|
|
55
55
|
`,
|
|
56
56
|
// The same order as remove, for the same reason.
|
|
57
57
|
removeEndedSteps: `
|
|
58
|
-
DELETE FROM
|
|
59
|
-
SELECT instance_id FROM
|
|
58
|
+
DELETE FROM pipeline_steps WHERE instance_id IN (
|
|
59
|
+
SELECT instance_id FROM pipeline_instances WHERE ended_at <= ?1
|
|
60
60
|
)
|
|
61
61
|
`,
|
|
62
|
-
removeEndedInstances: `DELETE FROM
|
|
62
|
+
removeEndedInstances: `DELETE FROM pipeline_instances WHERE ended_at <= ?1`,
|
|
63
63
|
};
|
|
64
64
|
/** Exported so the spec can ask SQLite which index serves each read. */
|
|
65
65
|
export const JOB_QUERIES = Q;
|
|
66
|
-
/** `InstanceChange` field to `
|
|
66
|
+
/** `InstanceChange` field to `pipeline_instances` column. */
|
|
67
67
|
const COLUMNS = {
|
|
68
68
|
status: 'status',
|
|
69
69
|
cause: 'cause',
|
|
@@ -77,7 +77,7 @@ const COLUMNS = {
|
|
|
77
77
|
const instantOrNull = (ms) => ms === null ? null : fromEpochMs(ms);
|
|
78
78
|
const fromRow = (r) => ({
|
|
79
79
|
instanceId: r.instance_id,
|
|
80
|
-
|
|
80
|
+
pipeline: r.pipeline,
|
|
81
81
|
input: r.input,
|
|
82
82
|
runId: r.run_id,
|
|
83
83
|
unitKey: r.unit_key,
|
|
@@ -93,7 +93,7 @@ const fromRow = (r) => ({
|
|
|
93
93
|
endedAt: instantOrNull(r.ended_at),
|
|
94
94
|
});
|
|
95
95
|
/**
|
|
96
|
-
* `
|
|
96
|
+
* `pipeline_instances` and `pipeline_steps` (decision 0006) in D1. Each method is one
|
|
97
97
|
* statement of the protocol, except the two deletes, whose order is chosen so
|
|
98
98
|
* that a crash between them is harmless. No method reads the clock: every
|
|
99
99
|
* time comes from the executor, which reads the injected `Clock`.
|
|
@@ -106,7 +106,7 @@ export class D1JobStore {
|
|
|
106
106
|
async insert(row) {
|
|
107
107
|
const inserted = await this.#call('insert', async () => this.o.db
|
|
108
108
|
.prepare(Q.insert)
|
|
109
|
-
.bind(row.instanceId, row.
|
|
109
|
+
.bind(row.instanceId, row.pipeline, row.input, row.runId, row.unitKey, row.status, row.cause, row.reasonCode, row.currentStep, row.attempts, row.version, row.leaseExpiresAt, row.nextWakeAt, row.createdAt, row.endedAt)
|
|
110
110
|
.first());
|
|
111
111
|
return inserted === null ? 'exists' : 'inserted';
|
|
112
112
|
}
|
|
@@ -123,7 +123,7 @@ export class D1JobStore {
|
|
|
123
123
|
const fields = Object.keys(change).filter((field) => change[field] !== undefined);
|
|
124
124
|
const sets = fields.map((field, i) => `${COLUMNS[field]} = ?${i + 3}`);
|
|
125
125
|
const sql = `
|
|
126
|
-
UPDATE
|
|
126
|
+
UPDATE pipeline_instances SET ${['version = version + 1', ...sets].join(', ')}
|
|
127
127
|
WHERE instance_id = ?1 AND version = ?2
|
|
128
128
|
RETURNING version
|
|
129
129
|
`;
|
|
@@ -169,14 +169,14 @@ export class D1JobStore {
|
|
|
169
169
|
}
|
|
170
170
|
/**
|
|
171
171
|
* Builds the executor. It throws when a registration is refused, as for a
|
|
172
|
-
*
|
|
172
|
+
* Pipeline name outside `[A-Za-z0-9_]{1,64}`.
|
|
173
173
|
*
|
|
174
174
|
* The step state lives in `env.DB`, in the tables of
|
|
175
175
|
* `migrations/0007_create_job_tables.sql`. The toolkit supplies the clock
|
|
176
176
|
* (rule 3), the logger (rule 4), the journal the Step rows go to, and the
|
|
177
177
|
* queue the wake-ups go on (decision 0006, Amendment).
|
|
178
178
|
*/
|
|
179
|
-
export function
|
|
179
|
+
export function createCloudflarePipelines(env, toolkit, options) {
|
|
180
180
|
const executor = new ReferenceExecutor({
|
|
181
181
|
registrations: options.registrations,
|
|
182
182
|
store: options.store ?? new D1JobStore({ db: env.DB }),
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { WorkflowEntrypoint } from 'cloudflare:workers';
|
|
2
|
+
import type { PipelineRegistration, Pipelines, JsonValue, RunId, StepToolkit } from '../../contracts/index.js';
|
|
3
|
+
/**
|
|
4
|
+
* DURABLE PIPELINES ON CLOUDFLARE WORKFLOWS.
|
|
5
|
+
*
|
|
6
|
+
* Two halves, over one Workflow binding:
|
|
7
|
+
*
|
|
8
|
+
* - `workflowPipelinesEntrypoint` returns ONE GENERIC `WorkflowEntrypoint` class
|
|
9
|
+
* that runs every registered Pipeline. It finds the Pipeline from the instance id's
|
|
10
|
+
* prefix: a Pipeline name has no `-`, so the id's first `-` ends the name
|
|
11
|
+
* (`PipelineInstanceId`). Export it from the Worker's main module and bind it as
|
|
12
|
+
* a Workflow.
|
|
13
|
+
* - `createWorkflowPipelines` is the `Pipelines` a route calls. It creates and reads
|
|
14
|
+
* instances through that binding.
|
|
15
|
+
*
|
|
16
|
+
* One binding serves every Pipeline. Workflows scopes ids to a binding and
|
|
17
|
+
* `status(id)` takes no Pipeline name, so a binding per Pipeline would make `status`
|
|
18
|
+
* guess which binding to ask.
|
|
19
|
+
*
|
|
20
|
+
* THE CLASS HOLDS NO PIPELINE LOGIC. Every step is one `step.do` with the step's
|
|
21
|
+
* own retries and timeout, and the exhaustion handler is one more. Deployed
|
|
22
|
+
* Workflows replays `run()` after a suspension and local Workflows does not
|
|
23
|
+
* (docs/spikes/cloudflare-workflows.md, "Three more findings"), so the code
|
|
24
|
+
* between the `step.do` calls only reads the event and what earlier
|
|
25
|
+
* `step.do` calls returned. A test that passes locally does not prove this.
|
|
26
|
+
*/
|
|
27
|
+
/** What an instance is created with. The id carries the Pipeline name and key. */
|
|
28
|
+
export type WorkflowPipelinesParams = {
|
|
29
|
+
readonly input: JsonValue;
|
|
30
|
+
readonly runId: RunId;
|
|
31
|
+
};
|
|
32
|
+
/** The Workflow binding the executor creates and reads instances through. */
|
|
33
|
+
export type PipelinesWorkflow = Workflow<WorkflowPipelinesParams>;
|
|
34
|
+
export type WorkflowPipelinesEntrypointOptions<Env> = {
|
|
35
|
+
/**
|
|
36
|
+
* The journal, clock and logger every step receives as `toolkit`. Called
|
|
37
|
+
* with the Worker's `env` in each invocation, as `registrations` is. The
|
|
38
|
+
* reference executor passes its own; a Workflow has none until it builds one.
|
|
39
|
+
*/
|
|
40
|
+
readonly toolkit: (env: Env) => StepToolkit;
|
|
41
|
+
/** Defaults to `CLOUDFLARE_MANIFEST.stepResultMaxBytes`, 1 MiB. */
|
|
42
|
+
readonly stepResultMaxBytes?: number;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* The generic Workflow class. `registrations` is called with the Worker's
|
|
46
|
+
* `env` in each invocation, so a deps builder can close over the bindings:
|
|
47
|
+
*
|
|
48
|
+
* export const PipelinesWorkflow = workflowPipelinesEntrypoint(
|
|
49
|
+
* (env: Env) => [
|
|
50
|
+
* (register) => register(selfSignUp, () => createSignUpDeps(env)),
|
|
51
|
+
* ],
|
|
52
|
+
* { toolkit: (env: Env) => toolkitFor(env) },
|
|
53
|
+
* )
|
|
54
|
+
*
|
|
55
|
+
* It must return the same registrations `createWorkflowPipelines` was given.
|
|
56
|
+
*/
|
|
57
|
+
export declare function workflowPipelinesEntrypoint<Env>(registrations: (env: Env) => readonly PipelineRegistration[], options: WorkflowPipelinesEntrypointOptions<Env>): new (ctx: ExecutionContext, env: Env) => WorkflowEntrypoint<Env, WorkflowPipelinesParams>;
|
|
58
|
+
export type WorkflowPipelinesOptions = {
|
|
59
|
+
readonly workflow: PipelinesWorkflow;
|
|
60
|
+
readonly registrations: readonly PipelineRegistration[];
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* `Pipelines` over the Workflow binding that `workflowPipelinesEntrypoint`'s class is
|
|
64
|
+
* bound to. Throws when it is built if a registration's name breaks the rule.
|
|
65
|
+
*/
|
|
66
|
+
export declare function createWorkflowPipelines(options: WorkflowPipelinesOptions): Pipelines;
|