@anatta.io/tva 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -2
- package/dist/adapters/cloudflare/bindings.d.ts +10 -0
- package/dist/adapters/cloudflare/bindings.js +1 -0
- package/dist/adapters/cloudflare/blob-store.d.ts +39 -0
- package/dist/adapters/cloudflare/blob-store.js +95 -0
- package/dist/adapters/cloudflare/cache.d.ts +14 -0
- package/dist/adapters/cloudflare/cache.js +48 -0
- package/dist/adapters/cloudflare/faults.d.ts +7 -0
- package/dist/adapters/cloudflare/faults.js +39 -0
- package/dist/adapters/cloudflare/index.d.ts +15 -0
- package/dist/adapters/cloudflare/index.js +16 -0
- package/dist/adapters/cloudflare/journal.d.ts +110 -0
- package/dist/adapters/cloudflare/journal.js +325 -0
- package/dist/adapters/cloudflare/ledger.d.ts +14 -0
- package/dist/adapters/cloudflare/ledger.js +108 -0
- package/dist/adapters/cloudflare/logger.d.ts +22 -0
- package/dist/adapters/cloudflare/logger.js +49 -0
- package/dist/adapters/cloudflare/manifest.d.ts +81 -0
- package/dist/adapters/cloudflare/manifest.js +81 -0
- package/dist/adapters/cloudflare/pipelines.d.ts +97 -0
- package/dist/adapters/cloudflare/pipelines.js +218 -0
- package/dist/adapters/cloudflare/queue.d.ts +80 -0
- package/dist/adapters/cloudflare/queue.js +177 -0
- package/dist/adapters/cloudflare/retention.d.ts +24 -0
- package/dist/adapters/cloudflare/retention.js +103 -0
- package/dist/adapters/cloudflare/session-storage.d.ts +27 -0
- package/dist/adapters/cloudflare/session-storage.js +78 -0
- package/dist/adapters/cloudflare/toolkit.d.ts +16 -0
- package/dist/adapters/cloudflare/toolkit.js +57 -0
- package/dist/adapters/cloudflare/workflow-pipelines.d.ts +66 -0
- package/dist/adapters/cloudflare/workflow-pipelines.js +323 -0
- package/dist/adapters/journal-records.d.ts +80 -0
- package/dist/adapters/journal-records.js +75 -0
- package/dist/adapters/memory/blob-store.d.ts +9 -0
- package/dist/adapters/memory/blob-store.js +19 -0
- package/dist/adapters/memory/cache.d.ts +13 -0
- package/dist/adapters/memory/cache.js +36 -0
- package/dist/adapters/memory/clock.d.ts +1 -0
- package/dist/adapters/memory/clock.js +4 -0
- package/dist/adapters/memory/index.d.ts +11 -0
- package/dist/adapters/memory/index.js +11 -0
- package/dist/adapters/memory/journal.d.ts +35 -0
- package/dist/adapters/memory/journal.js +154 -0
- package/dist/adapters/memory/ledger.d.ts +9 -0
- package/dist/adapters/memory/ledger.js +33 -0
- package/dist/adapters/memory/logger.d.ts +16 -0
- package/dist/adapters/memory/logger.js +21 -0
- package/dist/adapters/memory/manifest.d.ts +59 -0
- package/dist/adapters/memory/manifest.js +59 -0
- package/dist/adapters/memory/pipelines.d.ts +62 -0
- package/dist/adapters/memory/pipelines.js +219 -0
- package/dist/adapters/memory/queue.d.ts +20 -0
- package/dist/adapters/memory/queue.js +102 -0
- package/dist/adapters/memory/session-storage.d.ts +20 -0
- package/dist/adapters/memory/session-storage.js +33 -0
- package/dist/adapters/memory/toolkit.d.ts +8 -0
- package/dist/adapters/memory/toolkit.js +31 -0
- package/dist/adapters/postgres/cache.d.ts +17 -0
- package/dist/adapters/postgres/cache.js +69 -0
- package/dist/adapters/postgres/config.d.ts +27 -0
- package/dist/adapters/postgres/config.js +45 -0
- package/dist/adapters/postgres/faults.d.ts +14 -0
- package/dist/adapters/postgres/faults.js +47 -0
- package/dist/adapters/postgres/index.d.ts +12 -0
- package/dist/adapters/postgres/index.js +12 -0
- package/dist/adapters/postgres/journal.d.ts +86 -0
- package/dist/adapters/postgres/journal.js +337 -0
- package/dist/adapters/postgres/ledger.d.ts +16 -0
- package/dist/adapters/postgres/ledger.js +97 -0
- package/dist/adapters/postgres/logger.d.ts +19 -0
- package/dist/adapters/postgres/logger.js +37 -0
- package/dist/adapters/postgres/manifest.d.ts +52 -0
- package/dist/adapters/postgres/manifest.js +53 -0
- package/dist/adapters/postgres/migrate.d.ts +20 -0
- package/dist/adapters/postgres/migrate.js +96 -0
- package/dist/adapters/postgres/queue.d.ts +64 -0
- package/dist/adapters/postgres/queue.js +333 -0
- package/dist/adapters/postgres/retention.d.ts +18 -0
- package/dist/adapters/postgres/retention.js +104 -0
- package/dist/adapters/postgres/session-storage.d.ts +20 -0
- package/dist/adapters/postgres/session-storage.js +71 -0
- package/dist/adapters/postgres/toolkit.d.ts +25 -0
- package/dist/adapters/postgres/toolkit.js +58 -0
- package/dist/adapters/postgres/with-client.d.ts +11 -0
- package/dist/adapters/postgres/with-client.js +29 -0
- package/dist/adapters/reference-executor.d.ts +171 -0
- package/dist/adapters/reference-executor.js +569 -0
- package/dist/adapters/retention.d.ts +18 -0
- package/dist/adapters/retention.js +13 -0
- package/dist/adapters/s3/blob-store.d.ts +35 -0
- package/dist/adapters/s3/blob-store.js +92 -0
- package/dist/adapters/s3/faults.d.ts +8 -0
- package/dist/adapters/s3/faults.js +34 -0
- package/dist/adapters/s3/index.d.ts +2 -0
- package/dist/adapters/s3/index.js +2 -0
- package/dist/adapters/session-envelope.d.ts +21 -0
- package/dist/adapters/session-envelope.js +122 -0
- package/dist/adapters/system-clock.d.ts +8 -0
- package/dist/adapters/system-clock.js +8 -0
- package/dist/contracts/blob-store.d.ts +11 -0
- package/dist/contracts/blob-store.js +1 -0
- package/dist/contracts/cache.d.ts +27 -0
- package/dist/contracts/cache.js +1 -0
- package/dist/contracts/duration.d.ts +23 -0
- package/dist/contracts/duration.js +27 -0
- package/dist/contracts/faults.d.ts +28 -0
- package/dist/contracts/faults.js +29 -0
- package/dist/contracts/identity.d.ts +12 -0
- package/dist/contracts/identity.js +1 -0
- package/dist/contracts/index.d.ts +14 -0
- package/dist/contracts/index.js +15 -0
- package/dist/contracts/instant.d.ts +17 -0
- package/dist/contracts/instant.js +12 -0
- package/dist/contracts/journal.d.ts +196 -0
- package/dist/contracts/journal.js +10 -0
- package/dist/contracts/ledger.d.ts +34 -0
- package/dist/contracts/ledger.js +1 -0
- package/dist/contracts/logger.d.ts +11 -0
- package/dist/contracts/logger.js +1 -0
- package/dist/contracts/manifest.d.ts +37 -0
- package/dist/contracts/manifest.js +30 -0
- package/dist/contracts/pipelines.d.ts +348 -0
- package/dist/contracts/pipelines.js +1 -0
- package/dist/contracts/queue.d.ts +55 -0
- package/dist/contracts/queue.js +1 -0
- package/dist/contracts/session-storage.d.ts +18 -0
- package/dist/contracts/session-storage.js +1 -0
- package/dist/contracts/toolkit.d.ts +21 -0
- package/dist/contracts/toolkit.js +1 -0
- 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/schedule/schedule.d.ts +40 -0
- package/dist/schedule/schedule.js +135 -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/use-cases/run-use-case.js +117 -0
- package/dist/use-cases/use-case-consumer.d.ts +44 -0
- 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 +63 -0
- package/dist/webhooks/create-webhook-handler.js +253 -0
- package/dist/webhooks/dead-letter-consumer.d.ts +14 -0
- package/dist/webhooks/dead-letter-consumer.js +42 -0
- package/dist/webhooks/define-registry.d.ts +42 -0
- package/dist/webhooks/define-registry.js +56 -0
- package/dist/webhooks/once.d.ts +15 -0
- package/dist/webhooks/once.js +29 -0
- package/dist/webhooks/redact-customer-bodies.d.ts +29 -0
- package/dist/webhooks/redact-customer-bodies.js +45 -0
- package/dist/webhooks/replay-webhooks.d.ts +39 -0
- package/dist/webhooks/replay-webhooks.js +82 -0
- package/dist/webhooks/sign-shopify-webhook.d.ts +14 -0
- package/dist/webhooks/sign-shopify-webhook.js +31 -0
- 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 +52 -0
- package/dist/webhooks/webhook-consumer.js +132 -0
- package/migrations/0001_create_ledger_claims.sql +23 -0
- package/migrations/0002_create_journal.sql +76 -0
- package/migrations/0003_create_shopify_sessions.sql +30 -0
- package/migrations/0004_create_journal_steps.sql +34 -0
- package/migrations/0007_create_job_tables.sql +71 -0
- package/migrations/0008_add_ledger_completed_at.sql +7 -0
- package/migrations/0009_create_webhook_receipts.sql +34 -0
- package/migrations/0010_index_webhook_deliveries_received_at.sql +2 -0
- package/migrations/0011_add_webhook_task_reason_code.sql +4 -0
- 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/0001_create_ledger_claims.sql +13 -0
- package/migrations/postgres/0002_create_journal.sql +48 -0
- package/migrations/postgres/0003_create_shopify_sessions.sql +12 -0
- package/migrations/postgres/0004_create_journal_steps.sql +19 -0
- package/migrations/postgres/0005_create_cache_entries.sql +14 -0
- package/migrations/postgres/0006_create_queue.sql +42 -0
- package/migrations/postgres/0007_create_job_tables.sql +40 -0
- package/migrations/postgres/0008_add_ledger_completed_at.sql +3 -0
- package/migrations/postgres/0009_create_webhook_receipts.sql +23 -0
- package/migrations/postgres/0010_index_webhook_deliveries_received_at.sql +2 -0
- package/migrations/postgres/0011_add_webhook_task_reason_code.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 +144 -4
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import type { Instant, PipelineInstanceId, PipelineRegistration, Pipelines, Toolkit } from '../../contracts/index.js';
|
|
2
|
+
import type { InstanceChange, InstanceRow, Interrupt, ReferenceStore, WakeUp } from '../reference-executor.js';
|
|
3
|
+
import type { QueueMessageBatch } from './bindings.js';
|
|
4
|
+
import type { Envelope } from './queue.js';
|
|
5
|
+
/** Exported so the spec can ask SQLite which index serves each read. */
|
|
6
|
+
export declare const JOB_QUERIES: {
|
|
7
|
+
readonly insert: "\n INSERT INTO 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
|
+
};
|
|
17
|
+
export type D1JobStoreOptions = {
|
|
18
|
+
readonly db: D1Database;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* `pipeline_instances` and `pipeline_steps` (decision 0006) in D1. Each method is one
|
|
22
|
+
* statement of the protocol, except the two deletes, whose order is chosen so
|
|
23
|
+
* that a crash between them is harmless. No method reads the clock: every
|
|
24
|
+
* time comes from the executor, which reads the injected `Clock`.
|
|
25
|
+
*/
|
|
26
|
+
export declare class D1JobStore implements ReferenceStore {
|
|
27
|
+
#private;
|
|
28
|
+
private readonly o;
|
|
29
|
+
constructor(o: D1JobStoreOptions);
|
|
30
|
+
insert(row: InstanceRow): Promise<'inserted' | 'exists'>;
|
|
31
|
+
get(id: PipelineInstanceId): Promise<InstanceRow | undefined>;
|
|
32
|
+
/**
|
|
33
|
+
* `UPDATE … WHERE instance_id = ? AND version = ?`. `RETURNING` says
|
|
34
|
+
* whether the row matched, so the outcome does not depend on how D1 reports
|
|
35
|
+
* a changed-row count.
|
|
36
|
+
*/
|
|
37
|
+
update(id: 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
|
+
due(now: Instant): Promise<readonly InstanceRow[]>;
|
|
42
|
+
removeEndedBefore(cutoff: Instant): Promise<void>;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* THE REFERENCE EXECUTOR ON CLOUDFLARE: D1 for the step state, Queues for the
|
|
46
|
+
* wake-ups, and a Cron Trigger for the sweeper. The algorithm is the one in
|
|
47
|
+
* `reference-executor.ts`, shared with the memory adapter. Only the storage
|
|
48
|
+
* and the delivery are this adapter's.
|
|
49
|
+
*
|
|
50
|
+
* The Worker wires the two entry points the platform calls:
|
|
51
|
+
*
|
|
52
|
+
* export default {
|
|
53
|
+
* async queue(batch, env) { await pipelinesFor(env).consume(batch) },
|
|
54
|
+
* async scheduled(_controller, env) { await pipelinesFor(env).sweep() },
|
|
55
|
+
* }
|
|
56
|
+
*/
|
|
57
|
+
export type CloudflarePipelines = Pipelines & {
|
|
58
|
+
/**
|
|
59
|
+
* THE QUEUE CONSUMER. Give it the batches of the queue that the toolkit's
|
|
60
|
+
* `queue` sends the wake-ups to, and no other messages: it reads every
|
|
61
|
+
* body as a wake-up.
|
|
62
|
+
*
|
|
63
|
+
* Each message is acknowledged or retried on its own. A message the
|
|
64
|
+
* executor left for redelivery, because a D1 call failed, is retried here
|
|
65
|
+
* explicitly, so it comes back whatever the platform does with a message
|
|
66
|
+
* that is neither.
|
|
67
|
+
*/
|
|
68
|
+
consume(batch: QueueMessageBatch<Envelope<WakeUp>>): Promise<void>;
|
|
69
|
+
/**
|
|
70
|
+
* THE SWEEPER. Call it from the Worker's `scheduled` handler, on a Cron
|
|
71
|
+
* Trigger. It sends a wake-up for every running or failing instance whose
|
|
72
|
+
* `next_wake_at` has passed and whose lease has expired, which covers a
|
|
73
|
+
* lost wake-up and a backoff longer than `queueDelayMaxSeconds`, and it
|
|
74
|
+
* deletes ended instances whose retention has passed (decision 0006).
|
|
75
|
+
*/
|
|
76
|
+
sweep(): Promise<void>;
|
|
77
|
+
};
|
|
78
|
+
export type CloudflarePipelinesOptions = {
|
|
79
|
+
readonly registrations: readonly PipelineRegistration[];
|
|
80
|
+
/**
|
|
81
|
+
* TEST SEAMS. A restarted process is a second executor over the same
|
|
82
|
+
* store, and `interrupt` parks a consumer between two writes. An app
|
|
83
|
+
* passes neither.
|
|
84
|
+
*/
|
|
85
|
+
readonly store?: ReferenceStore;
|
|
86
|
+
readonly interrupt?: Interrupt;
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* Builds the executor. It throws when a registration is refused, as for a
|
|
90
|
+
* Pipeline name outside `[A-Za-z0-9_]{1,64}`.
|
|
91
|
+
*
|
|
92
|
+
* The step state lives in `env.DB`, in the tables of
|
|
93
|
+
* `migrations/0007_create_job_tables.sql`. The toolkit supplies the clock
|
|
94
|
+
* (rule 3), the logger (rule 4), the journal the Step rows go to, and the
|
|
95
|
+
* queue the wake-ups go on (decision 0006, Amendment).
|
|
96
|
+
*/
|
|
97
|
+
export declare function createCloudflarePipelines(env: Pick<Env, 'DB'>, toolkit: Pick<Toolkit<WakeUp>, 'clock' | 'logger' | 'journal' | 'queue'>, options: CloudflarePipelinesOptions): CloudflarePipelines;
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { fromEpochMs } from '../../contracts/index.js';
|
|
2
|
+
import { ReferenceExecutor } from '../reference-executor.js';
|
|
3
|
+
import { toFault } from './faults.js';
|
|
4
|
+
import { CLOUDFLARE_MANIFEST } from './manifest.js';
|
|
5
|
+
import { toQueueBatch } from './queue.js';
|
|
6
|
+
const TOOL = 'pipelines';
|
|
7
|
+
/**
|
|
8
|
+
* Every query the store runs, in one place, with every value bound. The one
|
|
9
|
+
* statement assembled at run time is the conditional UPDATE, and only its
|
|
10
|
+
* column list is: the names come from `COLUMNS`, never from a caller.
|
|
11
|
+
*/
|
|
12
|
+
const Q = {
|
|
13
|
+
// ON CONFLICT DO NOTHING, so a taken id is an empty RETURNING (an outcome)
|
|
14
|
+
// and not a constraint error (a fault).
|
|
15
|
+
insert: `
|
|
16
|
+
INSERT INTO pipeline_instances
|
|
17
|
+
(instance_id, pipeline, input, run_id, unit_key, status, cause, reason_code,
|
|
18
|
+
current_step, attempts, version, lease_expires_at, next_wake_at,
|
|
19
|
+
created_at, ended_at)
|
|
20
|
+
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)
|
|
21
|
+
ON CONFLICT(instance_id) DO NOTHING
|
|
22
|
+
RETURNING instance_id
|
|
23
|
+
`,
|
|
24
|
+
get: `SELECT * FROM pipeline_instances WHERE instance_id = ?1`,
|
|
25
|
+
// pipeline_steps first, and only while the instance has ended at or before the
|
|
26
|
+
// cutoff (ReferenceStore). A crash between the two statements leaves an
|
|
27
|
+
// ended instance with no stored results, which the next removal deletes.
|
|
28
|
+
// The other order could leave results with no instance, and a new instance
|
|
29
|
+
// with the same id would then read the old one's results as its own. The
|
|
30
|
+
// condition is on ended_at, not version, so a late removal cannot delete a
|
|
31
|
+
// newer instance's results: it has not ended, or ended after the cutoff.
|
|
32
|
+
removeSteps: `
|
|
33
|
+
DELETE FROM pipeline_steps WHERE instance_id = ?1 AND EXISTS (
|
|
34
|
+
SELECT 1 FROM pipeline_instances WHERE instance_id = ?1 AND ended_at <= ?2
|
|
35
|
+
)
|
|
36
|
+
`,
|
|
37
|
+
removeInstance: `
|
|
38
|
+
DELETE FROM pipeline_instances WHERE instance_id = ?1 AND ended_at <= ?2
|
|
39
|
+
`,
|
|
40
|
+
// The first result stored for a step is the one that stays (0006).
|
|
41
|
+
storeResult: `
|
|
42
|
+
INSERT INTO pipeline_steps (instance_id, step_index, result, completed_at)
|
|
43
|
+
VALUES (?1, ?2, ?3, ?4)
|
|
44
|
+
ON CONFLICT(instance_id, step_index) DO NOTHING
|
|
45
|
+
`,
|
|
46
|
+
results: `
|
|
47
|
+
SELECT step_index, result FROM pipeline_steps WHERE instance_id = ?1
|
|
48
|
+
`,
|
|
49
|
+
due: `
|
|
50
|
+
SELECT * FROM pipeline_instances
|
|
51
|
+
WHERE status IN ('running', 'failing')
|
|
52
|
+
AND next_wake_at <= ?1
|
|
53
|
+
AND (lease_expires_at IS NULL OR lease_expires_at <= ?1)
|
|
54
|
+
ORDER BY next_wake_at
|
|
55
|
+
`,
|
|
56
|
+
// The same order as remove, for the same reason.
|
|
57
|
+
removeEndedSteps: `
|
|
58
|
+
DELETE FROM pipeline_steps WHERE instance_id IN (
|
|
59
|
+
SELECT instance_id FROM pipeline_instances WHERE ended_at <= ?1
|
|
60
|
+
)
|
|
61
|
+
`,
|
|
62
|
+
removeEndedInstances: `DELETE FROM pipeline_instances WHERE ended_at <= ?1`,
|
|
63
|
+
};
|
|
64
|
+
/** Exported so the spec can ask SQLite which index serves each read. */
|
|
65
|
+
export const JOB_QUERIES = Q;
|
|
66
|
+
/** `InstanceChange` field to `pipeline_instances` column. */
|
|
67
|
+
const COLUMNS = {
|
|
68
|
+
status: 'status',
|
|
69
|
+
cause: 'cause',
|
|
70
|
+
reasonCode: 'reason_code',
|
|
71
|
+
currentStep: 'current_step',
|
|
72
|
+
attempts: 'attempts',
|
|
73
|
+
leaseExpiresAt: 'lease_expires_at',
|
|
74
|
+
nextWakeAt: 'next_wake_at',
|
|
75
|
+
endedAt: 'ended_at',
|
|
76
|
+
};
|
|
77
|
+
const instantOrNull = (ms) => ms === null ? null : fromEpochMs(ms);
|
|
78
|
+
const fromRow = (r) => ({
|
|
79
|
+
instanceId: r.instance_id,
|
|
80
|
+
pipeline: r.pipeline,
|
|
81
|
+
input: r.input,
|
|
82
|
+
runId: r.run_id,
|
|
83
|
+
unitKey: r.unit_key,
|
|
84
|
+
status: r.status,
|
|
85
|
+
cause: r.cause,
|
|
86
|
+
reasonCode: r.reason_code,
|
|
87
|
+
currentStep: r.current_step,
|
|
88
|
+
attempts: r.attempts,
|
|
89
|
+
version: r.version,
|
|
90
|
+
leaseExpiresAt: instantOrNull(r.lease_expires_at),
|
|
91
|
+
nextWakeAt: instantOrNull(r.next_wake_at),
|
|
92
|
+
createdAt: fromEpochMs(r.created_at),
|
|
93
|
+
endedAt: instantOrNull(r.ended_at),
|
|
94
|
+
});
|
|
95
|
+
/**
|
|
96
|
+
* `pipeline_instances` and `pipeline_steps` (decision 0006) in D1. Each method is one
|
|
97
|
+
* statement of the protocol, except the two deletes, whose order is chosen so
|
|
98
|
+
* that a crash between them is harmless. No method reads the clock: every
|
|
99
|
+
* time comes from the executor, which reads the injected `Clock`.
|
|
100
|
+
*/
|
|
101
|
+
export class D1JobStore {
|
|
102
|
+
o;
|
|
103
|
+
constructor(o) {
|
|
104
|
+
this.o = o;
|
|
105
|
+
}
|
|
106
|
+
async insert(row) {
|
|
107
|
+
const inserted = await this.#call('insert', async () => this.o.db
|
|
108
|
+
.prepare(Q.insert)
|
|
109
|
+
.bind(row.instanceId, row.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
|
+
.first());
|
|
111
|
+
return inserted === null ? 'exists' : 'inserted';
|
|
112
|
+
}
|
|
113
|
+
async get(id) {
|
|
114
|
+
const row = await this.#call('get', async () => this.o.db.prepare(Q.get).bind(id).first());
|
|
115
|
+
return row === null ? undefined : fromRow(row);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* `UPDATE … WHERE instance_id = ? AND version = ?`. `RETURNING` says
|
|
119
|
+
* whether the row matched, so the outcome does not depend on how D1 reports
|
|
120
|
+
* a changed-row count.
|
|
121
|
+
*/
|
|
122
|
+
async update(id, version, change) {
|
|
123
|
+
const fields = Object.keys(change).filter((field) => change[field] !== undefined);
|
|
124
|
+
const sets = fields.map((field, i) => `${COLUMNS[field]} = ?${i + 3}`);
|
|
125
|
+
const sql = `
|
|
126
|
+
UPDATE pipeline_instances SET ${['version = version + 1', ...sets].join(', ')}
|
|
127
|
+
WHERE instance_id = ?1 AND version = ?2
|
|
128
|
+
RETURNING version
|
|
129
|
+
`;
|
|
130
|
+
const won = await this.#call('update', async () => this.o.db
|
|
131
|
+
.prepare(sql)
|
|
132
|
+
.bind(id, version, ...fields.map((field) => change[field] ?? null))
|
|
133
|
+
.first());
|
|
134
|
+
return won !== null;
|
|
135
|
+
}
|
|
136
|
+
async remove(id, cutoff) {
|
|
137
|
+
await this.#call('remove', async () => this.o.db.prepare(Q.removeSteps).bind(id, cutoff).run());
|
|
138
|
+
await this.#call('remove', async () => this.o.db.prepare(Q.removeInstance).bind(id, cutoff).run());
|
|
139
|
+
}
|
|
140
|
+
async storeResult(id, stepIndex, result, completedAt) {
|
|
141
|
+
await this.#call('storeResult', async () => this.o.db
|
|
142
|
+
.prepare(Q.storeResult)
|
|
143
|
+
.bind(id, stepIndex, result, completedAt)
|
|
144
|
+
.run());
|
|
145
|
+
}
|
|
146
|
+
async results(id) {
|
|
147
|
+
const { results } = await this.#call('results', async () => this.o.db
|
|
148
|
+
.prepare(Q.results)
|
|
149
|
+
.bind(id)
|
|
150
|
+
.all());
|
|
151
|
+
return new Map(results.map((r) => [r.step_index, r.result]));
|
|
152
|
+
}
|
|
153
|
+
async due(now) {
|
|
154
|
+
const { results } = await this.#call('due', async () => this.o.db.prepare(Q.due).bind(now).all());
|
|
155
|
+
return results.map(fromRow);
|
|
156
|
+
}
|
|
157
|
+
async removeEndedBefore(cutoff) {
|
|
158
|
+
await this.#call('removeEndedBefore', async () => this.o.db.prepare(Q.removeEndedSteps).bind(cutoff).run());
|
|
159
|
+
await this.#call('removeEndedBefore', async () => this.o.db.prepare(Q.removeEndedInstances).bind(cutoff).run());
|
|
160
|
+
}
|
|
161
|
+
async #call(operation, f) {
|
|
162
|
+
try {
|
|
163
|
+
return await f();
|
|
164
|
+
}
|
|
165
|
+
catch (e) {
|
|
166
|
+
throw toFault(TOOL, operation, e);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Builds the executor. It throws when a registration is refused, as for a
|
|
172
|
+
* Pipeline name outside `[A-Za-z0-9_]{1,64}`.
|
|
173
|
+
*
|
|
174
|
+
* The step state lives in `env.DB`, in the tables of
|
|
175
|
+
* `migrations/0007_create_job_tables.sql`. The toolkit supplies the clock
|
|
176
|
+
* (rule 3), the logger (rule 4), the journal the Step rows go to, and the
|
|
177
|
+
* queue the wake-ups go on (decision 0006, Amendment).
|
|
178
|
+
*/
|
|
179
|
+
export function createCloudflarePipelines(env, toolkit, options) {
|
|
180
|
+
const executor = new ReferenceExecutor({
|
|
181
|
+
registrations: options.registrations,
|
|
182
|
+
store: options.store ?? new D1JobStore({ db: env.DB }),
|
|
183
|
+
queue: toolkit.queue,
|
|
184
|
+
clock: toolkit.clock,
|
|
185
|
+
logger: toolkit.logger,
|
|
186
|
+
journal: toolkit.journal,
|
|
187
|
+
manifest: CLOUDFLARE_MANIFEST,
|
|
188
|
+
...(options.interrupt === undefined
|
|
189
|
+
? {}
|
|
190
|
+
: { interrupt: options.interrupt }),
|
|
191
|
+
});
|
|
192
|
+
return {
|
|
193
|
+
dispatch: async (definition, input, dispatchOptions) => executor.dispatch(definition, input, dispatchOptions),
|
|
194
|
+
status: async (id) => executor.status(id),
|
|
195
|
+
sweep: async () => executor.sweep(),
|
|
196
|
+
async consume(batch) {
|
|
197
|
+
const platform = toQueueBatch(batch);
|
|
198
|
+
const answered = new Set();
|
|
199
|
+
const tracked = {
|
|
200
|
+
messages: platform.messages,
|
|
201
|
+
ack: (id) => {
|
|
202
|
+
answered.add(id);
|
|
203
|
+
platform.ack(id);
|
|
204
|
+
},
|
|
205
|
+
retry: (id, retryOptions) => {
|
|
206
|
+
answered.add(id);
|
|
207
|
+
platform.retry(id, retryOptions);
|
|
208
|
+
},
|
|
209
|
+
};
|
|
210
|
+
await executor.consume(tracked);
|
|
211
|
+
for (const message of platform.messages) {
|
|
212
|
+
if (!answered.has(message.id)) {
|
|
213
|
+
platform.retry(message.id);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
},
|
|
217
|
+
};
|
|
218
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import type { Clock, DeploymentIdentity, MessageId, Queue, QueueBatch, QueueConsumer, SendOptions } from '../../contracts/index.js';
|
|
2
|
+
import type { QueueBinding, QueueMessageBatch } from './bindings.js';
|
|
3
|
+
/**
|
|
4
|
+
* What actually goes on the wire.
|
|
5
|
+
*
|
|
6
|
+
* Cloudflare's producer takes a body and nothing else: `send()` returns queue
|
|
7
|
+
* metrics, not an id, and there is nowhere to attach a header. So the three
|
|
8
|
+
* things `QueueMessage` promises and the platform does not carry — the id the
|
|
9
|
+
* caller was given, when it was enqueued, and WHICH DEPLOYMENT sent it — travel
|
|
10
|
+
* inside the body.
|
|
11
|
+
*
|
|
12
|
+
* `v` is a version marker. The day this shape changes, a consumer will be
|
|
13
|
+
* draining messages of both shapes for as long as the retention window, and a
|
|
14
|
+
* field that says which is which costs one byte now and a rewrite later.
|
|
15
|
+
*/
|
|
16
|
+
export type Envelope<T> = {
|
|
17
|
+
readonly v: 1;
|
|
18
|
+
readonly id: MessageId;
|
|
19
|
+
readonly body: T;
|
|
20
|
+
readonly enqueuedAt: string;
|
|
21
|
+
readonly identity: DeploymentIdentity;
|
|
22
|
+
};
|
|
23
|
+
export type CloudflareQueueOptions = {
|
|
24
|
+
readonly queue: QueueBinding<Envelope<unknown>>;
|
|
25
|
+
readonly clock: Clock;
|
|
26
|
+
readonly identity: DeploymentIdentity;
|
|
27
|
+
readonly maxDelaySeconds: number;
|
|
28
|
+
readonly maxBytes: number;
|
|
29
|
+
readonly batchMaxMessages: number;
|
|
30
|
+
readonly batchMaxBytes: number;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Queue over a Cloudflare Queues producer binding.
|
|
34
|
+
*
|
|
35
|
+
* EVERY CEILING IS CHECKED HERE, BEFORE THE CALL, and none of them is clamped.
|
|
36
|
+
* That is not defensive habit: in workerd the platform enforces none of its own
|
|
37
|
+
* documented limits. A `delaySeconds` of 86,401, a 200 KB body and a
|
|
38
|
+
* 150-message batch were all accepted locally without complaint — see
|
|
39
|
+
* docs/platform-facts.md. An adapter that leaves this to the platform passes
|
|
40
|
+
* every local test and fails once deployed, which is the exact failure the
|
|
41
|
+
* manifest exists to prevent.
|
|
42
|
+
*/
|
|
43
|
+
export declare class CloudflareQueue<T> implements Queue<T> {
|
|
44
|
+
#private;
|
|
45
|
+
private readonly o;
|
|
46
|
+
constructor(o: CloudflareQueueOptions);
|
|
47
|
+
send(body: T, options?: SendOptions): Promise<MessageId>;
|
|
48
|
+
sendBatch(bodies: readonly T[], options?: SendOptions): Promise<readonly MessageId[]>;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The consumer half: Cloudflare's `MessageBatch` as the contract's `QueueBatch`.
|
|
52
|
+
*
|
|
53
|
+
* ACKNOWLEDGEMENT IS PER MESSAGE. The returned batch has no `ackAll` and no
|
|
54
|
+
* `retryAll`, however convenient they look and however much the Cloudflare
|
|
55
|
+
* batch underneath offers them — a batch of ten where the fourth fails must
|
|
56
|
+
* leave nine acknowledged and one retried, and a convenience that makes the
|
|
57
|
+
* wrong thing a one-liner does not belong on the interface.
|
|
58
|
+
*
|
|
59
|
+
* Reordering stays permitted. Nothing here sorts, buffers or re-sequences: the
|
|
60
|
+
* contract says delivery MAY reorder, and an adapter that quietly guaranteed
|
|
61
|
+
* more would have callers depending on it by the time it stopped being true.
|
|
62
|
+
*/
|
|
63
|
+
export declare function toQueueBatch<T>(batch: QueueMessageBatch<Envelope<T>>): QueueBatch<T>;
|
|
64
|
+
/**
|
|
65
|
+
* Runs `consumer` on the batch, then retries every message it neither acked
|
|
66
|
+
* nor retried. Cloudflare acks those implicitly when the handler returns, so
|
|
67
|
+
* without this a forgotten settle loses the message here and redelivers it on
|
|
68
|
+
* every other adapter. A consumer that throws settles nothing, and Cloudflare
|
|
69
|
+
* retries the whole batch.
|
|
70
|
+
*/
|
|
71
|
+
export declare function consumeQueueBatch<T>(batch: QueueMessageBatch<Envelope<T>>, consumer: QueueConsumer<T>): Promise<void>;
|
|
72
|
+
/**
|
|
73
|
+
* Cloudflare's `sendBatch` caps, which are NOT manifest fields — `ToolManifest`
|
|
74
|
+
* has no batch shape, and adding one is a contract change with its own issue.
|
|
75
|
+
* They live here so the adapter can enforce them, and they carry rows in
|
|
76
|
+
* docs/platform-facts.md like everything else.
|
|
77
|
+
*/
|
|
78
|
+
export declare const QUEUE_BATCH_MAX_MESSAGES = 100;
|
|
79
|
+
/** "256KB in total", read as 1,000-byte KB for the same reason as the message cap. */
|
|
80
|
+
export declare const QUEUE_BATCH_MAX_BYTES = 256000;
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { LimitExceeded, checkDuration } from '../../contracts/index.js';
|
|
2
|
+
import { toFault } from './faults.js';
|
|
3
|
+
const TOOL = 'queue';
|
|
4
|
+
const sizeOf = (envelope) => new TextEncoder().encode(JSON.stringify(envelope)).byteLength;
|
|
5
|
+
/**
|
|
6
|
+
* Queue over a Cloudflare Queues producer binding.
|
|
7
|
+
*
|
|
8
|
+
* EVERY CEILING IS CHECKED HERE, BEFORE THE CALL, and none of them is clamped.
|
|
9
|
+
* That is not defensive habit: in workerd the platform enforces none of its own
|
|
10
|
+
* documented limits. A `delaySeconds` of 86,401, a 200 KB body and a
|
|
11
|
+
* 150-message batch were all accepted locally without complaint — see
|
|
12
|
+
* docs/platform-facts.md. An adapter that leaves this to the platform passes
|
|
13
|
+
* every local test and fails once deployed, which is the exact failure the
|
|
14
|
+
* manifest exists to prevent.
|
|
15
|
+
*/
|
|
16
|
+
export class CloudflareQueue {
|
|
17
|
+
o;
|
|
18
|
+
constructor(o) {
|
|
19
|
+
this.o = o;
|
|
20
|
+
}
|
|
21
|
+
async send(body, options) {
|
|
22
|
+
const delaySeconds = this.#checkedDelay(options);
|
|
23
|
+
const envelope = this.#wrap(body);
|
|
24
|
+
this.#checkSize(envelope);
|
|
25
|
+
await this.#call('send', async () => this.o.queue.send(envelope, delaySeconds === undefined ? {} : { delaySeconds }));
|
|
26
|
+
return envelope.id;
|
|
27
|
+
}
|
|
28
|
+
async sendBatch(bodies, options) {
|
|
29
|
+
// No round trip to send nothing. Cloudflare would accept the empty batch;
|
|
30
|
+
// the caller still gets billed for the request.
|
|
31
|
+
if (bodies.length === 0) {
|
|
32
|
+
return [];
|
|
33
|
+
}
|
|
34
|
+
const delaySeconds = this.#checkedDelay(options);
|
|
35
|
+
if (bodies.length > this.o.batchMaxMessages) {
|
|
36
|
+
// THROWN, NOT SPLIT. Splitting would turn one call into several
|
|
37
|
+
// independent ones, so a failure halfway leaves some messages sent and
|
|
38
|
+
// the caller holding a rejected promise with no way to know which. It is
|
|
39
|
+
// also the batch equivalent of clamping a delay, and the contract is
|
|
40
|
+
// explicit that a ceiling is reported rather than quietly worked around.
|
|
41
|
+
throw new LimitExceeded(TOOL, `batch of ${bodies.length} messages exceeds the ${this.o.batchMaxMessages} the target accepts`);
|
|
42
|
+
}
|
|
43
|
+
const envelopes = bodies.map((b) => this.#wrap(b));
|
|
44
|
+
let total = 0;
|
|
45
|
+
for (const envelope of envelopes) {
|
|
46
|
+
total += this.#checkSize(envelope);
|
|
47
|
+
}
|
|
48
|
+
if (total > this.o.batchMaxBytes) {
|
|
49
|
+
throw new LimitExceeded(TOOL, `batch of ${total} bytes exceeds the ${this.o.batchMaxBytes} the target accepts`);
|
|
50
|
+
}
|
|
51
|
+
await this.#call('sendBatch', async () => this.o.queue.sendBatch(envelopes.map((body) => ({ body })), delaySeconds === undefined ? {} : { delaySeconds }));
|
|
52
|
+
return envelopes.map((e) => e.id);
|
|
53
|
+
}
|
|
54
|
+
#wrap(body) {
|
|
55
|
+
return {
|
|
56
|
+
v: 1,
|
|
57
|
+
// The platform generates an id server-side and shows it only to the
|
|
58
|
+
// consumer, so the sender would never learn it. This one is the sender's,
|
|
59
|
+
// and it is what comes back on delivery.
|
|
60
|
+
id: crypto.randomUUID(),
|
|
61
|
+
body,
|
|
62
|
+
enqueuedAt: new Date(this.o.clock.now()).toISOString(),
|
|
63
|
+
identity: this.o.identity,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
#checkedDelay(options) {
|
|
67
|
+
const delaySeconds = options?.delaySeconds;
|
|
68
|
+
if (delaySeconds === undefined) {
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
// Before the ceiling check, which cannot catch it: NaN > maxDelaySeconds is
|
|
72
|
+
// false, so a NaN delay would reach the platform and produce a message that
|
|
73
|
+
// is never visible and therefore never delivered.
|
|
74
|
+
checkDuration(TOOL, 'delaySeconds', delaySeconds);
|
|
75
|
+
if (delaySeconds > this.o.maxDelaySeconds) {
|
|
76
|
+
throw new LimitExceeded(TOOL, `delaySeconds ${delaySeconds} exceeds queueDelayMaxSeconds ${this.o.maxDelaySeconds}`);
|
|
77
|
+
}
|
|
78
|
+
return delaySeconds;
|
|
79
|
+
}
|
|
80
|
+
/** Returns the size, so a batch can total what it has already checked. */
|
|
81
|
+
#checkSize(envelope) {
|
|
82
|
+
// The ENVELOPE is measured, not the caller's body. The identity and the
|
|
83
|
+
// timestamps are on the wire and count against the platform's limit, so
|
|
84
|
+
// measuring the body alone would under-report by exactly the amount this
|
|
85
|
+
// adapter added.
|
|
86
|
+
const bytes = sizeOf(envelope);
|
|
87
|
+
if (bytes > this.o.maxBytes) {
|
|
88
|
+
throw new LimitExceeded(TOOL, `message of ${bytes} bytes exceeds messageMaxBytes ${this.o.maxBytes}`);
|
|
89
|
+
}
|
|
90
|
+
return bytes;
|
|
91
|
+
}
|
|
92
|
+
async #call(operation, f) {
|
|
93
|
+
try {
|
|
94
|
+
return await f();
|
|
95
|
+
}
|
|
96
|
+
catch (e) {
|
|
97
|
+
throw toFault(TOOL, operation, e);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* The consumer half: Cloudflare's `MessageBatch` as the contract's `QueueBatch`.
|
|
103
|
+
*
|
|
104
|
+
* ACKNOWLEDGEMENT IS PER MESSAGE. The returned batch has no `ackAll` and no
|
|
105
|
+
* `retryAll`, however convenient they look and however much the Cloudflare
|
|
106
|
+
* batch underneath offers them — a batch of ten where the fourth fails must
|
|
107
|
+
* leave nine acknowledged and one retried, and a convenience that makes the
|
|
108
|
+
* wrong thing a one-liner does not belong on the interface.
|
|
109
|
+
*
|
|
110
|
+
* Reordering stays permitted. Nothing here sorts, buffers or re-sequences: the
|
|
111
|
+
* contract says delivery MAY reorder, and an adapter that quietly guaranteed
|
|
112
|
+
* more would have callers depending on it by the time it stopped being true.
|
|
113
|
+
*/
|
|
114
|
+
export function toQueueBatch(batch) {
|
|
115
|
+
// Keyed by OUR id, the one send() returned, so the caller can acknowledge a
|
|
116
|
+
// message using the identifier they already hold.
|
|
117
|
+
const platform = new Map();
|
|
118
|
+
const messages = batch.messages.map((m) => {
|
|
119
|
+
platform.set(m.body.id, m);
|
|
120
|
+
return {
|
|
121
|
+
id: m.body.id,
|
|
122
|
+
body: m.body.body,
|
|
123
|
+
// Cloudflare's own counter: 1 on first delivery, incremented on retry.
|
|
124
|
+
attempt: m.attempts,
|
|
125
|
+
enqueuedAt: m.body.enqueuedAt,
|
|
126
|
+
identity: m.body.identity,
|
|
127
|
+
};
|
|
128
|
+
});
|
|
129
|
+
return {
|
|
130
|
+
messages,
|
|
131
|
+
ack: (id) => {
|
|
132
|
+
platform.get(id)?.ack();
|
|
133
|
+
},
|
|
134
|
+
retry: (id, options) => {
|
|
135
|
+
const delaySeconds = options?.delaySeconds;
|
|
136
|
+
platform
|
|
137
|
+
.get(id)
|
|
138
|
+
?.retry(delaySeconds === undefined ? {} : { delaySeconds });
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Runs `consumer` on the batch, then retries every message it neither acked
|
|
144
|
+
* nor retried. Cloudflare acks those implicitly when the handler returns, so
|
|
145
|
+
* without this a forgotten settle loses the message here and redelivers it on
|
|
146
|
+
* every other adapter. A consumer that throws settles nothing, and Cloudflare
|
|
147
|
+
* retries the whole batch.
|
|
148
|
+
*/
|
|
149
|
+
export async function consumeQueueBatch(batch, consumer) {
|
|
150
|
+
const inner = toQueueBatch(batch);
|
|
151
|
+
const settled = new Set();
|
|
152
|
+
await consumer({
|
|
153
|
+
messages: inner.messages,
|
|
154
|
+
ack: (id) => {
|
|
155
|
+
settled.add(id);
|
|
156
|
+
inner.ack(id);
|
|
157
|
+
},
|
|
158
|
+
retry: (id, options) => {
|
|
159
|
+
settled.add(id);
|
|
160
|
+
inner.retry(id, options);
|
|
161
|
+
},
|
|
162
|
+
});
|
|
163
|
+
for (const m of inner.messages) {
|
|
164
|
+
if (!settled.has(m.id)) {
|
|
165
|
+
inner.retry(m.id);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Cloudflare's `sendBatch` caps, which are NOT manifest fields — `ToolManifest`
|
|
171
|
+
* has no batch shape, and adding one is a contract change with its own issue.
|
|
172
|
+
* They live here so the adapter can enforce them, and they carry rows in
|
|
173
|
+
* docs/platform-facts.md like everything else.
|
|
174
|
+
*/
|
|
175
|
+
export const QUEUE_BATCH_MAX_MESSAGES = 100;
|
|
176
|
+
/** "256KB in total", read as 1,000-byte KB for the same reason as the message cap. */
|
|
177
|
+
export const QUEUE_BATCH_MAX_BYTES = 256_000;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { BlobStore, Clock } from '../../contracts/index.js';
|
|
2
|
+
import { type SweepOptions } from '../retention.js';
|
|
3
|
+
export { DEFAULT_RETENTION_SECONDS, type SweepOptions } from '../retention.js';
|
|
4
|
+
export type CloudflareSweepDeps = {
|
|
5
|
+
readonly db: D1Database;
|
|
6
|
+
readonly clock: Clock;
|
|
7
|
+
};
|
|
8
|
+
/** Deletes one batch of ledger claims whose lease ended `olderThanSeconds` ago. */
|
|
9
|
+
export declare function sweepLedger(deps: CloudflareSweepDeps, options?: SweepOptions): Promise<number>;
|
|
10
|
+
/**
|
|
11
|
+
* Deletes one batch of webhook receipts past retention, and their raw bodies.
|
|
12
|
+
* Bodies go first: a crash after them leaves rows the next sweep finishes, and
|
|
13
|
+
* deleting a missing blob is a no-op. Returns how many deliveries it deleted.
|
|
14
|
+
*/
|
|
15
|
+
export declare function sweepWebhookReceipts(deps: CloudflareSweepDeps & {
|
|
16
|
+
readonly blobStore: BlobStore;
|
|
17
|
+
}, options?: SweepOptions): Promise<number>;
|
|
18
|
+
/** For the query-plan tests, as the journal exports its own. */
|
|
19
|
+
export declare const RETENTION_QUERIES: {
|
|
20
|
+
readonly sweepLedger: "\n DELETE FROM ledger_claims WHERE expires_at < ?1 AND key IN (\n SELECT key FROM ledger_claims WHERE expires_at < ?1\n ORDER BY expires_at LIMIT ?2\n )\n";
|
|
21
|
+
readonly sweptDeliveries: "\n SELECT delivery_id, body_key FROM webhook_deliveries d\n WHERE received_at < ?1 AND NOT EXISTS (\n SELECT 1 FROM webhook_tasks t\n WHERE t.delivery_id = d.delivery_id AND t.state NOT IN ('done', 'dead')\n )\n ORDER BY received_at LIMIT ?2\n";
|
|
22
|
+
readonly deleteTasks: "\n DELETE FROM webhook_tasks\n WHERE delivery_id IN (SELECT value FROM json_each(?1))\n AND NOT EXISTS (\n SELECT 1 FROM webhook_tasks k\n WHERE k.delivery_id = webhook_tasks.delivery_id\n AND k.state NOT IN ('done', 'dead')\n )\n";
|
|
23
|
+
readonly deleteDeliveries: "\n DELETE FROM webhook_deliveries\n WHERE delivery_id IN (SELECT value FROM json_each(?1))\n AND NOT EXISTS (\n SELECT 1 FROM webhook_tasks t\n WHERE t.delivery_id = webhook_deliveries.delivery_id\n )\n";
|
|
24
|
+
};
|