@oona/vlo 0.0.0-stage → 0.1.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/LICENSE +201 -0
- package/NOTICE +5 -0
- package/README.md +53 -2
- package/dist/agent.d.ts +107 -0
- package/dist/agent.js +324 -0
- package/dist/cli.d.ts +8 -0
- package/dist/cli.js +1540 -0
- package/dist/define-DwM_Qhbw.js +74 -0
- package/dist/domain-Bs8TeDCv.js +338 -0
- package/dist/domain-CJN6n_JD.d.ts +860 -0
- package/dist/host.d.ts +844 -0
- package/dist/host.js +314 -0
- package/dist/index-CIIcdblQ.d.ts +824 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +4 -0
- package/dist/roles-D25bG980.js +3869 -0
- package/dist/src-DVCYkPA7.js +734 -0
- package/dist/testing.d.ts +58 -0
- package/dist/testing.js +511 -0
- package/dist/types-BLQQMmkc.d.ts +746 -0
- package/dist/vlo_kernel-CtzHHfHA.js +276 -0
- package/package.json +93 -4
- package/wasm/vlo_kernel.d.ts +82 -0
- package/wasm/vlo_kernel.js +382 -0
- package/wasm/vlo_kernel_bg.wasm +0 -0
- package/wasm/vlo_kernel_bg.wasm.d.ts +15 -0
|
@@ -0,0 +1,3869 @@
|
|
|
1
|
+
import { EventEmitter } from "node:events";
|
|
2
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
3
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import pg from "pg";
|
|
6
|
+
import { mkdirSync, readFileSync } from "node:fs";
|
|
7
|
+
import { createRequire } from "node:module";
|
|
8
|
+
import { i as findWorker, n as mergeDomains, s as isTerminalRunStatus } from "./domain-Bs8TeDCv.js";
|
|
9
|
+
import { createServer } from "node:http";
|
|
10
|
+
import { Readable } from "node:stream";
|
|
11
|
+
import { pipeline } from "node:stream/promises";
|
|
12
|
+
// src/blob/file.ts
|
|
13
|
+
/**
|
|
14
|
+
* The file blob store: `<dir>/<first two hex chars>/<sha256>`.
|
|
15
|
+
*
|
|
16
|
+
* Writes land on a temporary file in the same directory and are renamed into
|
|
17
|
+
* place, so a reader never sees a partial blob and two concurrent writers of the
|
|
18
|
+
* same content cannot corrupt it.
|
|
19
|
+
*/
|
|
20
|
+
/** The on-disk {@link BlobStore}. Opened by `openBlobStore("file://…")`. */
|
|
21
|
+
var FileBlobStore = class {
|
|
22
|
+
dir;
|
|
23
|
+
/** `dir` is created on the first `put`. */
|
|
24
|
+
constructor(dir) {
|
|
25
|
+
this.dir = dir;
|
|
26
|
+
}
|
|
27
|
+
/** Writes atomically (temp file + rename) and returns the sha256 hex digest. */
|
|
28
|
+
async put(bytes) {
|
|
29
|
+
const digest = createHash("sha256").update(bytes).digest("hex");
|
|
30
|
+
const target = this.pathFor(digest);
|
|
31
|
+
await mkdir(dirname(target), { recursive: true });
|
|
32
|
+
const temp = `${target}.${randomBytes(8).toString("hex")}.tmp`;
|
|
33
|
+
await writeFile(temp, bytes);
|
|
34
|
+
await rename(temp, target);
|
|
35
|
+
return digest;
|
|
36
|
+
}
|
|
37
|
+
/** Reads the blob; rejects with the `node:fs` error when it is missing. */
|
|
38
|
+
async get(sha256Hex) {
|
|
39
|
+
const buffer = await readFile(this.pathFor(sha256Hex));
|
|
40
|
+
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
|
|
41
|
+
}
|
|
42
|
+
pathFor(sha256Hex) {
|
|
43
|
+
return join(this.dir, sha256Hex.slice(0, 2), sha256Hex);
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
// src/blob/gcs.ts
|
|
47
|
+
/**
|
|
48
|
+
* The Google Cloud Storage blob store: `gs://<bucket>/<prefix>/<first two hex chars>/<sha256>`.
|
|
49
|
+
*
|
|
50
|
+
* Content addressing does the deduplication a bucket cannot: the object name *is* the digest,
|
|
51
|
+
* so `put` checks existence and skips the upload instead of rewriting the same bytes. That
|
|
52
|
+
* also makes a retried offload free, which matters because every oversized payload passes
|
|
53
|
+
* through here on the write path.
|
|
54
|
+
*
|
|
55
|
+
* `@google-cloud/storage` is an optional peer dependency, loaded on first use: a host that
|
|
56
|
+
* stores blobs on disk should not have to install a cloud SDK.
|
|
57
|
+
*/
|
|
58
|
+
/**
|
|
59
|
+
* The Google Cloud Storage {@link BlobStore}. Opened by `openBlobStore("gcs://…")`. Needs
|
|
60
|
+
* the optional peer dependency `@google-cloud/storage` unless a `client` is injected.
|
|
61
|
+
*/
|
|
62
|
+
var GcsBlobStore = class {
|
|
63
|
+
bucketName;
|
|
64
|
+
prefix;
|
|
65
|
+
projectId;
|
|
66
|
+
bucket;
|
|
67
|
+
/** Throws a plain `Error` when `bucket` is empty. No network call is made here. */
|
|
68
|
+
constructor(options) {
|
|
69
|
+
if (!options.bucket) throw new Error("GcsBlobStore: a bucket name is required");
|
|
70
|
+
this.bucketName = options.bucket;
|
|
71
|
+
this.prefix = trim(options.prefix ?? "");
|
|
72
|
+
this.projectId = options.projectId;
|
|
73
|
+
if (options.client !== void 0) this.bucket = Promise.resolve(options.client.bucket(this.bucketName));
|
|
74
|
+
}
|
|
75
|
+
/** Uploads unless an object with that digest already exists; returns the sha256 hex digest. */
|
|
76
|
+
async put(bytes) {
|
|
77
|
+
const digest = createHash("sha256").update(bytes).digest("hex");
|
|
78
|
+
const file = (await this.open()).file(this.keyFor(digest));
|
|
79
|
+
const [exists] = await file.exists();
|
|
80
|
+
if (!exists) await file.save(bytes, {
|
|
81
|
+
resumable: false,
|
|
82
|
+
contentType: "application/octet-stream"
|
|
83
|
+
});
|
|
84
|
+
return digest;
|
|
85
|
+
}
|
|
86
|
+
/** Downloads the blob; rejects with the client's error when it is missing. */
|
|
87
|
+
async get(sha256Hex) {
|
|
88
|
+
const [contents] = await (await this.open()).file(this.keyFor(sha256Hex)).download();
|
|
89
|
+
return contents instanceof Uint8Array ? contents : new Uint8Array(contents);
|
|
90
|
+
}
|
|
91
|
+
keyFor(sha256Hex) {
|
|
92
|
+
const path = `${sha256Hex.slice(0, 2)}/${sha256Hex}`;
|
|
93
|
+
return this.prefix.length > 0 ? `${this.prefix}/${path}` : path;
|
|
94
|
+
}
|
|
95
|
+
open() {
|
|
96
|
+
this.bucket ??= loadStorage(this.projectId).then((client) => client.bucket(this.bucketName));
|
|
97
|
+
return this.bucket;
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
/**
|
|
101
|
+
* Application Default Credentials by default; `GCP_SERVICE_ACCOUNT_KEY_BASE64` when the
|
|
102
|
+
* runtime has no metadata server to ask (Vercel, a laptop, CI).
|
|
103
|
+
*/
|
|
104
|
+
async function loadStorage(projectId) {
|
|
105
|
+
let storage;
|
|
106
|
+
try {
|
|
107
|
+
storage = await import("@google-cloud/storage");
|
|
108
|
+
} catch (error) {
|
|
109
|
+
throw new Error(`gcs blob store: install the optional peer dependency @google-cloud/storage (^7) to use gcs:// urls (${error instanceof Error ? error.message : String(error)})`);
|
|
110
|
+
}
|
|
111
|
+
const encoded = process.env.GCP_SERVICE_ACCOUNT_KEY_BASE64;
|
|
112
|
+
const credentials = encoded === void 0 ? void 0 : JSON.parse(Buffer.from(encoded, "base64").toString());
|
|
113
|
+
return new storage.Storage({
|
|
114
|
+
...projectId !== void 0 ? { projectId } : {},
|
|
115
|
+
...credentials !== void 0 ? { credentials } : {}
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
function trim(value) {
|
|
119
|
+
return value.replace(/^\/+|\/+$/g, "");
|
|
120
|
+
}
|
|
121
|
+
// src/blob/open.ts
|
|
122
|
+
/** Blob store selection by URL scheme: `file://` on disk, `gcs://` in a bucket. */
|
|
123
|
+
const FILE_PREFIX = "file://";
|
|
124
|
+
const GCS_PREFIX = "gcs://";
|
|
125
|
+
/**
|
|
126
|
+
* Opens a blob store by URL: `file://<dir>` (relative to the working directory when the
|
|
127
|
+
* path is) or `gcs://<bucket>/<prefix>`. The GCS client is only loaded on first use.
|
|
128
|
+
* Throws a plain `Error` on any other scheme or an empty directory or bucket.
|
|
129
|
+
*/
|
|
130
|
+
function openBlobStore(url) {
|
|
131
|
+
if (url.startsWith(FILE_PREFIX)) {
|
|
132
|
+
const dir = url.slice(7);
|
|
133
|
+
if (dir.length === 0) throw new Error(`blob store url has no directory: ${url}`);
|
|
134
|
+
return new FileBlobStore(dir);
|
|
135
|
+
}
|
|
136
|
+
if (url.startsWith(GCS_PREFIX)) {
|
|
137
|
+
const [bucket, ...rest] = url.slice(6).split("/");
|
|
138
|
+
if (bucket === void 0 || bucket.length === 0) throw new Error(`blob store url has no bucket: ${url}`);
|
|
139
|
+
const prefix = rest.join("/");
|
|
140
|
+
return new GcsBlobStore({
|
|
141
|
+
bucket,
|
|
142
|
+
...prefix.length > 0 ? { prefix } : {}
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
throw new Error(`unsupported blob store url: ${url}`);
|
|
146
|
+
}
|
|
147
|
+
// src/journal/dialect.ts
|
|
148
|
+
const PG = {
|
|
149
|
+
kind: "pg",
|
|
150
|
+
skipLocked: " FOR UPDATE SKIP LOCKED"
|
|
151
|
+
};
|
|
152
|
+
/** SQLite serialises writers with `BEGIN IMMEDIATE`, so claims never collide. */
|
|
153
|
+
const SQLITE = {
|
|
154
|
+
kind: "sqlite",
|
|
155
|
+
skipLocked: ""
|
|
156
|
+
};
|
|
157
|
+
async function one(x, sql, params) {
|
|
158
|
+
return (await x.all(sql, params))[0] ?? null;
|
|
159
|
+
}
|
|
160
|
+
/** JSON as a bound parameter: one text encoding that both dialects accept. */
|
|
161
|
+
function jsonParam(value) {
|
|
162
|
+
return JSON.stringify(value ?? null);
|
|
163
|
+
}
|
|
164
|
+
function orNull(value) {
|
|
165
|
+
return value ?? null;
|
|
166
|
+
}
|
|
167
|
+
// src/journal/migrations/pg/0001_init.ts
|
|
168
|
+
const sql$5 = "-- Vlo journal, Postgres.\n--\n-- Every object is unqualified on purpose: the journal connects with\n-- `search_path = <schema>` (default `vlo`) and creates that schema before this\n-- file runs, so nothing here can reach `public`.\n--\n-- Hashed or replayed JSON (`state`, `kernel_state`, `payload`, `input`,\n-- `output`, `schemas.retry_policy`) is `text`, never `jsonb`: jsonb rewrites key\n-- order and numeric lexemes, which would break re-fold equality.\n-- Every instant is a `bigint` millisecond epoch named `*_ms`, so Postgres,\n-- SQLite and the TypeScript rows agree on one representation.\n\nCREATE TABLE IF NOT EXISTS migrations (\n version text PRIMARY KEY,\n applied_at_ms bigint NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS runs (\n run_id text PRIMARY KEY,\n namespace text NOT NULL DEFAULT 'default',\n workflow text NOT NULL,\n component_digest text NOT NULL,\n status text NOT NULL,\n last_seq bigint NOT NULL DEFAULT 0,\n parent_run_id text,\n parent_step_id text,\n continued_from text,\n input text,\n input_ref text,\n output text,\n output_ref text,\n search jsonb NOT NULL DEFAULT '{}',\n assignee text,\n created_at_ms bigint NOT NULL,\n updated_at_ms bigint NOT NULL,\n started_at_ms bigint,\n closed_at_ms bigint,\n parent_notified_at_ms bigint,\n start_claimed_until_ms bigint,\n notify_claimed_until_ms bigint\n);\n\n-- Outbox stage \"start runs\".\nCREATE INDEX IF NOT EXISTS runs_created_idx\n ON runs (created_at_ms) WHERE status = 'created';\n\n-- Outbox stage \"notify parents\".\nCREATE INDEX IF NOT EXISTS runs_notify_idx\n ON runs (closed_at_ms)\n WHERE parent_run_id IS NOT NULL AND parent_notified_at_ms IS NULL;\n\nCREATE INDEX IF NOT EXISTS runs_query_idx ON runs (namespace, status, created_at_ms);\nCREATE INDEX IF NOT EXISTS runs_search_idx ON runs USING gin (search);\n\nCREATE TABLE IF NOT EXISTS events (\n run_id text NOT NULL REFERENCES runs (run_id) ON DELETE CASCADE,\n seq bigint NOT NULL,\n step_id text NOT NULL,\n attempt integer NOT NULL,\n kind text NOT NULL,\n status text NOT NULL,\n cause text,\n schema_ref text,\n payload text,\n payload_ref text,\n error text,\n usage jsonb,\n random text NOT NULL,\n state_hash text NOT NULL,\n parent_run_id text,\n parent_step_id text,\n ts_ms bigint NOT NULL,\n PRIMARY KEY (run_id, seq)\n);\n\nCREATE TABLE IF NOT EXISTS run_state (\n run_id text PRIMARY KEY REFERENCES runs (run_id) ON DELETE CASCADE,\n seq bigint NOT NULL,\n bundle_digest text NOT NULL,\n kernel_state text NOT NULL,\n state text,\n state_ref text,\n state_hash text NOT NULL,\n CONSTRAINT run_state_one_body CHECK ((state IS NULL) <> (state_ref IS NULL))\n);\n\nCREATE TABLE IF NOT EXISTS tasks (\n task_id text PRIMARY KEY,\n run_id text NOT NULL REFERENCES runs (run_id) ON DELETE CASCADE,\n step_id text NOT NULL,\n attempt integer NOT NULL,\n activity text NOT NULL,\n schema_ref text,\n queue text NOT NULL,\n input text,\n input_ref text,\n retry_policy jsonb NOT NULL,\n status text NOT NULL,\n idempotency_key text NOT NULL,\n not_before_ms bigint NOT NULL,\n dispatched_at_ms bigint,\n dispatch_attempts integer NOT NULL DEFAULT 0,\n dispatch_claimed_until_ms bigint,\n lease_ttl_ms bigint NOT NULL,\n lease_until_ms bigint,\n worker_id text,\n heartbeat_at_ms bigint,\n created_at_ms bigint NOT NULL,\n updated_at_ms bigint NOT NULL,\n UNIQUE (run_id, step_id),\n UNIQUE (idempotency_key)\n);\n\n-- Outbox stage \"push tasks\".\nCREATE INDEX IF NOT EXISTS tasks_dispatch_idx\n ON tasks (queue, not_before_ms)\n WHERE status = 'scheduled' AND dispatched_at_ms IS NULL;\n\n-- Lease reaper.\nCREATE INDEX IF NOT EXISTS tasks_lease_idx\n ON tasks (lease_until_ms) WHERE status = 'running';\n\nCREATE INDEX IF NOT EXISTS tasks_run_idx ON tasks (run_id);\n\nCREATE TABLE IF NOT EXISTS timers (\n run_id text NOT NULL REFERENCES runs (run_id) ON DELETE CASCADE,\n step_id text NOT NULL,\n fire_at_ms bigint NOT NULL,\n fired_at_ms bigint,\n claimed_until_ms bigint,\n PRIMARY KEY (run_id, step_id)\n);\n\nCREATE INDEX IF NOT EXISTS timers_due_idx\n ON timers (fire_at_ms) WHERE fired_at_ms IS NULL;\n\nCREATE TABLE IF NOT EXISTS signal_waits (\n run_id text NOT NULL REFERENCES runs (run_id) ON DELETE CASCADE,\n step_id text NOT NULL,\n name text NOT NULL,\n schema_ref text,\n expires_at_ms bigint,\n PRIMARY KEY (run_id, step_id)\n);\n\nCREATE INDEX IF NOT EXISTS signal_waits_name_idx ON signal_waits (run_id, name);\n\nCREATE TABLE IF NOT EXISTS signals (\n signal_id text PRIMARY KEY,\n run_id text NOT NULL REFERENCES runs (run_id) ON DELETE CASCADE,\n name text NOT NULL,\n payload text,\n payload_ref text,\n sender text,\n created_at_ms bigint NOT NULL,\n delivered_at_ms bigint,\n delivered_step_id text\n);\n\nCREATE INDEX IF NOT EXISTS signals_pending_idx\n ON signals (run_id, name, created_at_ms) WHERE delivered_at_ms IS NULL;\n\nCREATE TABLE IF NOT EXISTS schemas (\n name text NOT NULL,\n version text NOT NULL,\n json_schema text NOT NULL,\n retry_policy text,\n created_at_ms bigint NOT NULL,\n PRIMARY KEY (name, version)\n);\n\nCREATE TABLE IF NOT EXISTS bundles (\n digest text PRIMARY KEY,\n workflow text NOT NULL,\n kind text NOT NULL,\n blob_ref text NOT NULL,\n source_map_ref text,\n created_at_ms bigint NOT NULL\n);\n";
|
|
169
|
+
// src/journal/migrations/pg/0002_task_timeout.ts
|
|
170
|
+
const sql$4 = `-- Vlo journal, Postgres. Activity timeouts.
|
|
171
|
+
|
|
172
|
+
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS timeout_ms bigint;
|
|
173
|
+
|
|
174
|
+
-- Timeout backstop: running attempts whose dispatch is older than their budget.
|
|
175
|
+
CREATE INDEX IF NOT EXISTS tasks_timeout_idx
|
|
176
|
+
ON tasks (dispatched_at_ms)
|
|
177
|
+
WHERE status = 'running' AND timeout_ms IS NOT NULL;
|
|
178
|
+
`;
|
|
179
|
+
// src/journal/migrations/pg/0003_continued_to.ts
|
|
180
|
+
const sql$3 = `-- Vlo journal, Postgres. continue_as_new successor link.
|
|
181
|
+
|
|
182
|
+
ALTER TABLE runs ADD COLUMN IF NOT EXISTS continued_to text;
|
|
183
|
+
`;
|
|
184
|
+
// src/journal/migrations/sqlite/0001_init.ts
|
|
185
|
+
const sql$2 = "-- Vlo journal, SQLite. Mirror of migrations/pg/0001_init.sql.\n--\n-- SQLite has one file per journal, so tables are unprefixed. Millisecond epochs\n-- are INTEGER, JSON is TEXT (SQLite has no jsonb), and hashed or replayed JSON\n-- stays byte-exact for the same reason as in Postgres.\n\nCREATE TABLE IF NOT EXISTS migrations (\n version TEXT PRIMARY KEY,\n applied_at_ms INTEGER NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS runs (\n run_id TEXT PRIMARY KEY,\n namespace TEXT NOT NULL DEFAULT 'default',\n workflow TEXT NOT NULL,\n component_digest TEXT NOT NULL,\n status TEXT NOT NULL,\n last_seq INTEGER NOT NULL DEFAULT 0,\n parent_run_id TEXT,\n parent_step_id TEXT,\n continued_from TEXT,\n input TEXT,\n input_ref TEXT,\n output TEXT,\n output_ref TEXT,\n search TEXT NOT NULL DEFAULT '{}',\n assignee TEXT,\n created_at_ms INTEGER NOT NULL,\n updated_at_ms INTEGER NOT NULL,\n started_at_ms INTEGER,\n closed_at_ms INTEGER,\n parent_notified_at_ms INTEGER,\n start_claimed_until_ms INTEGER,\n notify_claimed_until_ms INTEGER\n);\n\n-- Outbox stage \"start runs\".\nCREATE INDEX IF NOT EXISTS runs_created_idx\n ON runs (created_at_ms) WHERE status = 'created';\n\n-- Outbox stage \"notify parents\".\nCREATE INDEX IF NOT EXISTS runs_notify_idx\n ON runs (closed_at_ms)\n WHERE parent_run_id IS NOT NULL AND parent_notified_at_ms IS NULL;\n\nCREATE INDEX IF NOT EXISTS runs_query_idx ON runs (namespace, status, created_at_ms);\n\nCREATE TABLE IF NOT EXISTS events (\n run_id TEXT NOT NULL REFERENCES runs (run_id) ON DELETE CASCADE,\n seq INTEGER NOT NULL,\n step_id TEXT NOT NULL,\n attempt INTEGER NOT NULL,\n kind TEXT NOT NULL,\n status TEXT NOT NULL,\n cause TEXT,\n schema_ref TEXT,\n payload TEXT,\n payload_ref TEXT,\n error TEXT,\n usage TEXT,\n random TEXT NOT NULL,\n state_hash TEXT NOT NULL,\n parent_run_id TEXT,\n parent_step_id TEXT,\n ts_ms INTEGER NOT NULL,\n PRIMARY KEY (run_id, seq)\n);\n\nCREATE TABLE IF NOT EXISTS run_state (\n run_id TEXT PRIMARY KEY REFERENCES runs (run_id) ON DELETE CASCADE,\n seq INTEGER NOT NULL,\n bundle_digest TEXT NOT NULL,\n kernel_state TEXT NOT NULL,\n state TEXT,\n state_ref TEXT,\n state_hash TEXT NOT NULL,\n CONSTRAINT run_state_one_body CHECK ((state IS NULL) <> (state_ref IS NULL))\n);\n\nCREATE TABLE IF NOT EXISTS tasks (\n task_id TEXT PRIMARY KEY,\n run_id TEXT NOT NULL REFERENCES runs (run_id) ON DELETE CASCADE,\n step_id TEXT NOT NULL,\n attempt INTEGER NOT NULL,\n activity TEXT NOT NULL,\n schema_ref TEXT,\n queue TEXT NOT NULL,\n input TEXT,\n input_ref TEXT,\n retry_policy TEXT NOT NULL,\n status TEXT NOT NULL,\n idempotency_key TEXT NOT NULL,\n not_before_ms INTEGER NOT NULL,\n dispatched_at_ms INTEGER,\n dispatch_attempts INTEGER NOT NULL DEFAULT 0,\n dispatch_claimed_until_ms INTEGER,\n lease_ttl_ms INTEGER NOT NULL,\n lease_until_ms INTEGER,\n worker_id TEXT,\n heartbeat_at_ms INTEGER,\n created_at_ms INTEGER NOT NULL,\n updated_at_ms INTEGER NOT NULL,\n UNIQUE (run_id, step_id),\n UNIQUE (idempotency_key)\n);\n\n-- Outbox stage \"push tasks\".\nCREATE INDEX IF NOT EXISTS tasks_dispatch_idx\n ON tasks (queue, not_before_ms)\n WHERE status = 'scheduled' AND dispatched_at_ms IS NULL;\n\n-- Lease reaper.\nCREATE INDEX IF NOT EXISTS tasks_lease_idx\n ON tasks (lease_until_ms) WHERE status = 'running';\n\nCREATE INDEX IF NOT EXISTS tasks_run_idx ON tasks (run_id);\n\nCREATE TABLE IF NOT EXISTS timers (\n run_id TEXT NOT NULL REFERENCES runs (run_id) ON DELETE CASCADE,\n step_id TEXT NOT NULL,\n fire_at_ms INTEGER NOT NULL,\n fired_at_ms INTEGER,\n claimed_until_ms INTEGER,\n PRIMARY KEY (run_id, step_id)\n);\n\nCREATE INDEX IF NOT EXISTS timers_due_idx\n ON timers (fire_at_ms) WHERE fired_at_ms IS NULL;\n\nCREATE TABLE IF NOT EXISTS signal_waits (\n run_id TEXT NOT NULL REFERENCES runs (run_id) ON DELETE CASCADE,\n step_id TEXT NOT NULL,\n name TEXT NOT NULL,\n schema_ref TEXT,\n expires_at_ms INTEGER,\n PRIMARY KEY (run_id, step_id)\n);\n\nCREATE INDEX IF NOT EXISTS signal_waits_name_idx ON signal_waits (run_id, name);\n\nCREATE TABLE IF NOT EXISTS signals (\n signal_id TEXT PRIMARY KEY,\n run_id TEXT NOT NULL REFERENCES runs (run_id) ON DELETE CASCADE,\n name TEXT NOT NULL,\n payload TEXT,\n payload_ref TEXT,\n sender TEXT,\n created_at_ms INTEGER NOT NULL,\n delivered_at_ms INTEGER,\n delivered_step_id TEXT\n);\n\nCREATE INDEX IF NOT EXISTS signals_pending_idx\n ON signals (run_id, name, created_at_ms) WHERE delivered_at_ms IS NULL;\n\nCREATE TABLE IF NOT EXISTS schemas (\n name TEXT NOT NULL,\n version TEXT NOT NULL,\n json_schema TEXT NOT NULL,\n retry_policy TEXT,\n created_at_ms INTEGER NOT NULL,\n PRIMARY KEY (name, version)\n);\n\nCREATE TABLE IF NOT EXISTS bundles (\n digest TEXT PRIMARY KEY,\n workflow TEXT NOT NULL,\n kind TEXT NOT NULL,\n blob_ref TEXT NOT NULL,\n source_map_ref TEXT,\n created_at_ms INTEGER NOT NULL\n);\n";
|
|
186
|
+
// src/journal/migrations/sqlite/0002_task_timeout.ts
|
|
187
|
+
const sql$1 = `-- Vlo journal, SQLite. Mirror of migrations/pg/0002_task_timeout.
|
|
188
|
+
|
|
189
|
+
ALTER TABLE tasks ADD COLUMN timeout_ms INTEGER;
|
|
190
|
+
|
|
191
|
+
-- Timeout backstop: running attempts whose dispatch is older than their budget.
|
|
192
|
+
CREATE INDEX IF NOT EXISTS tasks_timeout_idx
|
|
193
|
+
ON tasks (dispatched_at_ms)
|
|
194
|
+
WHERE status = 'running' AND timeout_ms IS NOT NULL;
|
|
195
|
+
`;
|
|
196
|
+
// src/journal/migrations/sqlite/0003_continued_to.ts
|
|
197
|
+
const sql = `-- Vlo journal, SQLite. Mirror of migrations/pg/0003_continued_to.
|
|
198
|
+
|
|
199
|
+
ALTER TABLE runs ADD COLUMN continued_to TEXT;
|
|
200
|
+
`;
|
|
201
|
+
// src/journal/migrations.ts
|
|
202
|
+
const MIGRATION_VERSIONS = [
|
|
203
|
+
"0001_init",
|
|
204
|
+
"0002_task_timeout",
|
|
205
|
+
"0003_continued_to"
|
|
206
|
+
];
|
|
207
|
+
const MIGRATIONS = {
|
|
208
|
+
pg: {
|
|
209
|
+
"0001_init": sql$5,
|
|
210
|
+
"0002_task_timeout": sql$4,
|
|
211
|
+
"0003_continued_to": sql$3
|
|
212
|
+
},
|
|
213
|
+
sqlite: {
|
|
214
|
+
"0001_init": sql$2,
|
|
215
|
+
"0002_task_timeout": sql$1,
|
|
216
|
+
"0003_continued_to": sql
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
function migrationSql(kind, version) {
|
|
220
|
+
return MIGRATIONS[kind][version];
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* @param hasMigrationsTable dialect-specific probe, so the runner needs no
|
|
224
|
+
* bootstrap copy of the `migrations` DDL.
|
|
225
|
+
*/
|
|
226
|
+
async function applyMigrations(x, kind, hasMigrationsTable, nowMs) {
|
|
227
|
+
const applied = await hasMigrationsTable() ? await appliedVersions(x) : /* @__PURE__ */ new Set();
|
|
228
|
+
for (const version of MIGRATION_VERSIONS) {
|
|
229
|
+
if (applied.has(version)) continue;
|
|
230
|
+
await x.exec(migrationSql(kind, version));
|
|
231
|
+
await x.run("INSERT INTO migrations (version, applied_at_ms) VALUES (?, ?) ON CONFLICT (version) DO NOTHING", [version, nowMs]);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
async function appliedVersions(x) {
|
|
235
|
+
const rows = await x.all("SELECT version FROM migrations");
|
|
236
|
+
return new Set(rows.map((r) => r.version));
|
|
237
|
+
}
|
|
238
|
+
// src/journal/rows.ts
|
|
239
|
+
function num(value) {
|
|
240
|
+
return typeof value === "number" ? value : Number(value);
|
|
241
|
+
}
|
|
242
|
+
function optNum(value) {
|
|
243
|
+
return value == null ? null : num(value);
|
|
244
|
+
}
|
|
245
|
+
function parseJson(value) {
|
|
246
|
+
if (value == null) return null;
|
|
247
|
+
return typeof value === "string" ? JSON.parse(value) : value;
|
|
248
|
+
}
|
|
249
|
+
/** Copies the entries that are actually present, leaving absent columns off the row. */
|
|
250
|
+
function withPresent(row, optional) {
|
|
251
|
+
const sink = row;
|
|
252
|
+
for (const [key, value] of Object.entries(optional)) if (value !== null && value !== void 0) sink[key] = value;
|
|
253
|
+
return row;
|
|
254
|
+
}
|
|
255
|
+
function mapRun(r) {
|
|
256
|
+
return withPresent({
|
|
257
|
+
run_id: String(r.run_id),
|
|
258
|
+
namespace: String(r.namespace),
|
|
259
|
+
workflow: String(r.workflow),
|
|
260
|
+
component_digest: String(r.component_digest),
|
|
261
|
+
status: r.status,
|
|
262
|
+
last_seq: num(r.last_seq),
|
|
263
|
+
search: parseJson(r.search) ?? {},
|
|
264
|
+
created_at_ms: num(r.created_at_ms),
|
|
265
|
+
updated_at_ms: num(r.updated_at_ms)
|
|
266
|
+
}, {
|
|
267
|
+
parent_run_id: r.parent_run_id,
|
|
268
|
+
parent_step_id: r.parent_step_id,
|
|
269
|
+
continued_from: r.continued_from,
|
|
270
|
+
continued_to: r.continued_to,
|
|
271
|
+
input: r.input,
|
|
272
|
+
input_ref: r.input_ref,
|
|
273
|
+
output: r.output,
|
|
274
|
+
output_ref: r.output_ref,
|
|
275
|
+
assignee: r.assignee,
|
|
276
|
+
started_at_ms: optNum(r.started_at_ms),
|
|
277
|
+
closed_at_ms: optNum(r.closed_at_ms),
|
|
278
|
+
parent_notified_at_ms: optNum(r.parent_notified_at_ms),
|
|
279
|
+
start_claimed_until_ms: optNum(r.start_claimed_until_ms),
|
|
280
|
+
notify_claimed_until_ms: optNum(r.notify_claimed_until_ms)
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
function mapEvent(r) {
|
|
284
|
+
return withPresent({
|
|
285
|
+
run_id: String(r.run_id),
|
|
286
|
+
seq: num(r.seq),
|
|
287
|
+
step_id: String(r.step_id),
|
|
288
|
+
attempt: num(r.attempt),
|
|
289
|
+
kind: r.kind,
|
|
290
|
+
status: r.status,
|
|
291
|
+
ts_ms: num(r.ts_ms),
|
|
292
|
+
random: String(r.random),
|
|
293
|
+
state_hash: String(r.state_hash)
|
|
294
|
+
}, {
|
|
295
|
+
cause: r.cause,
|
|
296
|
+
schema_ref: r.schema_ref,
|
|
297
|
+
payload: r.payload,
|
|
298
|
+
payload_ref: r.payload_ref,
|
|
299
|
+
error: r.error,
|
|
300
|
+
usage: parseJson(r.usage),
|
|
301
|
+
parent_run_id: r.parent_run_id,
|
|
302
|
+
parent_step_id: r.parent_step_id
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
function mapState(r) {
|
|
306
|
+
return withPresent({
|
|
307
|
+
run_id: String(r.run_id),
|
|
308
|
+
seq: num(r.seq),
|
|
309
|
+
bundle_digest: String(r.bundle_digest),
|
|
310
|
+
kernel_state: String(r.kernel_state),
|
|
311
|
+
state_hash: String(r.state_hash)
|
|
312
|
+
}, {
|
|
313
|
+
state: r.state,
|
|
314
|
+
state_ref: r.state_ref
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
function mapTask(r) {
|
|
318
|
+
return withPresent({
|
|
319
|
+
task_id: String(r.task_id),
|
|
320
|
+
run_id: String(r.run_id),
|
|
321
|
+
step_id: String(r.step_id),
|
|
322
|
+
attempt: num(r.attempt),
|
|
323
|
+
activity: String(r.activity),
|
|
324
|
+
queue: String(r.queue),
|
|
325
|
+
retry_policy: parseJson(r.retry_policy),
|
|
326
|
+
status: r.status,
|
|
327
|
+
idempotency_key: String(r.idempotency_key),
|
|
328
|
+
not_before_ms: num(r.not_before_ms),
|
|
329
|
+
dispatch_attempts: num(r.dispatch_attempts),
|
|
330
|
+
lease_ttl_ms: num(r.lease_ttl_ms),
|
|
331
|
+
created_at_ms: num(r.created_at_ms),
|
|
332
|
+
updated_at_ms: num(r.updated_at_ms)
|
|
333
|
+
}, {
|
|
334
|
+
schema_ref: r.schema_ref,
|
|
335
|
+
input: r.input,
|
|
336
|
+
input_ref: r.input_ref,
|
|
337
|
+
dispatched_at_ms: optNum(r.dispatched_at_ms),
|
|
338
|
+
dispatch_claimed_until_ms: optNum(r.dispatch_claimed_until_ms),
|
|
339
|
+
timeout_ms: optNum(r.timeout_ms),
|
|
340
|
+
lease_until_ms: optNum(r.lease_until_ms),
|
|
341
|
+
worker_id: r.worker_id,
|
|
342
|
+
heartbeat_at_ms: optNum(r.heartbeat_at_ms)
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
function mapTimer(r) {
|
|
346
|
+
return withPresent({
|
|
347
|
+
run_id: String(r.run_id),
|
|
348
|
+
step_id: String(r.step_id),
|
|
349
|
+
fire_at_ms: num(r.fire_at_ms)
|
|
350
|
+
}, {
|
|
351
|
+
fired_at_ms: optNum(r.fired_at_ms),
|
|
352
|
+
claimed_until_ms: optNum(r.claimed_until_ms)
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
function mapSignalWait(r) {
|
|
356
|
+
return withPresent({
|
|
357
|
+
run_id: String(r.run_id),
|
|
358
|
+
step_id: String(r.step_id),
|
|
359
|
+
name: String(r.name)
|
|
360
|
+
}, {
|
|
361
|
+
schema_ref: r.schema_ref,
|
|
362
|
+
expires_at_ms: optNum(r.expires_at_ms)
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
function mapSignal(r) {
|
|
366
|
+
return withPresent({
|
|
367
|
+
signal_id: String(r.signal_id),
|
|
368
|
+
run_id: String(r.run_id),
|
|
369
|
+
name: String(r.name),
|
|
370
|
+
created_at_ms: num(r.created_at_ms)
|
|
371
|
+
}, {
|
|
372
|
+
payload: r.payload,
|
|
373
|
+
payload_ref: r.payload_ref,
|
|
374
|
+
sender: r.sender,
|
|
375
|
+
delivered_at_ms: optNum(r.delivered_at_ms),
|
|
376
|
+
delivered_step_id: r.delivered_step_id
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
function mapSchema(r) {
|
|
380
|
+
return withPresent({
|
|
381
|
+
name: String(r.name),
|
|
382
|
+
version: String(r.version),
|
|
383
|
+
json_schema: String(r.json_schema)
|
|
384
|
+
}, { retry_policy: r.retry_policy });
|
|
385
|
+
}
|
|
386
|
+
// src/journal/reads.ts
|
|
387
|
+
const RUN_COLUMNS = "*";
|
|
388
|
+
const DEFAULT_QUERY_LIMIT = 100;
|
|
389
|
+
async function readEvents(x, runId, sinceSeq = 0) {
|
|
390
|
+
return (await x.all("SELECT * FROM events WHERE run_id = ? AND seq > ? ORDER BY seq", [runId, sinceSeq])).map(mapEvent);
|
|
391
|
+
}
|
|
392
|
+
async function getRun(x, runId) {
|
|
393
|
+
const row = await one(x, `SELECT ${RUN_COLUMNS} FROM runs WHERE run_id = ?`, [runId]);
|
|
394
|
+
return row ? mapRun(row) : null;
|
|
395
|
+
}
|
|
396
|
+
async function getState(x, runId) {
|
|
397
|
+
const row = await one(x, "SELECT * FROM run_state WHERE run_id = ?", [runId]);
|
|
398
|
+
return row ? mapState(row) : null;
|
|
399
|
+
}
|
|
400
|
+
async function getTask(x, taskId) {
|
|
401
|
+
const row = await one(x, "SELECT * FROM tasks WHERE task_id = ?", [taskId]);
|
|
402
|
+
return row ? mapTask(row) : null;
|
|
403
|
+
}
|
|
404
|
+
async function listTasks(x, runId) {
|
|
405
|
+
return (await x.all("SELECT * FROM tasks WHERE run_id = ? ORDER BY created_at_ms, task_id", [runId])).map(mapTask);
|
|
406
|
+
}
|
|
407
|
+
async function queryRuns(x, q) {
|
|
408
|
+
const where = [];
|
|
409
|
+
const params = [];
|
|
410
|
+
if (q.namespace !== void 0) {
|
|
411
|
+
where.push("namespace = ?");
|
|
412
|
+
params.push(q.namespace);
|
|
413
|
+
}
|
|
414
|
+
if (q.status !== void 0) {
|
|
415
|
+
where.push("status = ?");
|
|
416
|
+
params.push(q.status);
|
|
417
|
+
}
|
|
418
|
+
if (q.workflow !== void 0) {
|
|
419
|
+
where.push("workflow = ?");
|
|
420
|
+
params.push(q.workflow);
|
|
421
|
+
}
|
|
422
|
+
params.push(q.limit ?? DEFAULT_QUERY_LIMIT);
|
|
423
|
+
const filter = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
|
|
424
|
+
return (await x.all(`SELECT ${RUN_COLUMNS} FROM runs ${filter} ORDER BY created_at_ms DESC, run_id DESC LIMIT ?`, params)).map(mapRun);
|
|
425
|
+
}
|
|
426
|
+
async function dueTimers(x, nowMs, limit) {
|
|
427
|
+
return (await x.all(`SELECT * FROM timers
|
|
428
|
+
WHERE fired_at_ms IS NULL AND fire_at_ms <= ?
|
|
429
|
+
ORDER BY fire_at_ms, run_id, step_id
|
|
430
|
+
LIMIT ?`, [nowMs, limit])).map(mapTimer);
|
|
431
|
+
}
|
|
432
|
+
async function expiredLeases(x, nowMs, limit) {
|
|
433
|
+
return (await x.all(`SELECT * FROM tasks
|
|
434
|
+
WHERE status = 'running' AND lease_until_ms IS NOT NULL AND lease_until_ms < ?
|
|
435
|
+
ORDER BY lease_until_ms, task_id
|
|
436
|
+
LIMIT ?`, [nowMs, limit])).map(mapTask);
|
|
437
|
+
}
|
|
438
|
+
/**
|
|
439
|
+
* Running attempts whose wall-clock budget has run out. A task dispatched but not yet
|
|
440
|
+
* stamped has a NULL `dispatched_at_ms`, and NULL + timeout is NULL, so it is never due.
|
|
441
|
+
*/
|
|
442
|
+
async function expiredTimeouts(x, nowMs, limit) {
|
|
443
|
+
return (await x.all(`SELECT * FROM tasks
|
|
444
|
+
WHERE status = 'running'
|
|
445
|
+
AND timeout_ms IS NOT NULL
|
|
446
|
+
AND dispatched_at_ms + timeout_ms < ?
|
|
447
|
+
ORDER BY dispatched_at_ms, task_id
|
|
448
|
+
LIMIT ?`, [nowMs, limit])).map(mapTask);
|
|
449
|
+
}
|
|
450
|
+
// src/journal/apply.ts
|
|
451
|
+
const TERMINAL_RUN_STATUS = /* @__PURE__ */ new Set([
|
|
452
|
+
"completed",
|
|
453
|
+
"failed",
|
|
454
|
+
"cancelled",
|
|
455
|
+
"continued"
|
|
456
|
+
]);
|
|
457
|
+
const TERMINAL_TASK_STATUS = /* @__PURE__ */ new Set([
|
|
458
|
+
"succeeded",
|
|
459
|
+
"failed",
|
|
460
|
+
"cancelled"
|
|
461
|
+
]);
|
|
462
|
+
const INSERT_RUN = `
|
|
463
|
+
INSERT INTO runs (
|
|
464
|
+
run_id, namespace, workflow, component_digest, status, last_seq,
|
|
465
|
+
parent_run_id, parent_step_id, continued_from, input, input_ref, search,
|
|
466
|
+
created_at_ms, updated_at_ms
|
|
467
|
+
) VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
468
|
+
ON CONFLICT (run_id) DO NOTHING`;
|
|
469
|
+
const INSERT_EVENT = `
|
|
470
|
+
INSERT INTO events (
|
|
471
|
+
run_id, seq, step_id, attempt, kind, status, cause, schema_ref, payload,
|
|
472
|
+
payload_ref, error, usage, random, state_hash, parent_run_id, parent_step_id, ts_ms
|
|
473
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
|
|
474
|
+
const UPSERT_STATE = `
|
|
475
|
+
INSERT INTO run_state (run_id, seq, bundle_digest, kernel_state, state, state_ref, state_hash)
|
|
476
|
+
VALUES (?, ?, COALESCE(?, (SELECT component_digest FROM runs WHERE run_id = ?)), ?, ?, ?, ?)
|
|
477
|
+
ON CONFLICT (run_id) DO UPDATE SET
|
|
478
|
+
seq = excluded.seq,
|
|
479
|
+
bundle_digest = excluded.bundle_digest,
|
|
480
|
+
kernel_state = excluded.kernel_state,
|
|
481
|
+
state = excluded.state,
|
|
482
|
+
state_ref = excluded.state_ref,
|
|
483
|
+
state_hash = excluded.state_hash`;
|
|
484
|
+
/**
|
|
485
|
+
* A replay of the same attempt is a no-op; a retry at a higher attempt resets
|
|
486
|
+
* the outbox and lease columns so the dispatcher picks the task up again.
|
|
487
|
+
*/
|
|
488
|
+
const UPSERT_TASK = `
|
|
489
|
+
INSERT INTO tasks (
|
|
490
|
+
task_id, run_id, step_id, attempt, activity, schema_ref, queue, input,
|
|
491
|
+
retry_policy, status, idempotency_key, not_before_ms, dispatch_attempts,
|
|
492
|
+
lease_ttl_ms, timeout_ms, created_at_ms, updated_at_ms
|
|
493
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'scheduled', ?, ?, 0, ?, ?, ?, ?)
|
|
494
|
+
ON CONFLICT (task_id) DO UPDATE SET
|
|
495
|
+
attempt = excluded.attempt,
|
|
496
|
+
activity = excluded.activity,
|
|
497
|
+
schema_ref = excluded.schema_ref,
|
|
498
|
+
queue = excluded.queue,
|
|
499
|
+
input = excluded.input,
|
|
500
|
+
retry_policy = excluded.retry_policy,
|
|
501
|
+
status = 'scheduled',
|
|
502
|
+
idempotency_key = excluded.idempotency_key,
|
|
503
|
+
not_before_ms = excluded.not_before_ms,
|
|
504
|
+
dispatched_at_ms = NULL,
|
|
505
|
+
dispatch_attempts = 0,
|
|
506
|
+
dispatch_claimed_until_ms = NULL,
|
|
507
|
+
lease_until_ms = NULL,
|
|
508
|
+
worker_id = NULL,
|
|
509
|
+
heartbeat_at_ms = NULL,
|
|
510
|
+
lease_ttl_ms = excluded.lease_ttl_ms,
|
|
511
|
+
timeout_ms = excluded.timeout_ms,
|
|
512
|
+
updated_at_ms = excluded.updated_at_ms
|
|
513
|
+
WHERE tasks.attempt < excluded.attempt`;
|
|
514
|
+
const RESCHEDULE_TASK = `
|
|
515
|
+
UPDATE tasks SET
|
|
516
|
+
status = ?, attempt = ?, not_before_ms = ?, updated_at_ms = ?,
|
|
517
|
+
dispatched_at_ms = NULL, dispatch_claimed_until_ms = NULL,
|
|
518
|
+
lease_until_ms = NULL, worker_id = NULL
|
|
519
|
+
WHERE task_id = ?`;
|
|
520
|
+
const CLOSE_TASK = `
|
|
521
|
+
UPDATE tasks SET
|
|
522
|
+
status = ?, attempt = ?, updated_at_ms = ?,
|
|
523
|
+
lease_until_ms = NULL, dispatch_claimed_until_ms = NULL
|
|
524
|
+
WHERE task_id = ?`;
|
|
525
|
+
const SET_TASK_STATUS = `
|
|
526
|
+
UPDATE tasks SET status = ?, attempt = ?, updated_at_ms = ? WHERE task_id = ?`;
|
|
527
|
+
const INSERT_TIMER = `
|
|
528
|
+
INSERT INTO timers (run_id, step_id, fire_at_ms) VALUES (?, ?, ?)
|
|
529
|
+
ON CONFLICT (run_id, step_id) DO NOTHING`;
|
|
530
|
+
const INSERT_SIGNAL_WAIT = `
|
|
531
|
+
INSERT INTO signal_waits (run_id, step_id, name, schema_ref, expires_at_ms)
|
|
532
|
+
VALUES (?, ?, ?, ?, ?)
|
|
533
|
+
ON CONFLICT (run_id, step_id) DO NOTHING`;
|
|
534
|
+
const UPDATE_RUN = `
|
|
535
|
+
UPDATE runs SET
|
|
536
|
+
status = ?,
|
|
537
|
+
last_seq = ?,
|
|
538
|
+
updated_at_ms = ?,
|
|
539
|
+
started_at_ms = COALESCE(started_at_ms, ?),
|
|
540
|
+
output = COALESCE(?, output),
|
|
541
|
+
output_ref = COALESCE(?, output_ref),
|
|
542
|
+
closed_at_ms = COALESCE(closed_at_ms, ?),
|
|
543
|
+
continued_to = COALESCE(?, continued_to)
|
|
544
|
+
WHERE run_id = ?`;
|
|
545
|
+
async function insertRun(x, row, nowMs) {
|
|
546
|
+
await x.run(INSERT_RUN, [
|
|
547
|
+
row.run_id,
|
|
548
|
+
row.namespace ?? "default",
|
|
549
|
+
row.workflow,
|
|
550
|
+
row.component_digest,
|
|
551
|
+
row.status,
|
|
552
|
+
orNull(row.parent_run_id),
|
|
553
|
+
orNull(row.parent_step_id),
|
|
554
|
+
orNull(row.continued_from),
|
|
555
|
+
orNull(row.input),
|
|
556
|
+
orNull(row.input_ref),
|
|
557
|
+
jsonParam(row.search ?? {}),
|
|
558
|
+
nowMs,
|
|
559
|
+
nowMs
|
|
560
|
+
]);
|
|
561
|
+
}
|
|
562
|
+
async function applyTransition(x, runId, t, opts) {
|
|
563
|
+
const now = opts.nowMs;
|
|
564
|
+
for (const event of t.events) await insertEvent(x, runId, event);
|
|
565
|
+
await upsertState(x, runId, t, opts);
|
|
566
|
+
for (const task of t.tasks) await upsertTask(x, runId, task, now);
|
|
567
|
+
for (const update of t.task_updates) await applyTaskUpdate(x, update, now);
|
|
568
|
+
for (const timer of t.timers) await insertTimer(x, runId, timer);
|
|
569
|
+
for (const wait of t.signal_waits) await insertSignalWait(x, runId, wait);
|
|
570
|
+
for (const child of opts.childRuns ?? []) await insertRun(x, child, now);
|
|
571
|
+
if (opts.successorRun !== void 0) await insertRun(x, opts.successorRun, now);
|
|
572
|
+
await updateRun(x, runId, t, opts);
|
|
573
|
+
}
|
|
574
|
+
async function insertEvent(x, runId, e) {
|
|
575
|
+
await x.run(INSERT_EVENT, [
|
|
576
|
+
runId,
|
|
577
|
+
e.seq,
|
|
578
|
+
e.step_id,
|
|
579
|
+
e.attempt,
|
|
580
|
+
e.kind,
|
|
581
|
+
e.status,
|
|
582
|
+
orNull(e.cause),
|
|
583
|
+
orNull(e.schema_ref),
|
|
584
|
+
orNull(e.payload),
|
|
585
|
+
orNull(e.payload_ref),
|
|
586
|
+
orNull(e.error),
|
|
587
|
+
e.usage ? jsonParam(e.usage) : null,
|
|
588
|
+
e.random,
|
|
589
|
+
e.state_hash,
|
|
590
|
+
orNull(e.parent_run_id),
|
|
591
|
+
orNull(e.parent_step_id),
|
|
592
|
+
e.ts_ms
|
|
593
|
+
]);
|
|
594
|
+
}
|
|
595
|
+
async function upsertState(x, runId, t, opts) {
|
|
596
|
+
const offloaded = opts.stateRef !== void 0;
|
|
597
|
+
await x.run(UPSERT_STATE, [
|
|
598
|
+
runId,
|
|
599
|
+
t.run.last_seq,
|
|
600
|
+
orNull(opts.bundleDigest),
|
|
601
|
+
runId,
|
|
602
|
+
jsonParam(t.kernel_state),
|
|
603
|
+
offloaded ? null : t.state,
|
|
604
|
+
orNull(opts.stateRef),
|
|
605
|
+
t.state_hash
|
|
606
|
+
]);
|
|
607
|
+
}
|
|
608
|
+
async function upsertTask(x, runId, task, nowMs) {
|
|
609
|
+
await x.run(UPSERT_TASK, [
|
|
610
|
+
task.task_id,
|
|
611
|
+
runId,
|
|
612
|
+
task.step_id,
|
|
613
|
+
task.attempt,
|
|
614
|
+
task.activity,
|
|
615
|
+
orNull(task.schema_ref),
|
|
616
|
+
task.queue,
|
|
617
|
+
jsonParam(task.input),
|
|
618
|
+
jsonParam(task.retry),
|
|
619
|
+
task.idempotency_key,
|
|
620
|
+
nowMs,
|
|
621
|
+
task.lease_ttl_ms,
|
|
622
|
+
orNull(task.timeout_ms),
|
|
623
|
+
nowMs,
|
|
624
|
+
nowMs
|
|
625
|
+
]);
|
|
626
|
+
}
|
|
627
|
+
async function applyTaskUpdate(x, u, nowMs) {
|
|
628
|
+
if (u.status === "scheduled" || u.status === "retrying") {
|
|
629
|
+
const notBefore = u.not_before_ms ?? nowMs;
|
|
630
|
+
await x.run(RESCHEDULE_TASK, [
|
|
631
|
+
u.status,
|
|
632
|
+
u.attempt,
|
|
633
|
+
notBefore,
|
|
634
|
+
nowMs,
|
|
635
|
+
u.task_id
|
|
636
|
+
]);
|
|
637
|
+
return;
|
|
638
|
+
}
|
|
639
|
+
const sql = TERMINAL_TASK_STATUS.has(u.status) ? CLOSE_TASK : SET_TASK_STATUS;
|
|
640
|
+
await x.run(sql, [
|
|
641
|
+
u.status,
|
|
642
|
+
u.attempt,
|
|
643
|
+
nowMs,
|
|
644
|
+
u.task_id
|
|
645
|
+
]);
|
|
646
|
+
}
|
|
647
|
+
async function insertTimer(x, runId, timer) {
|
|
648
|
+
await x.run(INSERT_TIMER, [
|
|
649
|
+
runId,
|
|
650
|
+
timer.step_id,
|
|
651
|
+
timer.fire_at_ms
|
|
652
|
+
]);
|
|
653
|
+
}
|
|
654
|
+
async function insertSignalWait(x, runId, wait) {
|
|
655
|
+
await x.run(INSERT_SIGNAL_WAIT, [
|
|
656
|
+
runId,
|
|
657
|
+
wait.step_id,
|
|
658
|
+
wait.name,
|
|
659
|
+
orNull(wait.schema_ref),
|
|
660
|
+
orNull(wait.expires_at_ms)
|
|
661
|
+
]);
|
|
662
|
+
}
|
|
663
|
+
async function updateRun(x, runId, t, opts) {
|
|
664
|
+
const status = t.run.status;
|
|
665
|
+
const closed = TERMINAL_RUN_STATUS.has(status);
|
|
666
|
+
const outputRef = opts.outputRef;
|
|
667
|
+
const inlineOutput = outputRef === void 0 && t.completion?.output !== void 0 ? jsonParam(t.completion.output) : null;
|
|
668
|
+
const params = [
|
|
669
|
+
status,
|
|
670
|
+
t.run.last_seq,
|
|
671
|
+
opts.nowMs,
|
|
672
|
+
status === "created" ? null : opts.nowMs,
|
|
673
|
+
inlineOutput,
|
|
674
|
+
orNull(outputRef),
|
|
675
|
+
closed ? opts.nowMs : null,
|
|
676
|
+
orNull(opts.successorRun?.run_id),
|
|
677
|
+
runId
|
|
678
|
+
];
|
|
679
|
+
await x.run(UPDATE_RUN, params);
|
|
680
|
+
}
|
|
681
|
+
// src/journal/tx.ts
|
|
682
|
+
const RUN_LOCK_PREFIX = "vlo:run:";
|
|
683
|
+
var JournalTransaction = class {
|
|
684
|
+
x;
|
|
685
|
+
d;
|
|
686
|
+
constructor(x, d) {
|
|
687
|
+
this.x = x;
|
|
688
|
+
this.d = d;
|
|
689
|
+
}
|
|
690
|
+
async lockRun(runId) {
|
|
691
|
+
await this.x.advisoryLock(RUN_LOCK_PREFIX + runId);
|
|
692
|
+
return getRun(this.x, runId);
|
|
693
|
+
}
|
|
694
|
+
async createRun(row, nowMs) {
|
|
695
|
+
await insertRun(this.x, row, nowMs);
|
|
696
|
+
}
|
|
697
|
+
getState(runId) {
|
|
698
|
+
return getState(this.x, runId);
|
|
699
|
+
}
|
|
700
|
+
readEvents(runId, sinceSeq) {
|
|
701
|
+
return readEvents(this.x, runId, sinceSeq);
|
|
702
|
+
}
|
|
703
|
+
applyTransition(runId, t, opts) {
|
|
704
|
+
return applyTransition(this.x, runId, t, opts);
|
|
705
|
+
}
|
|
706
|
+
async claimUndispatchedTasks(nowMs, limit, holdMs, filter) {
|
|
707
|
+
const clauses = [];
|
|
708
|
+
const params = [
|
|
709
|
+
nowMs + holdMs,
|
|
710
|
+
nowMs,
|
|
711
|
+
nowMs,
|
|
712
|
+
nowMs
|
|
713
|
+
];
|
|
714
|
+
if (filter?.queue !== void 0) {
|
|
715
|
+
clauses.push("AND queue = ?");
|
|
716
|
+
params.push(filter.queue);
|
|
717
|
+
}
|
|
718
|
+
const excluded = filter?.excludeQueues ?? [];
|
|
719
|
+
if (excluded.length > 0) {
|
|
720
|
+
clauses.push(`AND queue NOT IN (${excluded.map(() => "?").join(", ")})`);
|
|
721
|
+
params.push(...excluded);
|
|
722
|
+
}
|
|
723
|
+
params.push(limit);
|
|
724
|
+
return (await this.x.all(`UPDATE tasks SET
|
|
725
|
+
dispatch_claimed_until_ms = ?,
|
|
726
|
+
dispatch_attempts = dispatch_attempts + 1,
|
|
727
|
+
updated_at_ms = ?
|
|
728
|
+
WHERE task_id IN (
|
|
729
|
+
SELECT task_id FROM tasks
|
|
730
|
+
WHERE status = 'scheduled'
|
|
731
|
+
AND dispatched_at_ms IS NULL
|
|
732
|
+
AND not_before_ms <= ?
|
|
733
|
+
AND (dispatch_claimed_until_ms IS NULL OR dispatch_claimed_until_ms < ?)
|
|
734
|
+
${clauses.join("\n ")}
|
|
735
|
+
ORDER BY not_before_ms, created_at_ms, task_id
|
|
736
|
+
LIMIT ?${this.d.skipLocked}
|
|
737
|
+
)
|
|
738
|
+
RETURNING *`, params)).map(mapTask);
|
|
739
|
+
}
|
|
740
|
+
async markDispatched(taskId, attempt, nowMs, leaseUntilMs, workerId) {
|
|
741
|
+
return await this.x.run(`UPDATE tasks SET
|
|
742
|
+
status = 'running',
|
|
743
|
+
dispatched_at_ms = ?,
|
|
744
|
+
lease_until_ms = ?,
|
|
745
|
+
heartbeat_at_ms = ?,
|
|
746
|
+
worker_id = ?,
|
|
747
|
+
dispatch_claimed_until_ms = NULL,
|
|
748
|
+
updated_at_ms = ?
|
|
749
|
+
WHERE task_id = ? AND attempt = ?
|
|
750
|
+
AND (status = 'scheduled' OR (status = 'running' AND dispatched_at_ms IS NULL))`, [
|
|
751
|
+
nowMs,
|
|
752
|
+
leaseUntilMs,
|
|
753
|
+
nowMs,
|
|
754
|
+
orNull(workerId),
|
|
755
|
+
nowMs,
|
|
756
|
+
taskId,
|
|
757
|
+
attempt
|
|
758
|
+
]) > 0;
|
|
759
|
+
}
|
|
760
|
+
async deferDispatch(taskId, attempt, notBeforeMs) {
|
|
761
|
+
await this.x.run(`UPDATE tasks SET not_before_ms = ?, dispatch_claimed_until_ms = NULL
|
|
762
|
+
WHERE task_id = ? AND attempt = ?`, [
|
|
763
|
+
notBeforeMs,
|
|
764
|
+
taskId,
|
|
765
|
+
attempt
|
|
766
|
+
]);
|
|
767
|
+
}
|
|
768
|
+
async heartbeat(taskId, attempt, leaseUntilMs, nowMs) {
|
|
769
|
+
return await this.x.run(`UPDATE tasks SET lease_until_ms = ?, heartbeat_at_ms = ?, updated_at_ms = ?
|
|
770
|
+
WHERE task_id = ? AND attempt = ? AND status = 'running'`, [
|
|
771
|
+
leaseUntilMs,
|
|
772
|
+
nowMs,
|
|
773
|
+
nowMs,
|
|
774
|
+
taskId,
|
|
775
|
+
attempt
|
|
776
|
+
]) > 0;
|
|
777
|
+
}
|
|
778
|
+
async claimCreatedRuns(nowMs, limit, holdMs) {
|
|
779
|
+
return (await this.x.all(`UPDATE runs SET start_claimed_until_ms = ?, updated_at_ms = ?
|
|
780
|
+
WHERE run_id IN (
|
|
781
|
+
SELECT run_id FROM runs
|
|
782
|
+
WHERE status = 'created'
|
|
783
|
+
AND (start_claimed_until_ms IS NULL OR start_claimed_until_ms < ?)
|
|
784
|
+
ORDER BY created_at_ms, run_id
|
|
785
|
+
LIMIT ?${this.d.skipLocked}
|
|
786
|
+
)
|
|
787
|
+
RETURNING *`, [
|
|
788
|
+
nowMs + holdMs,
|
|
789
|
+
nowMs,
|
|
790
|
+
nowMs,
|
|
791
|
+
limit
|
|
792
|
+
])).map(mapRun);
|
|
793
|
+
}
|
|
794
|
+
async claimClosedUnnotified(nowMs, limit, holdMs) {
|
|
795
|
+
return (await this.x.all(`UPDATE runs SET notify_claimed_until_ms = ?, updated_at_ms = ?
|
|
796
|
+
WHERE run_id IN (
|
|
797
|
+
SELECT run_id FROM runs
|
|
798
|
+
WHERE parent_run_id IS NOT NULL
|
|
799
|
+
AND parent_notified_at_ms IS NULL
|
|
800
|
+
AND closed_at_ms IS NOT NULL
|
|
801
|
+
AND (notify_claimed_until_ms IS NULL OR notify_claimed_until_ms < ?)
|
|
802
|
+
ORDER BY closed_at_ms, run_id
|
|
803
|
+
LIMIT ?${this.d.skipLocked}
|
|
804
|
+
)
|
|
805
|
+
RETURNING *`, [
|
|
806
|
+
nowMs + holdMs,
|
|
807
|
+
nowMs,
|
|
808
|
+
nowMs,
|
|
809
|
+
limit
|
|
810
|
+
])).map(mapRun);
|
|
811
|
+
}
|
|
812
|
+
async markParentNotified(runId, nowMs) {
|
|
813
|
+
await this.x.run(`UPDATE runs SET parent_notified_at_ms = ?, updated_at_ms = ?
|
|
814
|
+
WHERE run_id = ? AND parent_notified_at_ms IS NULL`, [
|
|
815
|
+
nowMs,
|
|
816
|
+
nowMs,
|
|
817
|
+
runId
|
|
818
|
+
]);
|
|
819
|
+
}
|
|
820
|
+
async claimDueTimers(nowMs, limit, holdMs) {
|
|
821
|
+
return (await this.x.all(`UPDATE timers SET claimed_until_ms = ?
|
|
822
|
+
WHERE (run_id, step_id) IN (
|
|
823
|
+
SELECT run_id, step_id FROM timers
|
|
824
|
+
WHERE fired_at_ms IS NULL
|
|
825
|
+
AND fire_at_ms <= ?
|
|
826
|
+
AND (claimed_until_ms IS NULL OR claimed_until_ms < ?)
|
|
827
|
+
ORDER BY fire_at_ms, run_id, step_id
|
|
828
|
+
LIMIT ?${this.d.skipLocked}
|
|
829
|
+
)
|
|
830
|
+
RETURNING *`, [
|
|
831
|
+
nowMs + holdMs,
|
|
832
|
+
nowMs,
|
|
833
|
+
nowMs,
|
|
834
|
+
limit
|
|
835
|
+
])).map(mapTimer);
|
|
836
|
+
}
|
|
837
|
+
async markTimerFired(runId, stepId, nowMs) {
|
|
838
|
+
return await this.x.run("UPDATE timers SET fired_at_ms = ? WHERE run_id = ? AND step_id = ? AND fired_at_ms IS NULL", [
|
|
839
|
+
nowMs,
|
|
840
|
+
runId,
|
|
841
|
+
stepId
|
|
842
|
+
]) > 0;
|
|
843
|
+
}
|
|
844
|
+
async putSignal(row, nowMs) {
|
|
845
|
+
await this.x.run(`INSERT INTO signals (signal_id, run_id, name, payload, payload_ref, sender, created_at_ms)
|
|
846
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
847
|
+
ON CONFLICT (signal_id) DO NOTHING`, [
|
|
848
|
+
row.signal_id,
|
|
849
|
+
row.run_id,
|
|
850
|
+
row.name,
|
|
851
|
+
orNull(row.payload),
|
|
852
|
+
orNull(row.payload_ref),
|
|
853
|
+
orNull(row.sender),
|
|
854
|
+
nowMs
|
|
855
|
+
]);
|
|
856
|
+
}
|
|
857
|
+
async takeSignal(runId, name) {
|
|
858
|
+
const row = await one(this.x, `SELECT * FROM signals
|
|
859
|
+
WHERE run_id = ? AND name = ? AND delivered_at_ms IS NULL
|
|
860
|
+
ORDER BY created_at_ms, signal_id
|
|
861
|
+
LIMIT 1${this.d.skipLocked}`, [runId, name]);
|
|
862
|
+
return row ? mapSignal(row) : null;
|
|
863
|
+
}
|
|
864
|
+
async markSignalDelivered(signalId, stepId, nowMs) {
|
|
865
|
+
await this.x.run(`UPDATE signals SET delivered_at_ms = ?, delivered_step_id = ?
|
|
866
|
+
WHERE signal_id = ? AND delivered_at_ms IS NULL`, [
|
|
867
|
+
nowMs,
|
|
868
|
+
stepId,
|
|
869
|
+
signalId
|
|
870
|
+
]);
|
|
871
|
+
}
|
|
872
|
+
async getSignalWaits(runId) {
|
|
873
|
+
return (await this.x.all("SELECT * FROM signal_waits WHERE run_id = ? ORDER BY step_id", [runId])).map(mapSignalWait);
|
|
874
|
+
}
|
|
875
|
+
async removeSignalWait(runId, stepId) {
|
|
876
|
+
await this.x.run("DELETE FROM signal_waits WHERE run_id = ? AND step_id = ?", [runId, stepId]);
|
|
877
|
+
}
|
|
878
|
+
async upsertSchema(row, nowMs) {
|
|
879
|
+
await this.x.run(`INSERT INTO schemas (name, version, json_schema, retry_policy, created_at_ms)
|
|
880
|
+
VALUES (?, ?, ?, ?, ?)
|
|
881
|
+
ON CONFLICT (name, version) DO UPDATE SET
|
|
882
|
+
json_schema = excluded.json_schema,
|
|
883
|
+
retry_policy = excluded.retry_policy`, [
|
|
884
|
+
row.name,
|
|
885
|
+
row.version,
|
|
886
|
+
row.json_schema,
|
|
887
|
+
orNull(row.retry_policy),
|
|
888
|
+
nowMs
|
|
889
|
+
]);
|
|
890
|
+
}
|
|
891
|
+
async getSchema(name, version) {
|
|
892
|
+
const row = await one(this.x, "SELECT * FROM schemas WHERE name = ? AND version = ?", [name, version]);
|
|
893
|
+
return row ? mapSchema(row) : null;
|
|
894
|
+
}
|
|
895
|
+
};
|
|
896
|
+
// src/journal/types.ts
|
|
897
|
+
/**
|
|
898
|
+
* Thrown by every journal call made after `close()`.
|
|
899
|
+
*
|
|
900
|
+
* Shutdown is inherently racy: a worker reporting a result, a stage finishing its pass. The
|
|
901
|
+
* contract is that those calls fail with this, one recognisable error, instead of whatever
|
|
902
|
+
* the driver does to a closed handle — `node:sqlite` raises `ERR_INVALID_STATE` from a
|
|
903
|
+
* finalized statement, which surfaces as a crash rather than as "the host is stopping".
|
|
904
|
+
*/
|
|
905
|
+
var JournalClosed = class extends Error {
|
|
906
|
+
/** Always `journal_closed`. */
|
|
907
|
+
code = "journal_closed";
|
|
908
|
+
/** `dialect` names the implementation, e.g. `sqlite` or `postgres`. */
|
|
909
|
+
constructor(dialect) {
|
|
910
|
+
super(`vlo journal: the ${dialect} journal is closed`);
|
|
911
|
+
this.name = "JournalClosed";
|
|
912
|
+
}
|
|
913
|
+
};
|
|
914
|
+
// src/journal/postgres.ts
|
|
915
|
+
/**
|
|
916
|
+
* The Postgres journal.
|
|
917
|
+
*
|
|
918
|
+
* Every statement runs inside a transaction whose `search_path` is pinned with
|
|
919
|
+
* `SET LOCAL` to the journal's own schema (`vlo` by default, or a throwaway schema in
|
|
920
|
+
* tests), so the shared SQL can name tables unqualified and nothing can reach `public`.
|
|
921
|
+
* Nothing is session state: no startup `options`, no session-level `SET`, no
|
|
922
|
+
* session-level advisory locks — so the journal works behind transaction-mode poolers
|
|
923
|
+
* (PgBouncer, PlanetScale, Neon), which reject startup parameters and multiplex
|
|
924
|
+
* sessions. Per-run serialisation is a transaction-scoped advisory lock; claims use
|
|
925
|
+
* `FOR UPDATE SKIP LOCKED`.
|
|
926
|
+
*/
|
|
927
|
+
const { Pool } = pg;
|
|
928
|
+
const MIGRATE_LOCK = "vlo:migrate";
|
|
929
|
+
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
930
|
+
const rewritten = /* @__PURE__ */ new Map();
|
|
931
|
+
/** Shared SQL is written with `?`; Postgres wants `$n`. */
|
|
932
|
+
function toPgSql(sql) {
|
|
933
|
+
const hit = rewritten.get(sql);
|
|
934
|
+
if (hit !== void 0) return hit;
|
|
935
|
+
let index = 0;
|
|
936
|
+
const out = sql.replace(/\?/g, () => `$${++index}`);
|
|
937
|
+
rewritten.set(sql, out);
|
|
938
|
+
return out;
|
|
939
|
+
}
|
|
940
|
+
var PgExecutor = class {
|
|
941
|
+
q;
|
|
942
|
+
constructor(q) {
|
|
943
|
+
this.q = q;
|
|
944
|
+
}
|
|
945
|
+
async all(sql, params = []) {
|
|
946
|
+
return (await this.q.query(toPgSql(sql), params)).rows;
|
|
947
|
+
}
|
|
948
|
+
async run(sql, params = []) {
|
|
949
|
+
return (await this.q.query(toPgSql(sql), params)).rowCount ?? 0;
|
|
950
|
+
}
|
|
951
|
+
async exec(sql) {
|
|
952
|
+
await this.q.query(sql);
|
|
953
|
+
}
|
|
954
|
+
async advisoryLock(key) {
|
|
955
|
+
await this.q.query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", [key]);
|
|
956
|
+
}
|
|
957
|
+
};
|
|
958
|
+
/** The Postgres {@link Journal}. Opened by `openJournal("postgres://…")`. */
|
|
959
|
+
var PostgresJournal = class {
|
|
960
|
+
pool;
|
|
961
|
+
schema;
|
|
962
|
+
executor;
|
|
963
|
+
closed = false;
|
|
964
|
+
/** Creates the pool; no connection is made until the first call. Throws on a schema name that is not a plain identifier. */
|
|
965
|
+
constructor(url, opts = {}) {
|
|
966
|
+
this.schema = assertIdentifier(opts.schema ?? "vlo");
|
|
967
|
+
this.pool = new Pool({
|
|
968
|
+
connectionString: url,
|
|
969
|
+
...opts.max !== void 0 ? { max: opts.max } : {}
|
|
970
|
+
});
|
|
971
|
+
this.executor = new PgExecutor({ query: (text, values) => this.inPinnedTransaction((client) => client.query(text, values)) });
|
|
972
|
+
}
|
|
973
|
+
/** Runs `fn` on one connection inside `BEGIN … COMMIT` with `search_path` set locally. */
|
|
974
|
+
async inPinnedTransaction(fn) {
|
|
975
|
+
this.assertOpen();
|
|
976
|
+
const client = await this.pool.connect();
|
|
977
|
+
try {
|
|
978
|
+
await client.query("BEGIN");
|
|
979
|
+
await client.query(`SET LOCAL search_path TO ${this.schema}`);
|
|
980
|
+
const result = await fn(client);
|
|
981
|
+
await client.query("COMMIT");
|
|
982
|
+
return result;
|
|
983
|
+
} catch (error) {
|
|
984
|
+
await client.query("ROLLBACK").catch(() => void 0);
|
|
985
|
+
throw error;
|
|
986
|
+
} finally {
|
|
987
|
+
client.release();
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
async migrate() {
|
|
991
|
+
this.assertOpen();
|
|
992
|
+
const client = await this.pool.connect();
|
|
993
|
+
try {
|
|
994
|
+
await client.query("BEGIN");
|
|
995
|
+
await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", [MIGRATE_LOCK]);
|
|
996
|
+
if ((await client.query("SELECT 1 FROM pg_namespace WHERE nspname = $1", [this.schema])).rowCount === 0) await client.query(`CREATE SCHEMA ${this.schema}`);
|
|
997
|
+
await client.query("COMMIT");
|
|
998
|
+
await client.query("BEGIN");
|
|
999
|
+
await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", [MIGRATE_LOCK]);
|
|
1000
|
+
await client.query(`SET LOCAL search_path TO ${this.schema}`);
|
|
1001
|
+
const executor = new PgExecutor(client);
|
|
1002
|
+
await applyMigrations(executor, "pg", () => this.hasMigrationsTable(executor), Date.now());
|
|
1003
|
+
await client.query("COMMIT");
|
|
1004
|
+
} catch (error) {
|
|
1005
|
+
await client.query("ROLLBACK").catch(() => void 0);
|
|
1006
|
+
throw error;
|
|
1007
|
+
} finally {
|
|
1008
|
+
client.release();
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
transaction(fn) {
|
|
1012
|
+
return this.inPinnedTransaction((client) => fn(new JournalTransaction(new PgExecutor(client), PG)));
|
|
1013
|
+
}
|
|
1014
|
+
readEvents(runId, sinceSeq) {
|
|
1015
|
+
return readEvents(this.executor, runId, sinceSeq);
|
|
1016
|
+
}
|
|
1017
|
+
getRun(runId) {
|
|
1018
|
+
return getRun(this.executor, runId);
|
|
1019
|
+
}
|
|
1020
|
+
getState(runId) {
|
|
1021
|
+
return getState(this.executor, runId);
|
|
1022
|
+
}
|
|
1023
|
+
getTask(taskId) {
|
|
1024
|
+
return getTask(this.executor, taskId);
|
|
1025
|
+
}
|
|
1026
|
+
listTasks(runId) {
|
|
1027
|
+
return listTasks(this.executor, runId);
|
|
1028
|
+
}
|
|
1029
|
+
query(q) {
|
|
1030
|
+
return queryRuns(this.executor, q);
|
|
1031
|
+
}
|
|
1032
|
+
dueTimers(nowMs, limit) {
|
|
1033
|
+
return dueTimers(this.executor, nowMs, limit);
|
|
1034
|
+
}
|
|
1035
|
+
expiredLeases(nowMs, limit) {
|
|
1036
|
+
return expiredLeases(this.executor, nowMs, limit);
|
|
1037
|
+
}
|
|
1038
|
+
expiredTimeouts(nowMs, limit) {
|
|
1039
|
+
return expiredTimeouts(this.executor, nowMs, limit);
|
|
1040
|
+
}
|
|
1041
|
+
/** Idempotent. */
|
|
1042
|
+
async close() {
|
|
1043
|
+
if (this.closed) return;
|
|
1044
|
+
this.closed = true;
|
|
1045
|
+
await this.pool.end();
|
|
1046
|
+
}
|
|
1047
|
+
assertOpen() {
|
|
1048
|
+
if (this.closed) throw new JournalClosed("postgres");
|
|
1049
|
+
}
|
|
1050
|
+
async hasMigrationsTable(x) {
|
|
1051
|
+
return (await x.all("SELECT to_regclass(CAST(? AS text)) IS NOT NULL AS present", [`${this.schema}.migrations`]))[0]?.present === true;
|
|
1052
|
+
}
|
|
1053
|
+
};
|
|
1054
|
+
function assertIdentifier(name) {
|
|
1055
|
+
if (!IDENTIFIER.test(name)) throw new Error(`invalid journal schema name: ${name}`);
|
|
1056
|
+
return name;
|
|
1057
|
+
}
|
|
1058
|
+
// src/journal/sqlite.ts
|
|
1059
|
+
/**
|
|
1060
|
+
* The SQLite journal: one file, one connection, `node:sqlite`.
|
|
1061
|
+
*
|
|
1062
|
+
* `node:sqlite` is synchronous while the `Journal` API is not, so a promise
|
|
1063
|
+
* mutex owns the connection: a transaction holds it from `BEGIN IMMEDIATE`
|
|
1064
|
+
* until `COMMIT`, and reads queue behind it. `BEGIN IMMEDIATE` takes SQLite's
|
|
1065
|
+
* write lock up front, which is what makes claims disjoint without
|
|
1066
|
+
* `SKIP LOCKED`.
|
|
1067
|
+
*/
|
|
1068
|
+
/**
|
|
1069
|
+
* `node:sqlite` prints an ExperimentalWarning the moment it is imported, so it is loaded
|
|
1070
|
+
* only when a SQLite journal is actually opened; a Postgres host never touches it.
|
|
1071
|
+
*/
|
|
1072
|
+
function loadSqlite() {
|
|
1073
|
+
return createRequire(import.meta.url)("node:sqlite");
|
|
1074
|
+
}
|
|
1075
|
+
/** Serialises access to the one synchronous connection. */
|
|
1076
|
+
var Mutex = class {
|
|
1077
|
+
tail = Promise.resolve();
|
|
1078
|
+
run(fn) {
|
|
1079
|
+
const result = this.tail.then(fn);
|
|
1080
|
+
this.tail = result.catch(() => void 0);
|
|
1081
|
+
return result;
|
|
1082
|
+
}
|
|
1083
|
+
};
|
|
1084
|
+
var SqliteExecutor = class {
|
|
1085
|
+
db;
|
|
1086
|
+
statements = /* @__PURE__ */ new Map();
|
|
1087
|
+
constructor(db) {
|
|
1088
|
+
this.db = db;
|
|
1089
|
+
}
|
|
1090
|
+
async all(sql, params = []) {
|
|
1091
|
+
return this.prepare(sql).all(...params);
|
|
1092
|
+
}
|
|
1093
|
+
async run(sql, params = []) {
|
|
1094
|
+
return Number(this.prepare(sql).run(...params).changes);
|
|
1095
|
+
}
|
|
1096
|
+
async exec(sql) {
|
|
1097
|
+
this.db.exec(sql);
|
|
1098
|
+
}
|
|
1099
|
+
/** No-op: `BEGIN IMMEDIATE` already holds the database's single write lock. */
|
|
1100
|
+
async advisoryLock() {}
|
|
1101
|
+
prepare(sql) {
|
|
1102
|
+
const hit = this.statements.get(sql);
|
|
1103
|
+
if (hit !== void 0) return hit;
|
|
1104
|
+
const statement = this.db.prepare(sql);
|
|
1105
|
+
this.statements.set(sql, statement);
|
|
1106
|
+
return statement;
|
|
1107
|
+
}
|
|
1108
|
+
};
|
|
1109
|
+
/** The SQLite {@link Journal}. Opened by `openJournal("sqlite://…")`. */
|
|
1110
|
+
var SqliteJournal = class {
|
|
1111
|
+
db;
|
|
1112
|
+
executor;
|
|
1113
|
+
mutex = new Mutex();
|
|
1114
|
+
/** Every statement in the executor's cache is finalized once the connection closes. */
|
|
1115
|
+
closed = false;
|
|
1116
|
+
/** Opens `location` (a path, or `:memory:`) in WAL mode, creating the parent directory. */
|
|
1117
|
+
constructor(location) {
|
|
1118
|
+
if (location !== ":memory:") mkdirSync(dirname(location), { recursive: true });
|
|
1119
|
+
this.db = new (loadSqlite()).DatabaseSync(location);
|
|
1120
|
+
this.db.exec("PRAGMA journal_mode = WAL");
|
|
1121
|
+
this.db.exec("PRAGMA busy_timeout = 5000");
|
|
1122
|
+
this.db.exec("PRAGMA foreign_keys = ON");
|
|
1123
|
+
this.executor = new SqliteExecutor(this.db);
|
|
1124
|
+
}
|
|
1125
|
+
async migrate() {
|
|
1126
|
+
await this.inTransaction(async () => {
|
|
1127
|
+
await applyMigrations(this.executor, "sqlite", () => this.hasMigrationsTable(), Date.now());
|
|
1128
|
+
});
|
|
1129
|
+
}
|
|
1130
|
+
transaction(fn) {
|
|
1131
|
+
return this.inTransaction(() => fn(new JournalTransaction(this.executor, SQLITE)));
|
|
1132
|
+
}
|
|
1133
|
+
readEvents(runId, sinceSeq) {
|
|
1134
|
+
return this.read(() => readEvents(this.executor, runId, sinceSeq));
|
|
1135
|
+
}
|
|
1136
|
+
getRun(runId) {
|
|
1137
|
+
return this.read(() => getRun(this.executor, runId));
|
|
1138
|
+
}
|
|
1139
|
+
getState(runId) {
|
|
1140
|
+
return this.read(() => getState(this.executor, runId));
|
|
1141
|
+
}
|
|
1142
|
+
getTask(taskId) {
|
|
1143
|
+
return this.read(() => getTask(this.executor, taskId));
|
|
1144
|
+
}
|
|
1145
|
+
listTasks(runId) {
|
|
1146
|
+
return this.read(() => listTasks(this.executor, runId));
|
|
1147
|
+
}
|
|
1148
|
+
query(q) {
|
|
1149
|
+
return this.read(() => queryRuns(this.executor, q));
|
|
1150
|
+
}
|
|
1151
|
+
dueTimers(nowMs, limit) {
|
|
1152
|
+
return this.read(() => dueTimers(this.executor, nowMs, limit));
|
|
1153
|
+
}
|
|
1154
|
+
expiredLeases(nowMs, limit) {
|
|
1155
|
+
return this.read(() => expiredLeases(this.executor, nowMs, limit));
|
|
1156
|
+
}
|
|
1157
|
+
expiredTimeouts(nowMs, limit) {
|
|
1158
|
+
return this.read(() => expiredTimeouts(this.executor, nowMs, limit));
|
|
1159
|
+
}
|
|
1160
|
+
/** Idempotent. Work queued before it still runs; anything after gets `JournalClosed`. */
|
|
1161
|
+
async close() {
|
|
1162
|
+
await this.mutex.run(async () => {
|
|
1163
|
+
if (this.closed) return;
|
|
1164
|
+
this.closed = true;
|
|
1165
|
+
this.db.close();
|
|
1166
|
+
});
|
|
1167
|
+
}
|
|
1168
|
+
read(fn) {
|
|
1169
|
+
return this.mutex.run(async () => {
|
|
1170
|
+
this.assertOpen();
|
|
1171
|
+
return fn();
|
|
1172
|
+
});
|
|
1173
|
+
}
|
|
1174
|
+
inTransaction(fn) {
|
|
1175
|
+
return this.mutex.run(async () => {
|
|
1176
|
+
this.assertOpen();
|
|
1177
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
1178
|
+
try {
|
|
1179
|
+
const result = await fn();
|
|
1180
|
+
this.db.exec("COMMIT");
|
|
1181
|
+
return result;
|
|
1182
|
+
} catch (error) {
|
|
1183
|
+
try {
|
|
1184
|
+
this.db.exec("ROLLBACK");
|
|
1185
|
+
} catch {}
|
|
1186
|
+
throw error;
|
|
1187
|
+
}
|
|
1188
|
+
});
|
|
1189
|
+
}
|
|
1190
|
+
assertOpen() {
|
|
1191
|
+
if (this.closed) throw new JournalClosed("sqlite");
|
|
1192
|
+
}
|
|
1193
|
+
async hasMigrationsTable() {
|
|
1194
|
+
return (await this.executor.all("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'migrations'")).length > 0;
|
|
1195
|
+
}
|
|
1196
|
+
};
|
|
1197
|
+
// src/journal/open.ts
|
|
1198
|
+
/** Journal selection by URL scheme. */
|
|
1199
|
+
const SQLITE_PREFIX = "sqlite://";
|
|
1200
|
+
/**
|
|
1201
|
+
* Opens a journal by URL: `sqlite://:memory:`, `sqlite://./.vlo/dev.db`,
|
|
1202
|
+
* `sqlite:///abs/path.db`, `postgres://…` or `postgresql://…`. Nothing is created or
|
|
1203
|
+
* migrated until `migrate()`. Throws a plain `Error` on any other scheme.
|
|
1204
|
+
*
|
|
1205
|
+
* @example
|
|
1206
|
+
* ```ts
|
|
1207
|
+
* import { openJournal } from "@oona/vlo/host";
|
|
1208
|
+
*
|
|
1209
|
+
* const journal = openJournal("postgres://user:pass@localhost/app", { schema: "vlo", max: 5 });
|
|
1210
|
+
* await journal.migrate();
|
|
1211
|
+
* const run = await journal.getRun("run_1");
|
|
1212
|
+
* await journal.close();
|
|
1213
|
+
* ```
|
|
1214
|
+
*/
|
|
1215
|
+
function openJournal(url, opts = {}) {
|
|
1216
|
+
if (url.startsWith(SQLITE_PREFIX)) return new SqliteJournal(sqliteLocation(url));
|
|
1217
|
+
if (url.startsWith("postgres://") || url.startsWith("postgresql://")) return new PostgresJournal(url, opts);
|
|
1218
|
+
throw new Error(`unsupported journal url: ${url}`);
|
|
1219
|
+
}
|
|
1220
|
+
function sqliteLocation(url) {
|
|
1221
|
+
const location = url.slice(9);
|
|
1222
|
+
if (location.length === 0) throw new Error(`sqlite journal url has no path: ${url}`);
|
|
1223
|
+
return location;
|
|
1224
|
+
}
|
|
1225
|
+
// src/kernel/protocol.ts
|
|
1226
|
+
const INLINE_LIMIT_BYTES = 262144;
|
|
1227
|
+
const START_STEP_ID = "start";
|
|
1228
|
+
/** Marker step ids the host writes to end a run without calling the reducer. */
|
|
1229
|
+
const CANCEL_STEP_ID = "cancel";
|
|
1230
|
+
const FAIL_STEP_ID = "fail";
|
|
1231
|
+
const NONDETERMINISM_STEP_ID = "nondeterminism";
|
|
1232
|
+
const CONTINUE_STEP_ID = "continue";
|
|
1233
|
+
// src/kernel/load.ts
|
|
1234
|
+
/**
|
|
1235
|
+
* Loads the Rust kernel compiled to wasm and adapts it to the `Kernel` interface.
|
|
1236
|
+
*
|
|
1237
|
+
* The wasm exports are JSON string in, JSON string out, so every method here is a
|
|
1238
|
+
* stringify / call / parse. Instantiation is synchronous (`initSync` over bytes read
|
|
1239
|
+
* from disk) and memoised: the kernel is stateless, so one instance serves the process.
|
|
1240
|
+
*/
|
|
1241
|
+
/**
|
|
1242
|
+
* `wasm/` sits next to `src/` in the repo and next to `dist/` in the published package,
|
|
1243
|
+
* so the bytes are one of two places relative to this module. `VLO_KERNEL_WASM` overrides
|
|
1244
|
+
* both; CI uses it to run the golden fixtures against a freshly built kernel.
|
|
1245
|
+
*/
|
|
1246
|
+
const WASM_CANDIDATES = ["../../wasm/vlo_kernel_bg.wasm", "../wasm/vlo_kernel_bg.wasm"];
|
|
1247
|
+
let loading;
|
|
1248
|
+
/**
|
|
1249
|
+
* Loads the wasm kernel once per process and returns the same instance afterwards. Looks for
|
|
1250
|
+
* `vlo_kernel_bg.wasm` in the package's `wasm/` directory, or at `VLO_KERNEL_WASM`. Rejects
|
|
1251
|
+
* when the bytes are missing or the kernel speaks a different protocol version.
|
|
1252
|
+
*/
|
|
1253
|
+
async function loadKernel() {
|
|
1254
|
+
loading ??= instantiate();
|
|
1255
|
+
return loading;
|
|
1256
|
+
}
|
|
1257
|
+
function readWasmBytes() {
|
|
1258
|
+
const override = process.env["VLO_KERNEL_WASM"];
|
|
1259
|
+
if (override !== void 0 && override !== "") return readFileSync(override);
|
|
1260
|
+
const failures = [];
|
|
1261
|
+
for (const candidate of WASM_CANDIDATES) try {
|
|
1262
|
+
return readFileSync(new URL(candidate, import.meta.url));
|
|
1263
|
+
} catch (error) {
|
|
1264
|
+
failures.push(`${candidate}: ${error.message}`);
|
|
1265
|
+
}
|
|
1266
|
+
throw new Error(`vlo kernel wasm not found; run scripts/build-kernel.sh\n${failures.join("\n")}`);
|
|
1267
|
+
}
|
|
1268
|
+
async function instantiate() {
|
|
1269
|
+
const wasm = await import("./vlo_kernel-CtzHHfHA.js");
|
|
1270
|
+
wasm.initSync({ module: readWasmBytes() });
|
|
1271
|
+
const call = (exported, input) => JSON.parse(exported(JSON.stringify(input)));
|
|
1272
|
+
const version = unwrap$1(JSON.parse(wasm.kernel_version()));
|
|
1273
|
+
if (version.protocol !== 1) throw new Error(`vlo kernel speaks protocol ${version.protocol}, this SDK speaks 1`);
|
|
1274
|
+
return {
|
|
1275
|
+
version: () => version,
|
|
1276
|
+
validateEvent: (event) => call(wasm.validate_event, event),
|
|
1277
|
+
prepareEvent: (input) => call(wasm.prepare_event, input),
|
|
1278
|
+
reduceStep: (input) => call(wasm.reduce_step, input),
|
|
1279
|
+
stateHash: (input) => call(wasm.compute_state_hash, input),
|
|
1280
|
+
planRetry: (input) => call(wasm.plan_retry, input),
|
|
1281
|
+
refoldCheck: (input) => call(wasm.refold_check, input),
|
|
1282
|
+
deriveIds: (input) => call(wasm.derive_ids, input)
|
|
1283
|
+
};
|
|
1284
|
+
}
|
|
1285
|
+
function unwrap$1(result) {
|
|
1286
|
+
if (!result.ok) throw new Error(`vlo kernel: ${result.error.code}: ${result.error.message}`);
|
|
1287
|
+
return result.value;
|
|
1288
|
+
}
|
|
1289
|
+
// src/host/errors.ts
|
|
1290
|
+
/**
|
|
1291
|
+
* Base of every error the host maps to an HTTP response. The router turns one into
|
|
1292
|
+
* `{ error: { code, message } }` with `status`; anything else is a 500 `internal`.
|
|
1293
|
+
*/
|
|
1294
|
+
var VloError = class extends Error {
|
|
1295
|
+
/** HTTP status the router answers with. */
|
|
1296
|
+
status;
|
|
1297
|
+
/** Stable machine-readable code, e.g. `run_not_found`. */
|
|
1298
|
+
code;
|
|
1299
|
+
/** `name` is set to the concrete subclass name. */
|
|
1300
|
+
constructor(code, message, status) {
|
|
1301
|
+
super(message);
|
|
1302
|
+
this.name = new.target.name;
|
|
1303
|
+
this.code = code;
|
|
1304
|
+
this.status = status;
|
|
1305
|
+
}
|
|
1306
|
+
};
|
|
1307
|
+
/** No run with that id. `run_not_found`, 404. */
|
|
1308
|
+
var RunNotFound = class extends VloError {
|
|
1309
|
+
runId;
|
|
1310
|
+
/** @param runId The id that was looked up; kept on the error. */
|
|
1311
|
+
constructor(runId) {
|
|
1312
|
+
super("run_not_found", `no run "${runId}"`, 404);
|
|
1313
|
+
this.runId = runId;
|
|
1314
|
+
}
|
|
1315
|
+
};
|
|
1316
|
+
/** No task with that id. `task_not_found`, 404. */
|
|
1317
|
+
var TaskNotFound = class extends VloError {
|
|
1318
|
+
taskId;
|
|
1319
|
+
/** @param taskId The id that was looked up; kept on the error. */
|
|
1320
|
+
constructor(taskId) {
|
|
1321
|
+
super("task_not_found", `no task "${taskId}"`, 404);
|
|
1322
|
+
this.taskId = taskId;
|
|
1323
|
+
}
|
|
1324
|
+
};
|
|
1325
|
+
/**
|
|
1326
|
+
* The run already ended, so a non-task event (a signal, say) cannot be applied.
|
|
1327
|
+
* `run_terminal`, 409. A late task result on an ended run is a duplicate, not this.
|
|
1328
|
+
*/
|
|
1329
|
+
var RunTerminal = class extends VloError {
|
|
1330
|
+
/** `status` is the terminal status the run is in. */
|
|
1331
|
+
constructor(runId, status) {
|
|
1332
|
+
super("run_terminal", `run "${runId}" is ${status}; no further events are accepted`, 409);
|
|
1333
|
+
}
|
|
1334
|
+
};
|
|
1335
|
+
/** The kernel refused the event: a duplicate, a stale attempt or an illegal transition. */
|
|
1336
|
+
var IllegalEvent = class extends VloError {
|
|
1337
|
+
/** The kernel's refusal, verbatim. Its `code` becomes this error's `code`. */
|
|
1338
|
+
kernelError;
|
|
1339
|
+
/** Code is the kernel's (`unknown_step`, `bad_seq`, `illegal_transition`, …), status 409. */
|
|
1340
|
+
constructor(error) {
|
|
1341
|
+
super(error.code, error.message, 409);
|
|
1342
|
+
this.kernelError = error;
|
|
1343
|
+
}
|
|
1344
|
+
};
|
|
1345
|
+
/**
|
|
1346
|
+
* The checkpoint or the re-fold disagreed with the journal. The run is failed first: the
|
|
1347
|
+
* `nondeterminism` marker it records carries `cause: "nondeterminism_detected"`, which is the
|
|
1348
|
+
* kernel's `Cause` value and stays as it is. This error's own code is `refold_mismatch`.
|
|
1349
|
+
*/
|
|
1350
|
+
var Nondeterminism = class extends VloError {
|
|
1351
|
+
runId;
|
|
1352
|
+
seq;
|
|
1353
|
+
/** `refold_mismatch`, 409. */
|
|
1354
|
+
constructor(runId, seq, detail) {
|
|
1355
|
+
super("refold_mismatch", `run "${runId}" diverged at seq ${seq}: ${detail}`, 409);
|
|
1356
|
+
this.runId = runId;
|
|
1357
|
+
this.seq = seq;
|
|
1358
|
+
}
|
|
1359
|
+
};
|
|
1360
|
+
/**
|
|
1361
|
+
* The reducer threw, or the host could not honour what it asked for. `applyEvent` swallows
|
|
1362
|
+
* this and records a `fail` marker with `cause: "app_error"` (the kernel's `Cause` value; this
|
|
1363
|
+
* error's own code is `reducer_failed`). Also raised when a `spawn` or `continue_as_new`
|
|
1364
|
+
* names a workflow this host has not registered.
|
|
1365
|
+
*/
|
|
1366
|
+
var ReducerFailed = class extends VloError {
|
|
1367
|
+
runId;
|
|
1368
|
+
trigger;
|
|
1369
|
+
/** The reducer's own message, without the folding context; journaled as the `fail` marker's `error`. */
|
|
1370
|
+
reason;
|
|
1371
|
+
/** `reducer_failed`, 409. Callers of `applyEvent` never see it; the run is failed instead. */
|
|
1372
|
+
constructor(runId, message, trigger, reason) {
|
|
1373
|
+
super("reducer_failed", message, 409);
|
|
1374
|
+
this.runId = runId;
|
|
1375
|
+
this.trigger = trigger;
|
|
1376
|
+
this.reason = reason ?? message;
|
|
1377
|
+
}
|
|
1378
|
+
};
|
|
1379
|
+
/** Kernel refusals that mean the step an event named is no longer open. */
|
|
1380
|
+
const STEP_GONE = /* @__PURE__ */ new Set([
|
|
1381
|
+
"unknown_step",
|
|
1382
|
+
"illegal_transition",
|
|
1383
|
+
"already_terminal"
|
|
1384
|
+
]);
|
|
1385
|
+
/**
|
|
1386
|
+
* True when `error` says the step an event was aimed at is closed for good: the run ended, or
|
|
1387
|
+
* the kernel refused the event because the step is unknown or past that transition. A timer
|
|
1388
|
+
* or a signal wait in that state has nothing left to wake, so its row is retired, not retried.
|
|
1389
|
+
*/
|
|
1390
|
+
function isStepGone(error) {
|
|
1391
|
+
if (error instanceof RunTerminal) return true;
|
|
1392
|
+
return error instanceof IllegalEvent && STEP_GONE.has(error.kernelError.code);
|
|
1393
|
+
}
|
|
1394
|
+
/** The host was asked to run a workflow it does not have registered. */
|
|
1395
|
+
var WorkflowRejected = class extends VloError {
|
|
1396
|
+
/** `unknown_workflow`, 400. */
|
|
1397
|
+
constructor(name) {
|
|
1398
|
+
super("unknown_workflow", `no workflow "${name}" is registered on this host`, 400);
|
|
1399
|
+
}
|
|
1400
|
+
};
|
|
1401
|
+
/** Bearer token or push signature missing or wrong. `unauthorized`, 401. */
|
|
1402
|
+
var Unauthorized = class extends VloError {
|
|
1403
|
+
/** Message defaults to `missing or invalid credentials`. */
|
|
1404
|
+
constructor(message = "missing or invalid credentials") {
|
|
1405
|
+
super("unauthorized", message, 401);
|
|
1406
|
+
}
|
|
1407
|
+
};
|
|
1408
|
+
/** Malformed body, query or signal payload. `bad_request`, 400. */
|
|
1409
|
+
var BadRequest = class extends VloError {
|
|
1410
|
+
/** `bad_request`, 400. */
|
|
1411
|
+
constructor(message) {
|
|
1412
|
+
super("bad_request", message, 400);
|
|
1413
|
+
}
|
|
1414
|
+
};
|
|
1415
|
+
/** The worker's lease is gone: stop working, someone else owns the attempt. */
|
|
1416
|
+
var LeaseLost = class extends VloError {
|
|
1417
|
+
/** `lease_lost`, 410. */
|
|
1418
|
+
constructor(taskId, attempt) {
|
|
1419
|
+
super("lease_lost", `task "${taskId}" attempt ${attempt} no longer holds its lease`, 410);
|
|
1420
|
+
}
|
|
1421
|
+
};
|
|
1422
|
+
// src/host/links.ts
|
|
1423
|
+
/**
|
|
1424
|
+
* Signed action links: a URL that delivers one named signal to one run, and nothing else.
|
|
1425
|
+
*
|
|
1426
|
+
* Same HMAC shape as the push signature (`worker/signature.ts`), with a different binding.
|
|
1427
|
+
* A push signs "this body, this attempt, now"; a link signs "this run, this signal, until
|
|
1428
|
+
* then" — because the holder is a person clicking an email hours later, not a peer host.
|
|
1429
|
+
* The token authorises exactly one `(run, signal)` pair, so leaking it cannot start a run,
|
|
1430
|
+
* read a journal or signal anything else.
|
|
1431
|
+
*/
|
|
1432
|
+
const PREFIX$2 = "v1";
|
|
1433
|
+
/** How long a minted link stays valid when the request gives no `expires_in_ms`: 7 days. */
|
|
1434
|
+
const DEFAULT_LINK_TTL_MS = 6048e5;
|
|
1435
|
+
/**
|
|
1436
|
+
* The secret signed links are minted with. Falls back to the control-plane token and then
|
|
1437
|
+
* the push secret so a single-secret deployment gets links for free; `undefined` disables
|
|
1438
|
+
* them rather than signing with an empty key.
|
|
1439
|
+
*/
|
|
1440
|
+
function linkSecret(auth) {
|
|
1441
|
+
return auth.linkSecret ?? auth.token ?? auth.pushSecret;
|
|
1442
|
+
}
|
|
1443
|
+
/**
|
|
1444
|
+
* Mints the token for a link: `v1.<expiresAtMs>.<hmac-sha256 hex>`. The host's
|
|
1445
|
+
* `POST /v1/runs/{id}/links/{name}` route does this for you; call it directly to mint
|
|
1446
|
+
* links out of band with the same secret ({@link linkSecret}).
|
|
1447
|
+
*
|
|
1448
|
+
* @example
|
|
1449
|
+
* ```ts
|
|
1450
|
+
* const token = signSignalLink(secret, {
|
|
1451
|
+
* runId: "run_1",
|
|
1452
|
+
* name: "approve",
|
|
1453
|
+
* expiresAtMs: Date.now() + DEFAULT_LINK_TTL_MS,
|
|
1454
|
+
* });
|
|
1455
|
+
* verifySignalLink(secret, token, "run_1", "approve", Date.now()); // true
|
|
1456
|
+
* ```
|
|
1457
|
+
*/
|
|
1458
|
+
function signSignalLink(secret, link) {
|
|
1459
|
+
const expiresAtMs = Math.floor(link.expiresAtMs);
|
|
1460
|
+
return `${PREFIX$2}.${expiresAtMs}.${digest$1(secret, link.runId, link.name, expiresAtMs)}`;
|
|
1461
|
+
}
|
|
1462
|
+
/**
|
|
1463
|
+
* True when `token` was signed with `secret` for exactly this `(runId, name)` and has not
|
|
1464
|
+
* expired at `nowMs`. Malformed tokens are false, never thrown; the comparison is timing-safe.
|
|
1465
|
+
*/
|
|
1466
|
+
function verifySignalLink(secret, token, runId, name, nowMs) {
|
|
1467
|
+
const [version, expiry, signature] = token.split(".");
|
|
1468
|
+
if (version !== PREFIX$2 || expiry === void 0 || signature === void 0) return false;
|
|
1469
|
+
const expiresAtMs = Number(expiry);
|
|
1470
|
+
if (!Number.isSafeInteger(expiresAtMs) || expiresAtMs <= nowMs) return false;
|
|
1471
|
+
const expected = Buffer.from(digest$1(secret, runId, name, expiresAtMs), "utf8");
|
|
1472
|
+
const actual = Buffer.from(signature, "utf8");
|
|
1473
|
+
if (expected.length !== actual.length) return false;
|
|
1474
|
+
return timingSafeEqual(expected, actual);
|
|
1475
|
+
}
|
|
1476
|
+
function digest$1(secret, runId, name, expiresAtMs) {
|
|
1477
|
+
return createHmac("sha256", secret).update(`${runId}.${name}.${expiresAtMs}`, "utf8").digest("hex");
|
|
1478
|
+
}
|
|
1479
|
+
// src/host/api/http.ts
|
|
1480
|
+
/** Small helpers shared by the routes: JSON in, JSON out, bearer auth, errors. */
|
|
1481
|
+
function json(body, status = 200) {
|
|
1482
|
+
return new Response(JSON.stringify(body), {
|
|
1483
|
+
status,
|
|
1484
|
+
headers: { "content-type": "application/json" }
|
|
1485
|
+
});
|
|
1486
|
+
}
|
|
1487
|
+
function errorResponse(error) {
|
|
1488
|
+
if (error instanceof VloError) return json({ error: {
|
|
1489
|
+
code: error.code,
|
|
1490
|
+
message: error.message
|
|
1491
|
+
} }, error.status);
|
|
1492
|
+
return json({ error: {
|
|
1493
|
+
code: "internal",
|
|
1494
|
+
message: error instanceof Error ? error.message : String(error)
|
|
1495
|
+
} }, 500);
|
|
1496
|
+
}
|
|
1497
|
+
async function readJson(request) {
|
|
1498
|
+
const text = await request.text();
|
|
1499
|
+
if (text.length === 0) return null;
|
|
1500
|
+
try {
|
|
1501
|
+
return JSON.parse(text);
|
|
1502
|
+
} catch (error) {
|
|
1503
|
+
throw new BadRequest(`body is not JSON: ${error instanceof Error ? error.message : error}`);
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
function requireBearer(request, token) {
|
|
1507
|
+
if (token === void 0) return;
|
|
1508
|
+
if (!constantTimeEquals(request.headers.get("authorization") ?? "", `Bearer ${token}`)) throw new Unauthorized();
|
|
1509
|
+
}
|
|
1510
|
+
/** Compares without leaking the match length through timing. Length itself is not secret. */
|
|
1511
|
+
function constantTimeEquals(actual, expected) {
|
|
1512
|
+
const a = Buffer.from(actual, "utf8");
|
|
1513
|
+
const b = Buffer.from(expected, "utf8");
|
|
1514
|
+
if (a.length !== b.length) return false;
|
|
1515
|
+
return timingSafeEqual(a, b);
|
|
1516
|
+
}
|
|
1517
|
+
function asObject(value) {
|
|
1518
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) throw new BadRequest("body must be a JSON object");
|
|
1519
|
+
return value;
|
|
1520
|
+
}
|
|
1521
|
+
function requireString(body, key) {
|
|
1522
|
+
const value = body[key];
|
|
1523
|
+
if (typeof value !== "string" || value.length === 0) throw new BadRequest(`"${key}" must be a non-empty string`);
|
|
1524
|
+
return value;
|
|
1525
|
+
}
|
|
1526
|
+
function requireInt(body, key) {
|
|
1527
|
+
const value = body[key];
|
|
1528
|
+
if (typeof value !== "number" || !Number.isInteger(value)) throw new BadRequest(`"${key}" must be an integer`);
|
|
1529
|
+
return value;
|
|
1530
|
+
}
|
|
1531
|
+
function optionalInt(body, key) {
|
|
1532
|
+
const value = body[key];
|
|
1533
|
+
if (value === void 0 || value === null) return void 0;
|
|
1534
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) throw new BadRequest(`"${key}" must be a non-negative integer`);
|
|
1535
|
+
return value;
|
|
1536
|
+
}
|
|
1537
|
+
const CAUSES = /* @__PURE__ */ new Set([
|
|
1538
|
+
"timeout",
|
|
1539
|
+
"heartbeat_lost",
|
|
1540
|
+
"app_error",
|
|
1541
|
+
"user_cancel",
|
|
1542
|
+
"schema_violation",
|
|
1543
|
+
"nondeterminism_detected"
|
|
1544
|
+
]);
|
|
1545
|
+
function optionalCause(body) {
|
|
1546
|
+
const value = body.cause;
|
|
1547
|
+
if (value === void 0 || value === null) return void 0;
|
|
1548
|
+
if (typeof value !== "string" || !CAUSES.has(value)) throw new BadRequest(`unknown cause`);
|
|
1549
|
+
return value;
|
|
1550
|
+
}
|
|
1551
|
+
/** Wire `usage` is snake_case and integral, because the kernel hashes it into run state. */
|
|
1552
|
+
function optionalUsage(body) {
|
|
1553
|
+
const value = body.usage;
|
|
1554
|
+
if (value === void 0 || value === null) return void 0;
|
|
1555
|
+
const fields = asObject(value);
|
|
1556
|
+
return {
|
|
1557
|
+
cpu_ms: optionalInt(fields, "cpu_ms") ?? 0,
|
|
1558
|
+
tokens: optionalInt(fields, "tokens") ?? 0,
|
|
1559
|
+
cost_micro_usd: optionalInt(fields, "cost_micro_usd") ?? 0
|
|
1560
|
+
};
|
|
1561
|
+
}
|
|
1562
|
+
// src/host/api/links.ts
|
|
1563
|
+
var LinksDisabled = class extends VloError {
|
|
1564
|
+
constructor() {
|
|
1565
|
+
super("links_disabled", "signed links need auth.linkSecret (or auth.token / auth.pushSecret) on this host", 503);
|
|
1566
|
+
}
|
|
1567
|
+
};
|
|
1568
|
+
async function postSignalLink(ctx, request, url, runId, name) {
|
|
1569
|
+
const secret = linkSecret(ctx.auth);
|
|
1570
|
+
if (secret === void 0) throw new LinksDisabled();
|
|
1571
|
+
const body = asObject(await readJson(request));
|
|
1572
|
+
const expiresAtMs = ctx.now() + (optionalInt(body, "expires_in_ms") ?? 6048e5);
|
|
1573
|
+
const token = signSignalLink(secret, {
|
|
1574
|
+
runId,
|
|
1575
|
+
name,
|
|
1576
|
+
expiresAtMs
|
|
1577
|
+
});
|
|
1578
|
+
return json({
|
|
1579
|
+
url: `${`${(ctx.publicUrl ?? url.origin).replace(/\/$/, "")}${ctx.basePath ?? ""}`}${signalPath(runId, name)}?token=${encodeURIComponent(token)}`,
|
|
1580
|
+
expires_at_ms: expiresAtMs
|
|
1581
|
+
});
|
|
1582
|
+
}
|
|
1583
|
+
/** The confirmation page. Deliberately dependency-free: it renders inside a webmail iframe. */
|
|
1584
|
+
function renderConfirmation(runId, name, token, basePath = "") {
|
|
1585
|
+
const action = `${basePath}${signalPath(runId, name)}?token=${encodeURIComponent(token)}`;
|
|
1586
|
+
const html = `<!doctype html>
|
|
1587
|
+
<html lang="en">
|
|
1588
|
+
<meta charset="utf-8">
|
|
1589
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1590
|
+
<meta name="robots" content="noindex, nofollow">
|
|
1591
|
+
<title>Confirm ${escapeHtml(name)}</title>
|
|
1592
|
+
<body style="font-family:system-ui,sans-serif;margin:0;padding:2rem;max-width:32rem">
|
|
1593
|
+
<h1 style="font-size:1.25rem">Confirm “${escapeHtml(name)}”</h1>
|
|
1594
|
+
<p>This sends the <code>${escapeHtml(name)}</code> signal to run <code>${escapeHtml(runId)}</code>.</p>
|
|
1595
|
+
<form method="post" action="${escapeHtml(action)}">
|
|
1596
|
+
<button type="submit" style="font:inherit;padding:.6rem 1.2rem">Confirm</button>
|
|
1597
|
+
</form>
|
|
1598
|
+
</body>
|
|
1599
|
+
</html>
|
|
1600
|
+
`;
|
|
1601
|
+
return new Response(html, {
|
|
1602
|
+
status: 200,
|
|
1603
|
+
headers: {
|
|
1604
|
+
"content-type": "text/html; charset=utf-8",
|
|
1605
|
+
"cache-control": "no-store"
|
|
1606
|
+
}
|
|
1607
|
+
});
|
|
1608
|
+
}
|
|
1609
|
+
function signalPath(runId, name) {
|
|
1610
|
+
return `/v1/runs/${encodeURIComponent(runId)}/signals/${encodeURIComponent(name)}`;
|
|
1611
|
+
}
|
|
1612
|
+
function escapeHtml(value) {
|
|
1613
|
+
return value.replace(/[&<>"']/g, (char) => ENTITIES[char] ?? char);
|
|
1614
|
+
}
|
|
1615
|
+
const ENTITIES = {
|
|
1616
|
+
"&": "&",
|
|
1617
|
+
"<": "<",
|
|
1618
|
+
">": ">",
|
|
1619
|
+
"\"": """,
|
|
1620
|
+
"'": "'"
|
|
1621
|
+
};
|
|
1622
|
+
// src/blob/ref.ts
|
|
1623
|
+
/** Blob references as they appear in `*_ref` columns. */
|
|
1624
|
+
const PREFIX$1 = "blob://sha256/";
|
|
1625
|
+
const SHA256_HEX = /^[0-9a-f]{64}$/;
|
|
1626
|
+
/** `blob://sha256/<hex>` for a lowercase sha256 digest. Throws a plain `Error` on anything else. */
|
|
1627
|
+
function toBlobRef(sha256Hex) {
|
|
1628
|
+
if (!SHA256_HEX.test(sha256Hex)) throw new Error(`not a sha256 hex digest: ${sha256Hex}`);
|
|
1629
|
+
return PREFIX$1 + sha256Hex;
|
|
1630
|
+
}
|
|
1631
|
+
/** The digest, or null when `ref` is not a blob reference. */
|
|
1632
|
+
function parseBlobRef(ref) {
|
|
1633
|
+
if (!ref.startsWith(PREFIX$1)) return null;
|
|
1634
|
+
const digest = ref.slice(14);
|
|
1635
|
+
return SHA256_HEX.test(digest) ? digest : null;
|
|
1636
|
+
}
|
|
1637
|
+
// src/blob/offload.ts
|
|
1638
|
+
/**
|
|
1639
|
+
* The 256 KB rule: JSON text rides inline in the journal while it fits, and
|
|
1640
|
+
* moves to the blob store otherwise. The journal stores the resulting
|
|
1641
|
+
* `blob://sha256/<hex>` in the matching `*_ref` column.
|
|
1642
|
+
*/
|
|
1643
|
+
const encoder = new TextEncoder();
|
|
1644
|
+
const decoder = new TextDecoder();
|
|
1645
|
+
/** A blob reference when `text` is too big to inline, otherwise null. */
|
|
1646
|
+
async function offloadIfOversized(store, text, limit = INLINE_LIMIT_BYTES) {
|
|
1647
|
+
const bytes = encoder.encode(text);
|
|
1648
|
+
if (bytes.byteLength <= limit) return null;
|
|
1649
|
+
return toBlobRef(await store.put(bytes));
|
|
1650
|
+
}
|
|
1651
|
+
/** Reads back what `offloadIfOversized` wrote, byte-exact. */
|
|
1652
|
+
async function readBlobText(store, ref) {
|
|
1653
|
+
const digest = parseBlobRef(ref);
|
|
1654
|
+
if (digest === null) throw new Error(`not a blob ref: ${ref}`);
|
|
1655
|
+
return decoder.decode(await store.get(digest));
|
|
1656
|
+
}
|
|
1657
|
+
// src/host/events.ts
|
|
1658
|
+
/**
|
|
1659
|
+
* Building the events the host submits, and telling them apart from the ones the kernel
|
|
1660
|
+
* emits.
|
|
1661
|
+
*
|
|
1662
|
+
* The journal holds both. Only *inputs* are re-fed on a re-fold; kernel outputs (a task
|
|
1663
|
+
* the reducer asked for, a signal wait, the `complete` marker) are recomputed by replaying
|
|
1664
|
+
* the inputs, so feeding them back would double-count. The partition below mirrors
|
|
1665
|
+
* `crates/kernel/src/classify.rs`: an event is an input exactly when `classify` routes it.
|
|
1666
|
+
*/
|
|
1667
|
+
const INPUT_MARKERS = /* @__PURE__ */ new Set([
|
|
1668
|
+
START_STEP_ID,
|
|
1669
|
+
CANCEL_STEP_ID,
|
|
1670
|
+
FAIL_STEP_ID,
|
|
1671
|
+
NONDETERMINISM_STEP_ID
|
|
1672
|
+
]);
|
|
1673
|
+
/** 32 lowercase hex characters, journaled so every replay sees the same randomness. */
|
|
1674
|
+
function randomHex() {
|
|
1675
|
+
return randomBytes(16).toString("hex");
|
|
1676
|
+
}
|
|
1677
|
+
function isInputEvent(event) {
|
|
1678
|
+
switch (event.kind) {
|
|
1679
|
+
case "marker": return INPUT_MARKERS.has(event.step_id);
|
|
1680
|
+
case "task": return event.status !== "scheduled";
|
|
1681
|
+
case "timer":
|
|
1682
|
+
case "signal": return event.status === "succeeded";
|
|
1683
|
+
case "child": return event.status === "succeeded" || event.status === "failed" || event.status === "cancelled";
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
const ASSIGNED_BY_KERNEL = [
|
|
1687
|
+
"seq",
|
|
1688
|
+
"state_hash",
|
|
1689
|
+
"parent_run_id",
|
|
1690
|
+
"parent_step_id"
|
|
1691
|
+
];
|
|
1692
|
+
/** Drops the fields the kernel assigns, so a journaled envelope can be re-submitted. */
|
|
1693
|
+
function toEventInput(envelope) {
|
|
1694
|
+
const input = { ...envelope };
|
|
1695
|
+
for (const field of ASSIGNED_BY_KERNEL) delete input[field];
|
|
1696
|
+
return input;
|
|
1697
|
+
}
|
|
1698
|
+
function base(b, rest) {
|
|
1699
|
+
return {
|
|
1700
|
+
run_id: b.runId,
|
|
1701
|
+
ts_ms: b.nowMs,
|
|
1702
|
+
random: randomHex(),
|
|
1703
|
+
...rest
|
|
1704
|
+
};
|
|
1705
|
+
}
|
|
1706
|
+
function startedEvent(b, inputJson) {
|
|
1707
|
+
return base(b, {
|
|
1708
|
+
step_id: START_STEP_ID,
|
|
1709
|
+
attempt: 0,
|
|
1710
|
+
kind: "marker",
|
|
1711
|
+
status: "succeeded",
|
|
1712
|
+
payload: inputJson
|
|
1713
|
+
});
|
|
1714
|
+
}
|
|
1715
|
+
function taskRunningEvent(b, stepId, attempt) {
|
|
1716
|
+
return base(b, {
|
|
1717
|
+
step_id: stepId,
|
|
1718
|
+
attempt,
|
|
1719
|
+
kind: "task",
|
|
1720
|
+
status: "running"
|
|
1721
|
+
});
|
|
1722
|
+
}
|
|
1723
|
+
/** What an attempt spent, when the worker reported any. The kernel banks it as it folds. */
|
|
1724
|
+
function spent(usage) {
|
|
1725
|
+
return usage !== void 0 ? { usage } : {};
|
|
1726
|
+
}
|
|
1727
|
+
function taskSucceededEvent(b, stepId, attempt, outputJson, schemaRef, usage) {
|
|
1728
|
+
return base(b, {
|
|
1729
|
+
step_id: stepId,
|
|
1730
|
+
attempt,
|
|
1731
|
+
kind: "task",
|
|
1732
|
+
status: "succeeded",
|
|
1733
|
+
payload: outputJson,
|
|
1734
|
+
...schemaRef !== void 0 ? { schema_ref: schemaRef } : {},
|
|
1735
|
+
...spent(usage)
|
|
1736
|
+
});
|
|
1737
|
+
}
|
|
1738
|
+
function taskFailedEvent(b, stepId, attempt, cause, error, usage) {
|
|
1739
|
+
return base(b, {
|
|
1740
|
+
step_id: stepId,
|
|
1741
|
+
attempt,
|
|
1742
|
+
kind: "task",
|
|
1743
|
+
status: "failed",
|
|
1744
|
+
cause,
|
|
1745
|
+
error,
|
|
1746
|
+
...spent(usage)
|
|
1747
|
+
});
|
|
1748
|
+
}
|
|
1749
|
+
/** `attempt` names the *next* attempt; the payload carries the delay the kernel planned. */
|
|
1750
|
+
function taskRetryingEvent(b, stepId, nextAttempt, cause, delayMs, error, usage) {
|
|
1751
|
+
return base(b, {
|
|
1752
|
+
step_id: stepId,
|
|
1753
|
+
attempt: nextAttempt,
|
|
1754
|
+
kind: "task",
|
|
1755
|
+
status: "retrying",
|
|
1756
|
+
cause,
|
|
1757
|
+
payload: JSON.stringify({ delay_ms: delayMs }),
|
|
1758
|
+
...error !== void 0 ? { error } : {},
|
|
1759
|
+
...spent(usage)
|
|
1760
|
+
});
|
|
1761
|
+
}
|
|
1762
|
+
/** A due timer. The kernel reads the deadline from the step, so there is no payload. */
|
|
1763
|
+
function timerFiredEvent(b, stepId) {
|
|
1764
|
+
return base(b, {
|
|
1765
|
+
step_id: stepId,
|
|
1766
|
+
attempt: 0,
|
|
1767
|
+
kind: "timer",
|
|
1768
|
+
status: "succeeded"
|
|
1769
|
+
});
|
|
1770
|
+
}
|
|
1771
|
+
function signalEvent(b, stepId, payloadJson) {
|
|
1772
|
+
return base(b, {
|
|
1773
|
+
step_id: stepId,
|
|
1774
|
+
attempt: 0,
|
|
1775
|
+
kind: "signal",
|
|
1776
|
+
status: "succeeded",
|
|
1777
|
+
payload: payloadJson
|
|
1778
|
+
});
|
|
1779
|
+
}
|
|
1780
|
+
function childEvent(b, stepId, status, outputJson) {
|
|
1781
|
+
return base(b, {
|
|
1782
|
+
step_id: stepId,
|
|
1783
|
+
attempt: 0,
|
|
1784
|
+
kind: "child",
|
|
1785
|
+
status,
|
|
1786
|
+
...outputJson !== void 0 ? { payload: outputJson } : {}
|
|
1787
|
+
});
|
|
1788
|
+
}
|
|
1789
|
+
function cancelEvent(b) {
|
|
1790
|
+
return base(b, {
|
|
1791
|
+
step_id: CANCEL_STEP_ID,
|
|
1792
|
+
attempt: 0,
|
|
1793
|
+
kind: "marker",
|
|
1794
|
+
status: "cancelled",
|
|
1795
|
+
cause: "user_cancel"
|
|
1796
|
+
});
|
|
1797
|
+
}
|
|
1798
|
+
/**
|
|
1799
|
+
* The reducer threw: `WorkflowFailure` and any other throw both land here. The event being
|
|
1800
|
+
* folded is rolled back with its transaction, so it rides along in the payload as evidence.
|
|
1801
|
+
*/
|
|
1802
|
+
function failEvent(b, message, trigger) {
|
|
1803
|
+
return base(b, {
|
|
1804
|
+
step_id: FAIL_STEP_ID,
|
|
1805
|
+
attempt: 0,
|
|
1806
|
+
kind: "marker",
|
|
1807
|
+
status: "failed",
|
|
1808
|
+
cause: "app_error",
|
|
1809
|
+
error: message,
|
|
1810
|
+
...trigger !== void 0 ? { payload: JSON.stringify(trigger) } : {}
|
|
1811
|
+
});
|
|
1812
|
+
}
|
|
1813
|
+
function nondeterminismEvent(b, detail) {
|
|
1814
|
+
return base(b, {
|
|
1815
|
+
step_id: NONDETERMINISM_STEP_ID,
|
|
1816
|
+
attempt: 0,
|
|
1817
|
+
kind: "marker",
|
|
1818
|
+
status: "failed",
|
|
1819
|
+
cause: "nondeterminism_detected",
|
|
1820
|
+
error: detail
|
|
1821
|
+
});
|
|
1822
|
+
}
|
|
1823
|
+
/** A run that accepts no further events. */
|
|
1824
|
+
function isTerminalRun(status) {
|
|
1825
|
+
return isTerminalRunStatus(status);
|
|
1826
|
+
}
|
|
1827
|
+
/** A child run's terminal status as the parent's `child` event sees it. */
|
|
1828
|
+
function childStatusOf(runStatus) {
|
|
1829
|
+
switch (runStatus) {
|
|
1830
|
+
case "completed": return "succeeded";
|
|
1831
|
+
case "failed": return "failed";
|
|
1832
|
+
case "cancelled": return "cancelled";
|
|
1833
|
+
default: return null;
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
/** Kernel calls are infallible-by-contract; a refusal is an `IllegalEvent` here. */
|
|
1837
|
+
function unwrap(result) {
|
|
1838
|
+
if (result.ok) return result.value;
|
|
1839
|
+
throw new IllegalEvent(result.error);
|
|
1840
|
+
}
|
|
1841
|
+
/** Codes that mean "this event was already folded", i.e. an at-least-once redelivery. */
|
|
1842
|
+
const DUPLICATE_CODES = /* @__PURE__ */ new Set([
|
|
1843
|
+
"unknown_step",
|
|
1844
|
+
"already_terminal",
|
|
1845
|
+
"bad_seq"
|
|
1846
|
+
]);
|
|
1847
|
+
function isDuplicate(error) {
|
|
1848
|
+
return DUPLICATE_CODES.has(error.code);
|
|
1849
|
+
}
|
|
1850
|
+
// src/host/refold.ts
|
|
1851
|
+
/**
|
|
1852
|
+
* One event → one write-set. The reducer runs here and nowhere else. Pure: nothing is
|
|
1853
|
+
* journaled, the caller applies the returned transition.
|
|
1854
|
+
*
|
|
1855
|
+
* @throws {@link ReducerFailed} when the workflow's reducer throws; carries the trigger event.
|
|
1856
|
+
* @throws {@link IllegalEvent} when the kernel refuses to prepare or reduce the event.
|
|
1857
|
+
*/
|
|
1858
|
+
function foldEvent(ctx, workflow, run, at, event) {
|
|
1859
|
+
const prepared = unwrap(ctx.kernel.prepareEvent({
|
|
1860
|
+
run,
|
|
1861
|
+
...at.kernelState !== void 0 ? { kernel_state: at.kernelState } : {},
|
|
1862
|
+
...at.state !== void 0 ? { state: at.state } : {},
|
|
1863
|
+
event
|
|
1864
|
+
}));
|
|
1865
|
+
if (prepared.mode === "lifecycle") return prepared.transition;
|
|
1866
|
+
let reduction;
|
|
1867
|
+
try {
|
|
1868
|
+
reduction = workflow.reduce(at.state ?? null, prepared.reducer_event, prepared.init_input);
|
|
1869
|
+
} catch (error) {
|
|
1870
|
+
const reason = messageOf$1(error);
|
|
1871
|
+
throw new ReducerFailed(run.run_id, `${reason} [while folding ${describe(event)}]`, event, reason);
|
|
1872
|
+
}
|
|
1873
|
+
return unwrap(ctx.kernel.reduceStep({
|
|
1874
|
+
run,
|
|
1875
|
+
kernel_state: prepared.kernel_state,
|
|
1876
|
+
event,
|
|
1877
|
+
reduction
|
|
1878
|
+
}));
|
|
1879
|
+
}
|
|
1880
|
+
function messageOf$1(error) {
|
|
1881
|
+
return error instanceof Error ? error.message : String(error);
|
|
1882
|
+
}
|
|
1883
|
+
function describe(event) {
|
|
1884
|
+
const cause = event.cause !== void 0 ? ` cause=${event.cause}` : "";
|
|
1885
|
+
const error = event.error !== void 0 ? ` error=${event.error}` : "";
|
|
1886
|
+
return `${event.kind} ${event.step_id}#${event.attempt} ${event.status}${cause}${error}`;
|
|
1887
|
+
}
|
|
1888
|
+
/**
|
|
1889
|
+
* Replays every input event in the journal. Kernel outputs (scheduled tasks, signal waits,
|
|
1890
|
+
* the `complete` marker) are recomputed, never re-fed.
|
|
1891
|
+
*
|
|
1892
|
+
* @throws {@link Nondeterminism} at the first event whose replayed `seq` or `state_hash`
|
|
1893
|
+
* differs from the journaled one, or when `events` holds nothing foldable.
|
|
1894
|
+
*/
|
|
1895
|
+
function rebuildCheckpoint(ctx, workflow, run, events) {
|
|
1896
|
+
let at = {};
|
|
1897
|
+
let stateHash = "";
|
|
1898
|
+
let lastSeq = 0;
|
|
1899
|
+
let status = "created";
|
|
1900
|
+
for (const envelope of events) {
|
|
1901
|
+
if (!isInputEvent(envelope)) continue;
|
|
1902
|
+
const transition = foldEvent(ctx, workflow, {
|
|
1903
|
+
run_id: run.run_id,
|
|
1904
|
+
workflow: run.workflow,
|
|
1905
|
+
bundle_digest: run.component_digest,
|
|
1906
|
+
status,
|
|
1907
|
+
last_seq: lastSeq,
|
|
1908
|
+
...run.parent_run_id !== void 0 ? { parent_run_id: run.parent_run_id } : {},
|
|
1909
|
+
...run.parent_step_id !== void 0 ? { parent_step_id: run.parent_step_id } : {}
|
|
1910
|
+
}, at, toEventInput(envelope));
|
|
1911
|
+
const trigger = transition.events[0];
|
|
1912
|
+
if (trigger === void 0 || trigger.seq !== envelope.seq) throw new Nondeterminism(run.run_id, envelope.seq, `replay produced seq ${trigger?.seq ?? "none"} for a journaled seq ${envelope.seq}`);
|
|
1913
|
+
if (trigger.state_hash !== envelope.state_hash) throw new Nondeterminism(run.run_id, envelope.seq, `state hash ${trigger.state_hash} does not match the journaled ${envelope.state_hash}`);
|
|
1914
|
+
at = {
|
|
1915
|
+
kernelState: transition.kernel_state,
|
|
1916
|
+
state: transition.state
|
|
1917
|
+
};
|
|
1918
|
+
stateHash = transition.state_hash;
|
|
1919
|
+
lastSeq = transition.run.last_seq;
|
|
1920
|
+
status = transition.run.status;
|
|
1921
|
+
}
|
|
1922
|
+
if (at.kernelState === void 0 || at.state === void 0) throw new Nondeterminism(run.run_id, 0, "the journal holds no foldable events for this run");
|
|
1923
|
+
return {
|
|
1924
|
+
kernelState: at.kernelState,
|
|
1925
|
+
state: at.state,
|
|
1926
|
+
stateHash,
|
|
1927
|
+
seq: lastSeq,
|
|
1928
|
+
status
|
|
1929
|
+
};
|
|
1930
|
+
}
|
|
1931
|
+
// src/host/transition.ts
|
|
1932
|
+
/**
|
|
1933
|
+
* The single writer path. Every durable change to a run goes through `applyEvent`.
|
|
1934
|
+
*
|
|
1935
|
+
* One transaction: take the run's write lock, load the checkpoint, fold the event, apply
|
|
1936
|
+
* the kernel's write-set. Cross-run effects (starting a child, telling a parent) and HTTP
|
|
1937
|
+
* pushes stay outside — SQLite serialises transactions through one connection, so holding
|
|
1938
|
+
* one across a network call would stall the whole host.
|
|
1939
|
+
*/
|
|
1940
|
+
/** Markers that end a run. They echo whatever checkpoint exists and never call the reducer. */
|
|
1941
|
+
const CLOSING_MARKERS = /* @__PURE__ */ new Set([
|
|
1942
|
+
CANCEL_STEP_ID,
|
|
1943
|
+
FAIL_STEP_ID,
|
|
1944
|
+
NONDETERMINISM_STEP_ID
|
|
1945
|
+
]);
|
|
1946
|
+
/**
|
|
1947
|
+
* Submits one event. Owns its transaction, recovers a reducer throw or a divergence into
|
|
1948
|
+
* the matching marker, then runs the post-commit work (buffered signals, emits, kick).
|
|
1949
|
+
*
|
|
1950
|
+
* A `ReducerFailed` is swallowed: the run is failed with an `app_error` marker and that
|
|
1951
|
+
* outcome is returned. A `Nondeterminism` is recorded as a marker and then rethrown.
|
|
1952
|
+
*
|
|
1953
|
+
* @throws {@link RunNotFound} when no run has that id.
|
|
1954
|
+
* @throws {@link RunTerminal} when the run ended and the event is not a task result or a closing marker.
|
|
1955
|
+
* @throws {@link WorkflowRejected} when the run's workflow is not registered on this host.
|
|
1956
|
+
* @throws {@link IllegalEvent} when the kernel refuses the event for a reason other than a duplicate.
|
|
1957
|
+
* @throws {@link Nondeterminism} after journaling the divergence.
|
|
1958
|
+
*/
|
|
1959
|
+
async function applyEvent(ctx, runId, source, after) {
|
|
1960
|
+
let outcome;
|
|
1961
|
+
try {
|
|
1962
|
+
outcome = await ctx.journal.transaction((tx) => runTransition(ctx, tx, runId, source, after));
|
|
1963
|
+
} catch (error) {
|
|
1964
|
+
if (error instanceof ReducerFailed) return applyEvent(ctx, runId, failEvent({
|
|
1965
|
+
runId,
|
|
1966
|
+
nowMs: ctx.now()
|
|
1967
|
+
}, error.reason, error.trigger));
|
|
1968
|
+
if (error instanceof Nondeterminism) {
|
|
1969
|
+
await applyEvent(ctx, runId, nondeterminismEvent({
|
|
1970
|
+
runId,
|
|
1971
|
+
nowMs: ctx.now()
|
|
1972
|
+
}, error.message));
|
|
1973
|
+
throw error;
|
|
1974
|
+
}
|
|
1975
|
+
throw error;
|
|
1976
|
+
}
|
|
1977
|
+
await afterCommit(ctx, runId, outcome);
|
|
1978
|
+
return outcome;
|
|
1979
|
+
}
|
|
1980
|
+
async function afterCommit(ctx, runId, outcome) {
|
|
1981
|
+
for (const emit of outcome.transition?.emits ?? []) ctx.events.emit("emit", {
|
|
1982
|
+
run_id: runId,
|
|
1983
|
+
channel: emit.channel,
|
|
1984
|
+
data: emit.data
|
|
1985
|
+
});
|
|
1986
|
+
for (const task of outcome.transition?.tasks ?? []) {
|
|
1987
|
+
const scheduled = {
|
|
1988
|
+
run_id: runId,
|
|
1989
|
+
task_id: task.task_id,
|
|
1990
|
+
queue: task.queue
|
|
1991
|
+
};
|
|
1992
|
+
ctx.events.emit("task_scheduled", scheduled);
|
|
1993
|
+
}
|
|
1994
|
+
for (const followUp of outcome.followUps) await applyEvent(ctx, runId, followUp);
|
|
1995
|
+
if (outcome.applied) ctx.kick();
|
|
1996
|
+
}
|
|
1997
|
+
async function runTransition(ctx, tx, runId, source, after) {
|
|
1998
|
+
const run = await tx.lockRun(runId);
|
|
1999
|
+
if (run === null) throw new RunNotFound(runId);
|
|
2000
|
+
const event = typeof source === "function" ? await source(tx, run) : source;
|
|
2001
|
+
if (event === null) return finish(tx, {
|
|
2002
|
+
applied: false,
|
|
2003
|
+
duplicate: false,
|
|
2004
|
+
run,
|
|
2005
|
+
followUps: []
|
|
2006
|
+
}, after);
|
|
2007
|
+
const closing = event.kind === "marker" && CLOSING_MARKERS.has(event.step_id);
|
|
2008
|
+
if (isTerminalRun(run.status)) {
|
|
2009
|
+
if (event.kind === "task" || closing) return finish(tx, {
|
|
2010
|
+
applied: false,
|
|
2011
|
+
duplicate: true,
|
|
2012
|
+
run,
|
|
2013
|
+
followUps: []
|
|
2014
|
+
}, after);
|
|
2015
|
+
throw new RunTerminal(runId, run.status);
|
|
2016
|
+
}
|
|
2017
|
+
const workflow = ctx.workflows.get(run.workflow);
|
|
2018
|
+
if (workflow === void 0) throw new WorkflowRejected(run.workflow);
|
|
2019
|
+
const at = await loadCheckpoint(ctx, tx, run, workflow, closing);
|
|
2020
|
+
let transition;
|
|
2021
|
+
try {
|
|
2022
|
+
transition = foldEvent(ctx, workflow, runRef(run), at, event);
|
|
2023
|
+
} catch (error) {
|
|
2024
|
+
if (error instanceof IllegalEvent && isDuplicate(error.kernelError)) return finish(tx, {
|
|
2025
|
+
applied: false,
|
|
2026
|
+
duplicate: true,
|
|
2027
|
+
run,
|
|
2028
|
+
followUps: []
|
|
2029
|
+
}, after);
|
|
2030
|
+
throw error;
|
|
2031
|
+
}
|
|
2032
|
+
const nowMs = ctx.now();
|
|
2033
|
+
const opts = {
|
|
2034
|
+
nowMs,
|
|
2035
|
+
...await offloadedRefs(ctx, transition),
|
|
2036
|
+
childRuns: childRuns(ctx, run, transition),
|
|
2037
|
+
...successorRun(ctx, run, transition)
|
|
2038
|
+
};
|
|
2039
|
+
await tx.applyTransition(runId, transition, opts);
|
|
2040
|
+
const followUps = await pickUpBufferedSignals(ctx, tx, runId, transition, nowMs);
|
|
2041
|
+
return finish(tx, {
|
|
2042
|
+
applied: true,
|
|
2043
|
+
duplicate: false,
|
|
2044
|
+
run,
|
|
2045
|
+
transition,
|
|
2046
|
+
followUps
|
|
2047
|
+
}, after);
|
|
2048
|
+
}
|
|
2049
|
+
async function finish(tx, outcome, after) {
|
|
2050
|
+
if (after !== void 0) await after(tx, outcome);
|
|
2051
|
+
return outcome;
|
|
2052
|
+
}
|
|
2053
|
+
/**
|
|
2054
|
+
* The checkpoint to fold onto.
|
|
2055
|
+
*
|
|
2056
|
+
* Only one checkpoint is kept per run, so the plan's "re-fold the last N events" becomes a
|
|
2057
|
+
* hash check: re-hashing the stored pair must reproduce the stored `state_hash`. A missing
|
|
2058
|
+
* checkpoint, or one written by a different bundle, is rebuilt from seq 0 instead.
|
|
2059
|
+
*/
|
|
2060
|
+
async function loadCheckpoint(ctx, tx, run, workflow, closing) {
|
|
2061
|
+
if (run.last_seq === 0) return {};
|
|
2062
|
+
const checkpoint = await tx.getState(run.run_id);
|
|
2063
|
+
if (closing) return checkpoint === null ? {} : await readCheckpoint(ctx, checkpoint);
|
|
2064
|
+
if (checkpoint === null || checkpoint.bundle_digest !== run.component_digest) {
|
|
2065
|
+
const rebuilt = rebuildCheckpoint(ctx, workflow, run, await tx.readEvents(run.run_id, 0));
|
|
2066
|
+
return {
|
|
2067
|
+
kernelState: rebuilt.kernelState,
|
|
2068
|
+
state: rebuilt.state
|
|
2069
|
+
};
|
|
2070
|
+
}
|
|
2071
|
+
const at = await readCheckpoint(ctx, checkpoint);
|
|
2072
|
+
if (at.kernelState === void 0 || at.state === void 0) throw new Nondeterminism(run.run_id, checkpoint.seq, "the checkpoint has no body");
|
|
2073
|
+
const hash = ctx.kernel.stateHash({
|
|
2074
|
+
kernel_state: at.kernelState,
|
|
2075
|
+
state: at.state
|
|
2076
|
+
});
|
|
2077
|
+
if (!hash.ok || hash.value.hash !== checkpoint.state_hash) throw new Nondeterminism(run.run_id, checkpoint.seq, `the checkpoint hashes to ${hash.ok ? hash.value.hash : hash.error.code}, not the stored ${checkpoint.state_hash}`);
|
|
2078
|
+
return at;
|
|
2079
|
+
}
|
|
2080
|
+
async function readCheckpoint(ctx, row) {
|
|
2081
|
+
const state = row.state ?? (row.state_ref ? await readBlobText(ctx.blob, row.state_ref) : void 0);
|
|
2082
|
+
return {
|
|
2083
|
+
kernelState: JSON.parse(row.kernel_state),
|
|
2084
|
+
...state !== void 0 ? { state } : {}
|
|
2085
|
+
};
|
|
2086
|
+
}
|
|
2087
|
+
async function offloadedRefs(ctx, t) {
|
|
2088
|
+
const refs = {};
|
|
2089
|
+
if (!t.state_inline) {
|
|
2090
|
+
const ref = await offloadIfOversized(ctx.blob, t.state);
|
|
2091
|
+
if (ref !== null) refs.stateRef = ref;
|
|
2092
|
+
}
|
|
2093
|
+
if (t.completion?.output !== void 0) {
|
|
2094
|
+
const ref = await offloadIfOversized(ctx.blob, JSON.stringify(t.completion.output));
|
|
2095
|
+
if (ref !== null) refs.outputRef = ref;
|
|
2096
|
+
}
|
|
2097
|
+
return refs;
|
|
2098
|
+
}
|
|
2099
|
+
/** Child runs land as `created` rows; the outbox starts them in their own transaction. */
|
|
2100
|
+
function childRuns(ctx, run, t) {
|
|
2101
|
+
return t.spawns.map((spawn) => {
|
|
2102
|
+
const child = ctx.workflows.get(spawn.workflow);
|
|
2103
|
+
if (child === void 0) throw new ReducerFailed(run.run_id, `cannot spawn "${spawn.workflow}": no such workflow is registered on this host`);
|
|
2104
|
+
return {
|
|
2105
|
+
run_id: spawn.child_run_id,
|
|
2106
|
+
namespace: run.namespace,
|
|
2107
|
+
workflow: spawn.workflow,
|
|
2108
|
+
component_digest: child.digest,
|
|
2109
|
+
status: "created",
|
|
2110
|
+
parent_run_id: run.run_id,
|
|
2111
|
+
parent_step_id: spawn.step_id,
|
|
2112
|
+
input: JSON.stringify(spawn.input)
|
|
2113
|
+
};
|
|
2114
|
+
});
|
|
2115
|
+
}
|
|
2116
|
+
/**
|
|
2117
|
+
* The successor of a `continue_as_new`, as a `created` row the outbox will start. Its id is
|
|
2118
|
+
* derived from the `continue` step, so re-deriving it lands on the same row (`ON CONFLICT DO
|
|
2119
|
+
* NOTHING`). It inherits the parent link: whichever run in the chain finally closes is the
|
|
2120
|
+
* one that tells the parent, and a `continued` run never does.
|
|
2121
|
+
*/
|
|
2122
|
+
function successorRun(ctx, run, t) {
|
|
2123
|
+
if (t.continue_as_new === void 0) return {};
|
|
2124
|
+
const workflow = ctx.workflows.get(run.workflow);
|
|
2125
|
+
if (workflow === void 0) throw new ReducerFailed(run.run_id, `cannot continue "${run.workflow}": no such workflow is registered on this host`);
|
|
2126
|
+
return { successorRun: {
|
|
2127
|
+
run_id: unwrap(ctx.kernel.deriveIds({
|
|
2128
|
+
run_id: run.run_id,
|
|
2129
|
+
step_id: CONTINUE_STEP_ID,
|
|
2130
|
+
attempt: 0
|
|
2131
|
+
})).child_run_id,
|
|
2132
|
+
namespace: run.namespace,
|
|
2133
|
+
workflow: run.workflow,
|
|
2134
|
+
component_digest: workflow.digest,
|
|
2135
|
+
status: "created",
|
|
2136
|
+
continued_from: run.run_id,
|
|
2137
|
+
input: JSON.stringify(t.continue_as_new.input),
|
|
2138
|
+
search: run.search,
|
|
2139
|
+
...run.parent_run_id !== void 0 ? { parent_run_id: run.parent_run_id } : {},
|
|
2140
|
+
...run.parent_step_id !== void 0 ? { parent_step_id: run.parent_step_id } : {}
|
|
2141
|
+
} };
|
|
2142
|
+
}
|
|
2143
|
+
/** A signal that arrived before anyone waited for it is delivered as soon as a wait opens. */
|
|
2144
|
+
async function pickUpBufferedSignals(ctx, tx, runId, t, nowMs) {
|
|
2145
|
+
const followUps = [];
|
|
2146
|
+
for (const wait of t.signal_waits) {
|
|
2147
|
+
const buffered = await tx.takeSignal(runId, wait.name);
|
|
2148
|
+
if (buffered === null) continue;
|
|
2149
|
+
await tx.markSignalDelivered(buffered.signal_id, wait.step_id, nowMs);
|
|
2150
|
+
await tx.removeSignalWait(runId, wait.step_id);
|
|
2151
|
+
followUps.push(signalEvent({
|
|
2152
|
+
runId,
|
|
2153
|
+
nowMs
|
|
2154
|
+
}, wait.step_id, await signalPayload(ctx, buffered)));
|
|
2155
|
+
}
|
|
2156
|
+
return followUps;
|
|
2157
|
+
}
|
|
2158
|
+
async function signalPayload(ctx, row) {
|
|
2159
|
+
if (row.payload !== void 0) return row.payload;
|
|
2160
|
+
if (row.payload_ref !== void 0) return readBlobText(ctx.blob, row.payload_ref);
|
|
2161
|
+
return "null";
|
|
2162
|
+
}
|
|
2163
|
+
/** The run identity the kernel folds against, taken from its row. */
|
|
2164
|
+
function runRef(run) {
|
|
2165
|
+
return {
|
|
2166
|
+
run_id: run.run_id,
|
|
2167
|
+
workflow: run.workflow,
|
|
2168
|
+
bundle_digest: run.component_digest,
|
|
2169
|
+
status: run.status,
|
|
2170
|
+
last_seq: run.last_seq,
|
|
2171
|
+
...run.parent_run_id !== void 0 ? { parent_run_id: run.parent_run_id } : {},
|
|
2172
|
+
...run.parent_step_id !== void 0 ? { parent_step_id: run.parent_step_id } : {}
|
|
2173
|
+
};
|
|
2174
|
+
}
|
|
2175
|
+
// src/host/task-dispatch.ts
|
|
2176
|
+
/**
|
|
2177
|
+
* The accept path a task takes on its way to a worker, shared by the two ways it can
|
|
2178
|
+
* leave the journal: the dispatcher pushing it, and a poller claiming it.
|
|
2179
|
+
*
|
|
2180
|
+
* Both do the same two things in the same order — build the push body, then commit
|
|
2181
|
+
* `task/running` together with the lease — so a pulled task is indistinguishable from a
|
|
2182
|
+
* pushed one to the kernel, the reaper and crash recovery.
|
|
2183
|
+
*/
|
|
2184
|
+
async function toPushedTask(ctx, task) {
|
|
2185
|
+
const inputJson = await inlineOrBlob(ctx, task.input, task.input_ref) ?? "null";
|
|
2186
|
+
const completeUrl = ctx.publicUrl === void 0 ? void 0 : `${ctx.publicUrl}${ctx.basePath ?? ""}/v1/tasks/${encodeURIComponent(task.task_id)}`;
|
|
2187
|
+
return {
|
|
2188
|
+
task_id: task.task_id,
|
|
2189
|
+
run_id: task.run_id,
|
|
2190
|
+
step_id: task.step_id,
|
|
2191
|
+
attempt: task.attempt,
|
|
2192
|
+
activity: {
|
|
2193
|
+
name: task.activity,
|
|
2194
|
+
...task.schema_ref !== void 0 ? { schema_ref: task.schema_ref } : {}
|
|
2195
|
+
},
|
|
2196
|
+
idempotency_key: task.idempotency_key,
|
|
2197
|
+
input: JSON.parse(inputJson),
|
|
2198
|
+
lease_ms: task.lease_ttl_ms,
|
|
2199
|
+
heartbeat_ms: Math.max(1e3, Math.floor(task.lease_ttl_ms / 3)),
|
|
2200
|
+
...task.timeout_ms !== void 0 ? { timeout_ms: task.timeout_ms } : {},
|
|
2201
|
+
...completeUrl !== void 0 ? { complete_url: completeUrl } : {}
|
|
2202
|
+
};
|
|
2203
|
+
}
|
|
2204
|
+
/** Records the dispatch: the `running` event and the lease commit together or not at all. */
|
|
2205
|
+
async function markTaskRunning(ctx, task, workerId) {
|
|
2206
|
+
const nowMs = ctx.now();
|
|
2207
|
+
await applyEvent(ctx, task.run_id, taskRunningEvent({
|
|
2208
|
+
runId: task.run_id,
|
|
2209
|
+
nowMs
|
|
2210
|
+
}, task.step_id, task.attempt), async (tx) => {
|
|
2211
|
+
await tx.markDispatched(task.task_id, task.attempt, nowMs, nowMs + task.lease_ttl_ms, workerId);
|
|
2212
|
+
});
|
|
2213
|
+
}
|
|
2214
|
+
/** A payload column: inline text, or the blob it was offloaded to. */
|
|
2215
|
+
async function inlineOrBlob(ctx, inline, ref) {
|
|
2216
|
+
if (inline !== void 0) return inline;
|
|
2217
|
+
if (ref !== void 0) return readBlobText(ctx.blob, ref);
|
|
2218
|
+
}
|
|
2219
|
+
// src/host/api/poll.ts
|
|
2220
|
+
const MAX_WAIT_MS = 25e3;
|
|
2221
|
+
const MAX_TASKS = 10;
|
|
2222
|
+
const RECHECK_MS = 500;
|
|
2223
|
+
/** A claim only has to outlive the accept below; the lease takes over from there. */
|
|
2224
|
+
const CLAIM_HOLD_MS = 3e4;
|
|
2225
|
+
async function postPoll(ctx, request) {
|
|
2226
|
+
const body = asObject(await readJson(request));
|
|
2227
|
+
return json({ tasks: await pollQueue(ctx, {
|
|
2228
|
+
queue: requireString(body, "queue"),
|
|
2229
|
+
workerId: requireString(body, "worker_id"),
|
|
2230
|
+
waitMs: bounded(body.wait_ms, 0, MAX_WAIT_MS),
|
|
2231
|
+
max: bounded(body.max, 1, MAX_TASKS)
|
|
2232
|
+
}) });
|
|
2233
|
+
}
|
|
2234
|
+
async function pollQueue(ctx, o) {
|
|
2235
|
+
const deadline = Date.now() + o.waitMs;
|
|
2236
|
+
for (;;) {
|
|
2237
|
+
const accepted = await accept(ctx, await ctx.journal.transaction((tx) => tx.claimUndispatchedTasks(ctx.now(), o.max, CLAIM_HOLD_MS, { queue: o.queue })), o.workerId);
|
|
2238
|
+
if (accepted.length > 0) return accepted;
|
|
2239
|
+
const remaining = deadline - Date.now();
|
|
2240
|
+
if (remaining <= 0) return [];
|
|
2241
|
+
await waitForWork(ctx, o.queue, Math.min(remaining, RECHECK_MS));
|
|
2242
|
+
}
|
|
2243
|
+
}
|
|
2244
|
+
/**
|
|
2245
|
+
* Records each claimed task as running before handing it over, exactly as a push does.
|
|
2246
|
+
* A task whose accept fails is left claimed; the hold lapses and it comes back.
|
|
2247
|
+
*/
|
|
2248
|
+
async function accept(ctx, tasks, workerId) {
|
|
2249
|
+
const accepted = [];
|
|
2250
|
+
for (const task of tasks) try {
|
|
2251
|
+
const pushed = await toPushedTask(ctx, task);
|
|
2252
|
+
await markTaskRunning(ctx, task, workerId);
|
|
2253
|
+
accepted.push(pushed);
|
|
2254
|
+
} catch (error) {
|
|
2255
|
+
ctx.events.emit("warning", {
|
|
2256
|
+
message: `could not hand out task ${task.task_id}`,
|
|
2257
|
+
error
|
|
2258
|
+
});
|
|
2259
|
+
}
|
|
2260
|
+
return accepted;
|
|
2261
|
+
}
|
|
2262
|
+
/** Resolves on the timeout, or as soon as this process commits a task for the queue. */
|
|
2263
|
+
function waitForWork(ctx, queue, timeoutMs) {
|
|
2264
|
+
return new Promise((resolve) => {
|
|
2265
|
+
const done = () => {
|
|
2266
|
+
clearTimeout(timer);
|
|
2267
|
+
ctx.events.off("task_scheduled", onScheduled);
|
|
2268
|
+
resolve();
|
|
2269
|
+
};
|
|
2270
|
+
const onScheduled = (message) => {
|
|
2271
|
+
if (message.queue === queue) done();
|
|
2272
|
+
};
|
|
2273
|
+
const timer = setTimeout(done, timeoutMs);
|
|
2274
|
+
timer.unref();
|
|
2275
|
+
ctx.events.on("task_scheduled", onScheduled);
|
|
2276
|
+
});
|
|
2277
|
+
}
|
|
2278
|
+
function bounded(value, min, max) {
|
|
2279
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return min;
|
|
2280
|
+
return Math.min(Math.max(Math.floor(value), min), max);
|
|
2281
|
+
}
|
|
2282
|
+
// src/host/runs.ts
|
|
2283
|
+
/**
|
|
2284
|
+
* Run-level operations behind the API: start, signal, cancel, read.
|
|
2285
|
+
*
|
|
2286
|
+
* `startRun` only writes a `created` row. The `started` event is folded by the dispatcher's
|
|
2287
|
+
* start-runs stage, so there is exactly one code path into a run's first transition and a
|
|
2288
|
+
* crash between "row written" and "run started" is recovered by the outbox rather than lost.
|
|
2289
|
+
*/
|
|
2290
|
+
/**
|
|
2291
|
+
* Writes a `created` run row and kicks the dispatcher; the `started` event is folded by the
|
|
2292
|
+
* outbox. Idempotent on `runId`. Runs on a host with the `api` role.
|
|
2293
|
+
*
|
|
2294
|
+
* @throws {@link WorkflowRejected} when the workflow is not registered.
|
|
2295
|
+
*/
|
|
2296
|
+
async function startRun(ctx, opts) {
|
|
2297
|
+
const workflow = ctx.workflows.get(opts.workflow);
|
|
2298
|
+
if (workflow === void 0) throw new WorkflowRejected(opts.workflow);
|
|
2299
|
+
const runId = opts.runId ?? `run_${randomHex()}`;
|
|
2300
|
+
await ctx.journal.transaction((tx) => tx.createRun({
|
|
2301
|
+
run_id: runId,
|
|
2302
|
+
namespace: opts.namespace ?? ctx.namespace,
|
|
2303
|
+
workflow: workflow.name,
|
|
2304
|
+
component_digest: workflow.digest,
|
|
2305
|
+
status: "created",
|
|
2306
|
+
input: JSON.stringify(opts.input ?? null),
|
|
2307
|
+
...opts.search !== void 0 ? { search: opts.search } : {}
|
|
2308
|
+
}, ctx.now()));
|
|
2309
|
+
ctx.kick();
|
|
2310
|
+
return { run_id: runId };
|
|
2311
|
+
}
|
|
2312
|
+
/**
|
|
2313
|
+
* Stores a signal and, when the run is waiting on that name, delivers it in the same
|
|
2314
|
+
* transaction. Validated against the registered signal schema when there is one. Never
|
|
2315
|
+
* answers 409 for an ended run: the signal is stored and reported as not delivered.
|
|
2316
|
+
*
|
|
2317
|
+
* @throws {@link BadRequest} when the payload fails the schema.
|
|
2318
|
+
* @throws {@link RunNotFound} when no run has that id.
|
|
2319
|
+
*/
|
|
2320
|
+
async function signalRun(ctx, runId, name, payload) {
|
|
2321
|
+
const definition = ctx.signals.get(name);
|
|
2322
|
+
let value = payload;
|
|
2323
|
+
if (definition !== void 0) {
|
|
2324
|
+
const parsed = definition.schema.safeParse(payload);
|
|
2325
|
+
if (!parsed.success) throw new BadRequest(`signal "${name}" payload is invalid: ${parsed.error.message}`);
|
|
2326
|
+
value = parsed.data;
|
|
2327
|
+
}
|
|
2328
|
+
const row = {
|
|
2329
|
+
signal_id: `sig_${randomHex()}`,
|
|
2330
|
+
run_id: runId,
|
|
2331
|
+
name,
|
|
2332
|
+
payload: JSON.stringify(value ?? null)
|
|
2333
|
+
};
|
|
2334
|
+
let matched;
|
|
2335
|
+
try {
|
|
2336
|
+
const outcome = await applyEvent(ctx, runId, async (tx) => {
|
|
2337
|
+
const nowMs = ctx.now();
|
|
2338
|
+
await tx.putSignal(row, nowMs);
|
|
2339
|
+
const wait = (await tx.getSignalWaits(runId)).find((w) => w.name === name);
|
|
2340
|
+
if (wait === void 0) return null;
|
|
2341
|
+
matched = wait.step_id;
|
|
2342
|
+
await tx.markSignalDelivered(row.signal_id, wait.step_id, nowMs);
|
|
2343
|
+
await tx.removeSignalWait(runId, wait.step_id);
|
|
2344
|
+
return signalEvent({
|
|
2345
|
+
runId,
|
|
2346
|
+
nowMs
|
|
2347
|
+
}, wait.step_id, row.payload ?? "null");
|
|
2348
|
+
});
|
|
2349
|
+
return {
|
|
2350
|
+
signal_id: row.signal_id,
|
|
2351
|
+
delivered: outcome.applied
|
|
2352
|
+
};
|
|
2353
|
+
} catch (error) {
|
|
2354
|
+
if (matched === void 0 || !isStepGone(error)) throw error;
|
|
2355
|
+
await recordLateSignal(ctx, row, matched);
|
|
2356
|
+
return {
|
|
2357
|
+
signal_id: row.signal_id,
|
|
2358
|
+
delivered: false
|
|
2359
|
+
};
|
|
2360
|
+
}
|
|
2361
|
+
}
|
|
2362
|
+
function recordLateSignal(ctx, row, stepId) {
|
|
2363
|
+
return ctx.journal.transaction(async (tx) => {
|
|
2364
|
+
const nowMs = ctx.now();
|
|
2365
|
+
await tx.putSignal(row, nowMs);
|
|
2366
|
+
await tx.markSignalDelivered(row.signal_id, stepId, nowMs);
|
|
2367
|
+
await tx.removeSignalWait(row.run_id, stepId);
|
|
2368
|
+
});
|
|
2369
|
+
}
|
|
2370
|
+
/**
|
|
2371
|
+
* Folds a `cancel` marker and returns the run. Cancelling an ended run is a no-op that
|
|
2372
|
+
* still returns the view.
|
|
2373
|
+
*
|
|
2374
|
+
* @throws {@link RunNotFound} when no run has that id.
|
|
2375
|
+
*/
|
|
2376
|
+
async function cancelRun(ctx, runId) {
|
|
2377
|
+
await applyEvent(ctx, runId, cancelEvent({
|
|
2378
|
+
runId,
|
|
2379
|
+
nowMs: ctx.now()
|
|
2380
|
+
}));
|
|
2381
|
+
return getRunView(ctx, runId);
|
|
2382
|
+
}
|
|
2383
|
+
/**
|
|
2384
|
+
* Reads one run, inlining an offloaded output.
|
|
2385
|
+
*
|
|
2386
|
+
* @throws {@link RunNotFound} when no run has that id.
|
|
2387
|
+
*/
|
|
2388
|
+
async function getRunView(ctx, runId) {
|
|
2389
|
+
const row = await ctx.journal.getRun(runId);
|
|
2390
|
+
if (row === null) throw new RunNotFound(runId);
|
|
2391
|
+
return toView(ctx, row);
|
|
2392
|
+
}
|
|
2393
|
+
/** Lists runs in the host's namespace unless `query.namespace` says otherwise. */
|
|
2394
|
+
async function listRuns(ctx, query) {
|
|
2395
|
+
const rows = await ctx.journal.query({
|
|
2396
|
+
namespace: ctx.namespace,
|
|
2397
|
+
...query
|
|
2398
|
+
});
|
|
2399
|
+
return Promise.all(rows.map((row) => toView(ctx, row)));
|
|
2400
|
+
}
|
|
2401
|
+
/** Journaled events with `seq > sinceSeq`, ascending. Empty for an unknown run. */
|
|
2402
|
+
function readRunEvents(ctx, runId, sinceSeq) {
|
|
2403
|
+
return ctx.journal.readEvents(runId, sinceSeq);
|
|
2404
|
+
}
|
|
2405
|
+
async function toView(ctx, row) {
|
|
2406
|
+
const outputJson = row.output ?? (row.output_ref !== void 0 ? await readBlobText(ctx.blob, row.output_ref) : void 0);
|
|
2407
|
+
const failure = row.status === "failed" ? await failureOf(ctx, row) : {};
|
|
2408
|
+
return {
|
|
2409
|
+
run_id: row.run_id,
|
|
2410
|
+
workflow: row.workflow,
|
|
2411
|
+
status: row.status,
|
|
2412
|
+
last_seq: row.last_seq,
|
|
2413
|
+
search: row.search,
|
|
2414
|
+
created_at_ms: row.created_at_ms,
|
|
2415
|
+
updated_at_ms: row.updated_at_ms,
|
|
2416
|
+
...row.started_at_ms !== void 0 ? { started_at_ms: row.started_at_ms } : {},
|
|
2417
|
+
...row.closed_at_ms !== void 0 ? { closed_at_ms: row.closed_at_ms } : {},
|
|
2418
|
+
...row.parent_run_id !== void 0 ? { parent_run_id: row.parent_run_id } : {},
|
|
2419
|
+
...row.continued_from !== void 0 ? { continued_from: row.continued_from } : {},
|
|
2420
|
+
...row.continued_to !== void 0 ? { continued_to: row.continued_to } : {},
|
|
2421
|
+
...outputJson !== void 0 ? { output: JSON.parse(outputJson) } : {},
|
|
2422
|
+
...failure
|
|
2423
|
+
};
|
|
2424
|
+
}
|
|
2425
|
+
/**
|
|
2426
|
+
* A failed run's last event is its closing marker (`fail` or `nondeterminism`), so one
|
|
2427
|
+
* read of `seq > last_seq - 1` gives the reason. Live runs never pay for it.
|
|
2428
|
+
*/
|
|
2429
|
+
async function failureOf(ctx, row) {
|
|
2430
|
+
const [last] = await ctx.journal.readEvents(row.run_id, Math.max(0, row.last_seq - 1));
|
|
2431
|
+
if (last === void 0 || last.kind !== "marker" || last.error === void 0) return {};
|
|
2432
|
+
return {
|
|
2433
|
+
error: last.error,
|
|
2434
|
+
...last.cause !== void 0 ? { cause: last.cause } : {}
|
|
2435
|
+
};
|
|
2436
|
+
}
|
|
2437
|
+
// src/host/api/runs.ts
|
|
2438
|
+
async function createRun(ctx, request) {
|
|
2439
|
+
const body = asObject(await readJson(request));
|
|
2440
|
+
return json(await startRun(ctx, {
|
|
2441
|
+
workflow: requireString(body, "workflow"),
|
|
2442
|
+
input: body.input ?? null,
|
|
2443
|
+
...typeof body.run_id === "string" ? { runId: body.run_id } : {},
|
|
2444
|
+
...isRecord(body.search) ? { search: body.search } : {}
|
|
2445
|
+
}), 201);
|
|
2446
|
+
}
|
|
2447
|
+
async function showRun(ctx, runId) {
|
|
2448
|
+
return json(await getRunView(ctx, runId));
|
|
2449
|
+
}
|
|
2450
|
+
async function showEvents(ctx, runId, url) {
|
|
2451
|
+
const since = Number(url.searchParams.get("since") ?? 0);
|
|
2452
|
+
return json(await readRunEvents(ctx, runId, Number.isFinite(since) ? since : 0));
|
|
2453
|
+
}
|
|
2454
|
+
async function postSignal(ctx, runId, name, request) {
|
|
2455
|
+
return json(await signalRun(ctx, runId, name, await readJson(request)));
|
|
2456
|
+
}
|
|
2457
|
+
async function postCancel(ctx, runId) {
|
|
2458
|
+
return json(await cancelRun(ctx, runId));
|
|
2459
|
+
}
|
|
2460
|
+
async function indexRuns(ctx, url) {
|
|
2461
|
+
const status = url.searchParams.get("status");
|
|
2462
|
+
const workflow = url.searchParams.get("workflow");
|
|
2463
|
+
const limit = Number(url.searchParams.get("limit") ?? 50);
|
|
2464
|
+
return json(await listRuns(ctx, {
|
|
2465
|
+
...status !== null ? { status } : {},
|
|
2466
|
+
...workflow !== null ? { workflow } : {},
|
|
2467
|
+
...Number.isInteger(limit) && limit > 0 ? { limit } : {}
|
|
2468
|
+
}));
|
|
2469
|
+
}
|
|
2470
|
+
function isRecord(value) {
|
|
2471
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2472
|
+
}
|
|
2473
|
+
// src/host/api/stream.ts
|
|
2474
|
+
const KEEPALIVE_MS = 15e3;
|
|
2475
|
+
async function streamRunEvents(ctx, runId, url, request) {
|
|
2476
|
+
if (await ctx.journal.getRun(runId) === null) throw new RunNotFound(runId);
|
|
2477
|
+
const since = sinceOf(url, request.headers);
|
|
2478
|
+
const encoder = new TextEncoder();
|
|
2479
|
+
const stream = new ReadableStream({ start(controller) {
|
|
2480
|
+
let open = true;
|
|
2481
|
+
const send = (frame) => {
|
|
2482
|
+
if (!open) return;
|
|
2483
|
+
try {
|
|
2484
|
+
controller.enqueue(encoder.encode(frame));
|
|
2485
|
+
} catch {
|
|
2486
|
+
open = false;
|
|
2487
|
+
}
|
|
2488
|
+
};
|
|
2489
|
+
const onEmit = (message) => {
|
|
2490
|
+
if (message.run_id !== runId) return;
|
|
2491
|
+
send(frame("emit", JSON.stringify({
|
|
2492
|
+
channel: message.channel,
|
|
2493
|
+
data: message.data
|
|
2494
|
+
})));
|
|
2495
|
+
};
|
|
2496
|
+
ctx.events.on("emit", onEmit);
|
|
2497
|
+
const keepalive = setInterval(() => send(": keepalive\n\n"), KEEPALIVE_MS);
|
|
2498
|
+
keepalive.unref();
|
|
2499
|
+
const finish = () => {
|
|
2500
|
+
if (!open) return;
|
|
2501
|
+
open = false;
|
|
2502
|
+
clearInterval(keepalive);
|
|
2503
|
+
ctx.events.off("emit", onEmit);
|
|
2504
|
+
try {
|
|
2505
|
+
controller.close();
|
|
2506
|
+
} catch {}
|
|
2507
|
+
};
|
|
2508
|
+
request.signal.addEventListener("abort", finish, { once: true });
|
|
2509
|
+
tail(ctx, runId, since, send, () => open).finally(finish);
|
|
2510
|
+
} });
|
|
2511
|
+
return new Response(stream, { headers: {
|
|
2512
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
2513
|
+
"cache-control": "no-cache, no-transform",
|
|
2514
|
+
connection: "keep-alive",
|
|
2515
|
+
"x-accel-buffering": "no"
|
|
2516
|
+
} });
|
|
2517
|
+
}
|
|
2518
|
+
/** Replays from `since`, then follows the journal until the run is terminal. */
|
|
2519
|
+
async function tail(ctx, runId, since, send, open) {
|
|
2520
|
+
let lastSeq = since;
|
|
2521
|
+
for (;;) {
|
|
2522
|
+
const events = await ctx.journal.readEvents(runId, lastSeq);
|
|
2523
|
+
for (const envelope of events) {
|
|
2524
|
+
send(frame("journal", JSON.stringify(envelope), envelope.seq));
|
|
2525
|
+
lastSeq = envelope.seq;
|
|
2526
|
+
}
|
|
2527
|
+
if (!open()) return;
|
|
2528
|
+
const run = await ctx.journal.getRun(runId);
|
|
2529
|
+
if (run !== null && isTerminalRun(run.status) && run.last_seq <= lastSeq) {
|
|
2530
|
+
send(frame("end", JSON.stringify(await getRunView(ctx, runId))));
|
|
2531
|
+
return;
|
|
2532
|
+
}
|
|
2533
|
+
await sleep(ctx.streamPollMs);
|
|
2534
|
+
if (!open()) return;
|
|
2535
|
+
}
|
|
2536
|
+
}
|
|
2537
|
+
function frame(event, data, id) {
|
|
2538
|
+
return `${id === void 0 ? "" : `id: ${id}\n`}event: ${event}\ndata: ${data}\n\n`;
|
|
2539
|
+
}
|
|
2540
|
+
/** `?since` wins over `Last-Event-ID`, so an explicit replay beats a reconnect. */
|
|
2541
|
+
function sinceOf(url, headers) {
|
|
2542
|
+
const explicit = Number(url.searchParams.get("since"));
|
|
2543
|
+
if (Number.isFinite(explicit) && explicit > 0) return explicit;
|
|
2544
|
+
const resumed = Number(headers.get("last-event-id"));
|
|
2545
|
+
return Number.isFinite(resumed) && resumed > 0 ? resumed : 0;
|
|
2546
|
+
}
|
|
2547
|
+
function sleep(ms) {
|
|
2548
|
+
return new Promise((resolve) => {
|
|
2549
|
+
setTimeout(resolve, ms).unref();
|
|
2550
|
+
});
|
|
2551
|
+
}
|
|
2552
|
+
/** True when the caller asked for a stream rather than the JSON array. */
|
|
2553
|
+
function wantsStream(request, url) {
|
|
2554
|
+
if (url.searchParams.get("stream") === "1") return true;
|
|
2555
|
+
return (request.headers.get("accept") ?? "").includes("text/event-stream");
|
|
2556
|
+
}
|
|
2557
|
+
// src/host/worker/complete.ts
|
|
2558
|
+
const DUPLICATE = { duplicate: true };
|
|
2559
|
+
const APPLIED = { duplicate: false };
|
|
2560
|
+
const TERMINAL_TASK = /* @__PURE__ */ new Set([
|
|
2561
|
+
"succeeded",
|
|
2562
|
+
"failed",
|
|
2563
|
+
"cancelled"
|
|
2564
|
+
]);
|
|
2565
|
+
/**
|
|
2566
|
+
* Records an attempt's output. Validated against the registered activity's output schema
|
|
2567
|
+
* when there is one; a violation fails the attempt with `schema_violation` and no retry.
|
|
2568
|
+
* The first terminal result for an attempt wins; later ones return `duplicate: true`.
|
|
2569
|
+
*
|
|
2570
|
+
* @throws {@link TaskNotFound} when no task has that id.
|
|
2571
|
+
*/
|
|
2572
|
+
async function completeTask(ctx, taskId, attempt, output, usage) {
|
|
2573
|
+
const task = await liveTask(ctx, taskId, attempt);
|
|
2574
|
+
if (task === null) return DUPLICATE;
|
|
2575
|
+
const activity = ctx.activities.get(task.activity);
|
|
2576
|
+
if (activity === void 0) return submit(ctx, task, JSON.stringify(output ?? null), usage);
|
|
2577
|
+
const parsed = activity.output.safeParse(output);
|
|
2578
|
+
if (!parsed.success) return failValidation(ctx, task, issuesOf(parsed.error.issues), usage);
|
|
2579
|
+
return submit(ctx, task, JSON.stringify(parsed.data ?? null), usage);
|
|
2580
|
+
}
|
|
2581
|
+
/**
|
|
2582
|
+
* Records an attempt's failure: a `retrying` event when `retryable` and the kernel's retry
|
|
2583
|
+
* plan allows another attempt, otherwise a `failed` event. The first terminal result for an
|
|
2584
|
+
* attempt wins; later ones return `duplicate: true`.
|
|
2585
|
+
*
|
|
2586
|
+
* `cause` names who lost the attempt: the handler by default, the reaper on a dead lease.
|
|
2587
|
+
* `usage` is banked whichever way the attempt ends — tokens burned before a throw are spent.
|
|
2588
|
+
*
|
|
2589
|
+
* @throws {@link TaskNotFound} when no task has that id.
|
|
2590
|
+
*/
|
|
2591
|
+
async function failTask(ctx, taskId, attempt, error, retryable = true, cause = "app_error", usage) {
|
|
2592
|
+
const task = await liveTask(ctx, taskId, attempt);
|
|
2593
|
+
if (task === null) return DUPLICATE;
|
|
2594
|
+
const nowMs = ctx.now();
|
|
2595
|
+
const base = {
|
|
2596
|
+
runId: task.run_id,
|
|
2597
|
+
nowMs
|
|
2598
|
+
};
|
|
2599
|
+
if (retryable) {
|
|
2600
|
+
const plan = ctx.kernel.planRetry({
|
|
2601
|
+
policy: task.retry_policy,
|
|
2602
|
+
attempt,
|
|
2603
|
+
cause,
|
|
2604
|
+
random: randomHex()
|
|
2605
|
+
});
|
|
2606
|
+
if (plan.ok && plan.value.retry) {
|
|
2607
|
+
await applyEvent(ctx, task.run_id, taskRetryingEvent(base, task.step_id, plan.value.next_attempt, cause, plan.value.delay_ms, error, usage));
|
|
2608
|
+
return APPLIED;
|
|
2609
|
+
}
|
|
2610
|
+
}
|
|
2611
|
+
await applyEvent(ctx, task.run_id, taskFailedEvent(base, task.step_id, attempt, cause, error, usage));
|
|
2612
|
+
return APPLIED;
|
|
2613
|
+
}
|
|
2614
|
+
/**
|
|
2615
|
+
* Extends the attempt's lease by the task's `lease_ttl_ms` from now.
|
|
2616
|
+
*
|
|
2617
|
+
* @throws {@link TaskNotFound} when no task has that id.
|
|
2618
|
+
* @throws {@link LeaseLost} when the task is not running at that attempt any more.
|
|
2619
|
+
*/
|
|
2620
|
+
async function heartbeatTask(ctx, taskId, attempt) {
|
|
2621
|
+
const task = await ctx.journal.getTask(taskId);
|
|
2622
|
+
if (task === null) throw new TaskNotFound(taskId);
|
|
2623
|
+
const nowMs = ctx.now();
|
|
2624
|
+
if (!await ctx.journal.transaction((tx) => tx.heartbeat(taskId, attempt, nowMs + task.lease_ttl_ms, nowMs))) throw new LeaseLost(taskId, attempt);
|
|
2625
|
+
}
|
|
2626
|
+
/** The task row when this attempt may still produce a result, else null (a redelivery). */
|
|
2627
|
+
async function liveTask(ctx, taskId, attempt) {
|
|
2628
|
+
const task = await ctx.journal.getTask(taskId);
|
|
2629
|
+
if (task === null) throw new TaskNotFound(taskId);
|
|
2630
|
+
if (task.attempt !== attempt || TERMINAL_TASK.has(task.status)) return null;
|
|
2631
|
+
return task;
|
|
2632
|
+
}
|
|
2633
|
+
function submit(ctx, task, outputJson, usage) {
|
|
2634
|
+
const event = taskSucceededEvent({
|
|
2635
|
+
runId: task.run_id,
|
|
2636
|
+
nowMs: ctx.now()
|
|
2637
|
+
}, task.step_id, task.attempt, outputJson, task.schema_ref, usage);
|
|
2638
|
+
return applyEvent(ctx, task.run_id, event).then(() => APPLIED);
|
|
2639
|
+
}
|
|
2640
|
+
/** A schema violation is the worker's fault, not a flake: the kernel never retries it. */
|
|
2641
|
+
async function failValidation(ctx, task, detail, usage) {
|
|
2642
|
+
await applyEvent(ctx, task.run_id, taskFailedEvent({
|
|
2643
|
+
runId: task.run_id,
|
|
2644
|
+
nowMs: ctx.now()
|
|
2645
|
+
}, task.step_id, task.attempt, "schema_violation", `activity "${task.activity}" returned an invalid output: ${detail}`, usage));
|
|
2646
|
+
return APPLIED;
|
|
2647
|
+
}
|
|
2648
|
+
function issuesOf(issues) {
|
|
2649
|
+
return issues.map((issue) => `${issue.path.map(String).join(".") || "<root>"}: ${issue.message}`).join("; ");
|
|
2650
|
+
}
|
|
2651
|
+
// src/host/worker/handle-task.ts
|
|
2652
|
+
/**
|
|
2653
|
+
* Runs one pushed task on a worker and reports exactly one terminal result. Heartbeats every
|
|
2654
|
+
* `heartbeat_ms`; a refused heartbeat, `timeout_ms` elapsing or `options.signal` aborting
|
|
2655
|
+
* all abort the handler's `ctx.signal`. A handler throw is reported as a retryable failure;
|
|
2656
|
+
* a missing handler as a non-retryable one. Resolves once the result was reported, and
|
|
2657
|
+
* rejects only when the reporter itself fails.
|
|
2658
|
+
*/
|
|
2659
|
+
async function handleTask(worker, task, reporter, options = {}) {
|
|
2660
|
+
const handler = worker.handlers.get(task.activity.name);
|
|
2661
|
+
if (handler === void 0) {
|
|
2662
|
+
await reporter.fail(task.task_id, task.attempt, `no handler for activity "${task.activity.name}"`, false);
|
|
2663
|
+
return;
|
|
2664
|
+
}
|
|
2665
|
+
const spend = usageTally();
|
|
2666
|
+
const controller = new AbortController();
|
|
2667
|
+
const stop = () => controller.abort();
|
|
2668
|
+
options.signal?.addEventListener("abort", stop, { once: true });
|
|
2669
|
+
let reported = false;
|
|
2670
|
+
/** The first terminal result wins; anything later is a loser of the race. */
|
|
2671
|
+
const report = (send) => {
|
|
2672
|
+
if (reported) return Promise.resolve();
|
|
2673
|
+
reported = true;
|
|
2674
|
+
return send();
|
|
2675
|
+
};
|
|
2676
|
+
const heartbeat = () => reporter.heartbeat(task.task_id, task.attempt);
|
|
2677
|
+
const beat = task.heartbeat_ms > 0 ? setInterval(() => {
|
|
2678
|
+
heartbeat().catch(stop);
|
|
2679
|
+
}, task.heartbeat_ms) : void 0;
|
|
2680
|
+
beat?.unref();
|
|
2681
|
+
const finished = (async () => {
|
|
2682
|
+
try {
|
|
2683
|
+
const output = await handler(task.input, {
|
|
2684
|
+
taskId: task.task_id,
|
|
2685
|
+
runId: task.run_id,
|
|
2686
|
+
attempt: task.attempt,
|
|
2687
|
+
heartbeat,
|
|
2688
|
+
reportUsage: spend.add,
|
|
2689
|
+
signal: controller.signal
|
|
2690
|
+
});
|
|
2691
|
+
await report(() => reporter.complete(task.task_id, task.attempt, output, spend.total()));
|
|
2692
|
+
} catch (error) {
|
|
2693
|
+
await report(() => reporter.fail(task.task_id, task.attempt, messageOf(error), true, spend.total()));
|
|
2694
|
+
}
|
|
2695
|
+
})();
|
|
2696
|
+
try {
|
|
2697
|
+
await raceTimeout(finished, task.timeout_ms, async () => {
|
|
2698
|
+
stop();
|
|
2699
|
+
await report(() => reporter.fail(task.task_id, task.attempt, `activity "${task.activity.name}" timed out after ${String(task.timeout_ms)} ms`, true, spend.total(), "timeout"));
|
|
2700
|
+
});
|
|
2701
|
+
} finally {
|
|
2702
|
+
if (beat !== void 0) clearInterval(beat);
|
|
2703
|
+
options.signal?.removeEventListener("abort", stop);
|
|
2704
|
+
}
|
|
2705
|
+
}
|
|
2706
|
+
/**
|
|
2707
|
+
* Resolves on whichever comes first: the handler settling, or the timeout reporting. A
|
|
2708
|
+
* handler that ignores `ctx.signal` keeps running, but it no longer owns the attempt.
|
|
2709
|
+
*/
|
|
2710
|
+
function raceTimeout(finished, timeoutMs, onTimeout) {
|
|
2711
|
+
if (timeoutMs === void 0 || timeoutMs <= 0) return finished;
|
|
2712
|
+
return new Promise((resolve, reject) => {
|
|
2713
|
+
const timer = setTimeout(() => {
|
|
2714
|
+
onTimeout().then(resolve, reject);
|
|
2715
|
+
}, timeoutMs);
|
|
2716
|
+
timer.unref();
|
|
2717
|
+
finished.then(() => {
|
|
2718
|
+
clearTimeout(timer);
|
|
2719
|
+
resolve();
|
|
2720
|
+
}, (error) => {
|
|
2721
|
+
clearTimeout(timer);
|
|
2722
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
2723
|
+
});
|
|
2724
|
+
});
|
|
2725
|
+
}
|
|
2726
|
+
function usageTally() {
|
|
2727
|
+
const total = {
|
|
2728
|
+
cpu_ms: 0,
|
|
2729
|
+
tokens: 0,
|
|
2730
|
+
cost_micro_usd: 0
|
|
2731
|
+
};
|
|
2732
|
+
let touched = false;
|
|
2733
|
+
return {
|
|
2734
|
+
add(usage) {
|
|
2735
|
+
touched = true;
|
|
2736
|
+
total.cpu_ms += whole(usage.cpuMs);
|
|
2737
|
+
total.tokens += whole(usage.tokens);
|
|
2738
|
+
total.cost_micro_usd += whole(usage.costMicroUsd);
|
|
2739
|
+
},
|
|
2740
|
+
total: () => touched ? { ...total } : void 0
|
|
2741
|
+
};
|
|
2742
|
+
}
|
|
2743
|
+
/** `Usage` is hashed into the kernel state, so it is integers only and never negative. */
|
|
2744
|
+
function whole(value) {
|
|
2745
|
+
if (value === void 0 || !Number.isFinite(value)) return 0;
|
|
2746
|
+
return Math.max(0, Math.trunc(value));
|
|
2747
|
+
}
|
|
2748
|
+
function messageOf(error) {
|
|
2749
|
+
if (error instanceof Error) return error.message;
|
|
2750
|
+
return String(error);
|
|
2751
|
+
}
|
|
2752
|
+
// src/host/worker/reporters.ts
|
|
2753
|
+
/** Reports straight into this host's journal via {@link completeTask}, {@link failTask} and {@link heartbeatTask}. */
|
|
2754
|
+
function localReporter(ctx) {
|
|
2755
|
+
return {
|
|
2756
|
+
async complete(taskId, attempt, output, usage) {
|
|
2757
|
+
await completeTask(ctx, taskId, attempt, output, usage);
|
|
2758
|
+
},
|
|
2759
|
+
async fail(taskId, attempt, error, retryable, usage, cause) {
|
|
2760
|
+
await failTask(ctx, taskId, attempt, error, retryable, cause ?? "app_error", usage);
|
|
2761
|
+
},
|
|
2762
|
+
heartbeat: (taskId, attempt) => heartbeatTask(ctx, taskId, attempt)
|
|
2763
|
+
};
|
|
2764
|
+
}
|
|
2765
|
+
/**
|
|
2766
|
+
* Reports over HTTP to the host that owns the task. `completeUrl` is the task's base URL
|
|
2767
|
+
* (`…/v1/tasks/{id}`); the three verbs hang off it. Each call has a 10 s timeout and throws
|
|
2768
|
+
* a plain `Error` on a non-2xx answer, which for `heartbeat` is how a lost lease surfaces.
|
|
2769
|
+
*/
|
|
2770
|
+
function remoteReporter(completeUrl, token, fetchImpl = globalThis.fetch) {
|
|
2771
|
+
const post = async (verb, body) => {
|
|
2772
|
+
const response = await fetchImpl(`${completeUrl}/${verb}`, {
|
|
2773
|
+
method: "POST",
|
|
2774
|
+
headers: {
|
|
2775
|
+
"content-type": "application/json",
|
|
2776
|
+
...token !== void 0 ? { authorization: `Bearer ${token}` } : {}
|
|
2777
|
+
},
|
|
2778
|
+
body: JSON.stringify(body),
|
|
2779
|
+
signal: AbortSignal.timeout(1e4)
|
|
2780
|
+
});
|
|
2781
|
+
if (!response.ok) throw new Error(`task ${verb} failed: ${response.status} ${await response.text()}`);
|
|
2782
|
+
};
|
|
2783
|
+
return {
|
|
2784
|
+
complete: (_taskId, attempt, output, usage) => post("complete", {
|
|
2785
|
+
attempt,
|
|
2786
|
+
output,
|
|
2787
|
+
...usage !== void 0 ? { usage } : {}
|
|
2788
|
+
}),
|
|
2789
|
+
fail: (_taskId, attempt, error, retryable, usage, cause) => post("fail", {
|
|
2790
|
+
attempt,
|
|
2791
|
+
error,
|
|
2792
|
+
retryable,
|
|
2793
|
+
...usage !== void 0 ? { usage } : {},
|
|
2794
|
+
...cause !== void 0 ? { cause } : {}
|
|
2795
|
+
}),
|
|
2796
|
+
heartbeat: (_taskId, attempt) => post("heartbeat", { attempt })
|
|
2797
|
+
};
|
|
2798
|
+
}
|
|
2799
|
+
// src/host/worker/signature.ts
|
|
2800
|
+
/**
|
|
2801
|
+
* Push signatures. Same shape as the repo's Zernio webhook verifier: HMAC-SHA256, hex,
|
|
2802
|
+
* compared timing-safe — but the signed string binds the task and a timestamp as well as
|
|
2803
|
+
* the body, so a captured push cannot be replayed onto a different attempt or an hour later.
|
|
2804
|
+
*/
|
|
2805
|
+
/** Header carrying the pushed task's id. */
|
|
2806
|
+
const TASK_ID_HEADER = "vlo-task-id";
|
|
2807
|
+
/** Header carrying the attempt number. */
|
|
2808
|
+
const ATTEMPT_HEADER = "vlo-attempt";
|
|
2809
|
+
/** Header carrying the signing time, epoch milliseconds. */
|
|
2810
|
+
const TIMESTAMP_HEADER = "vlo-timestamp";
|
|
2811
|
+
/** Header carrying the signature, `v1=<hex>`. */
|
|
2812
|
+
const SIGNATURE_HEADER = "vlo-signature";
|
|
2813
|
+
const PREFIX = "v1=";
|
|
2814
|
+
const WINDOW_MS = 3e5;
|
|
2815
|
+
function digest(secret, taskId, attempt, tsMs, body) {
|
|
2816
|
+
const bodyHash = createHash("sha256").update(body, "utf8").digest("hex");
|
|
2817
|
+
return createHmac("sha256", secret).update(`${taskId}.${attempt}.${tsMs}.${bodyHash}`, "utf8").digest("hex");
|
|
2818
|
+
}
|
|
2819
|
+
/**
|
|
2820
|
+
* Signs a push: `v1=` + HMAC-SHA256 over `taskId.attempt.tsMs.sha256(body)`, hex. The
|
|
2821
|
+
* dispatcher's HTTP transport calls this; a custom transport signs the same way.
|
|
2822
|
+
*/
|
|
2823
|
+
function signPush(secret, taskId, attempt, tsMs, body) {
|
|
2824
|
+
return PREFIX + digest(secret, taskId, attempt, tsMs, body);
|
|
2825
|
+
}
|
|
2826
|
+
/**
|
|
2827
|
+
* True when the `vlo-*` headers sign `rawBody` with `secret` and the timestamp is within
|
|
2828
|
+
* 5 minutes of `nowMs` (default `Date.now()`). Missing or malformed headers are false, never
|
|
2829
|
+
* thrown; the comparison is timing-safe.
|
|
2830
|
+
*/
|
|
2831
|
+
function verifySignature(secret, headers, rawBody, nowMs = Date.now()) {
|
|
2832
|
+
const taskId = headers.get(TASK_ID_HEADER);
|
|
2833
|
+
const attempt = Number(headers.get(ATTEMPT_HEADER));
|
|
2834
|
+
const tsMs = Number(headers.get(TIMESTAMP_HEADER));
|
|
2835
|
+
const signature = headers.get(SIGNATURE_HEADER);
|
|
2836
|
+
if (taskId === null || signature === null) return false;
|
|
2837
|
+
if (!Number.isInteger(attempt) || !Number.isFinite(tsMs)) return false;
|
|
2838
|
+
if (Math.abs(nowMs - tsMs) > WINDOW_MS) return false;
|
|
2839
|
+
const expected = Buffer.from(signPush(secret, taskId, attempt, tsMs, rawBody), "utf8");
|
|
2840
|
+
const actual = Buffer.from(signature, "utf8");
|
|
2841
|
+
if (expected.length !== actual.length) return false;
|
|
2842
|
+
return timingSafeEqual(expected, actual);
|
|
2843
|
+
}
|
|
2844
|
+
// src/host/api/tasks.ts
|
|
2845
|
+
async function postComplete(ctx, taskId, request) {
|
|
2846
|
+
const body = asObject(await readJson(request));
|
|
2847
|
+
return json(await completeTask(ctx, taskId, requireInt(body, "attempt"), body.output ?? null, optionalUsage(body)));
|
|
2848
|
+
}
|
|
2849
|
+
async function postFail(ctx, taskId, request) {
|
|
2850
|
+
const body = asObject(await readJson(request));
|
|
2851
|
+
return json(await failTask(ctx, taskId, requireInt(body, "attempt"), requireString(body, "error"), body.retryable !== false, optionalCause(body) ?? "app_error", optionalUsage(body)));
|
|
2852
|
+
}
|
|
2853
|
+
async function postHeartbeat(ctx, taskId, request) {
|
|
2854
|
+
await heartbeatTask(ctx, taskId, requireInt(asObject(await readJson(request)), "attempt"));
|
|
2855
|
+
return json({ ok: true });
|
|
2856
|
+
}
|
|
2857
|
+
/**
|
|
2858
|
+
* Inbound push. Answers 202 and runs the handler afterwards: the pusher is recording the
|
|
2859
|
+
* dispatch while this returns, and holding the connection open for the whole task would
|
|
2860
|
+
* put the lease and the socket timeout in competition.
|
|
2861
|
+
*/
|
|
2862
|
+
async function postPush(ctx, request, inFlight) {
|
|
2863
|
+
const secret = ctx.auth.pushSecret;
|
|
2864
|
+
if (secret === void 0) return json({ error: {
|
|
2865
|
+
code: "no_push_secret",
|
|
2866
|
+
message: "this host accepts no pushes"
|
|
2867
|
+
} }, 503);
|
|
2868
|
+
const raw = await request.text();
|
|
2869
|
+
if (!verifySignature(secret, request.headers, raw, ctx.now())) throw new Unauthorized();
|
|
2870
|
+
const task = JSON.parse(raw);
|
|
2871
|
+
const worker = workerFor(ctx, task.activity.name);
|
|
2872
|
+
if (worker === void 0) return json({ error: {
|
|
2873
|
+
code: "no_handler",
|
|
2874
|
+
message: `no worker serves "${task.activity.name}"`
|
|
2875
|
+
} }, 404);
|
|
2876
|
+
if (inFlight.has(task.idempotency_key)) return json({ duplicate: true }, 409);
|
|
2877
|
+
const reporter = task.complete_url !== void 0 ? remoteReporter(task.complete_url, ctx.auth.callbackToken ?? ctx.auth.token) : localReporter(ctx);
|
|
2878
|
+
inFlight.add(task.idempotency_key);
|
|
2879
|
+
setImmediate(() => {
|
|
2880
|
+
handleTask(worker, task, reporter).finally(() => inFlight.delete(task.idempotency_key));
|
|
2881
|
+
});
|
|
2882
|
+
return new Response(null, { status: 202 });
|
|
2883
|
+
}
|
|
2884
|
+
function workerFor(ctx, activity) {
|
|
2885
|
+
return ctx.workers.find((w) => w.handlers.has(activity) && w.queues.some((q) => ctx.roles.has(`worker:${q}`)));
|
|
2886
|
+
}
|
|
2887
|
+
// src/host/api/router.ts
|
|
2888
|
+
var NotServed = class extends VloError {
|
|
2889
|
+
constructor(role) {
|
|
2890
|
+
super("role_not_served", `this host does not hold the "${role}" role`, 404);
|
|
2891
|
+
}
|
|
2892
|
+
};
|
|
2893
|
+
var NoRoute = class extends VloError {
|
|
2894
|
+
constructor(method, path) {
|
|
2895
|
+
super("no_route", `${method} ${path} is not a route`, 404);
|
|
2896
|
+
}
|
|
2897
|
+
};
|
|
2898
|
+
/** `"api/vlo"`, `"/api/vlo/"` and `"/api/vlo"` all normalise to `"/api/vlo"`; `""` to none. */
|
|
2899
|
+
function normalizeBasePath(value) {
|
|
2900
|
+
if (value === void 0) return void 0;
|
|
2901
|
+
const trimmed = value.replace(/^\/+/, "").replace(/\/+$/, "");
|
|
2902
|
+
return trimmed.length === 0 ? void 0 : `/${trimmed}`;
|
|
2903
|
+
}
|
|
2904
|
+
/**
|
|
2905
|
+
* Builds the `/v1` router for a context. Every {@link VloError} becomes a JSON error response
|
|
2906
|
+
* with its status; anything else is a 500. Routes a role is not held for answer 404
|
|
2907
|
+
* `role_not_served`. `createHost` calls this; only custom hosts need it directly.
|
|
2908
|
+
*/
|
|
2909
|
+
function createRouter(ctx) {
|
|
2910
|
+
/** Idempotency keys this process is running right now, for the push endpoint. */
|
|
2911
|
+
const inFlight = /* @__PURE__ */ new Set();
|
|
2912
|
+
return async (request) => {
|
|
2913
|
+
try {
|
|
2914
|
+
return await route(ctx, request, inFlight);
|
|
2915
|
+
} catch (error) {
|
|
2916
|
+
return errorResponse(error);
|
|
2917
|
+
}
|
|
2918
|
+
};
|
|
2919
|
+
}
|
|
2920
|
+
async function route(ctx, request, inFlight) {
|
|
2921
|
+
const url = new URL(request.url);
|
|
2922
|
+
const path = stripBase(url.pathname.split("/").filter(Boolean).map(decodeURIComponent), ctx.basePath);
|
|
2923
|
+
const method = request.method.toUpperCase();
|
|
2924
|
+
if (path[0] === "healthz") return json({
|
|
2925
|
+
ok: true,
|
|
2926
|
+
roles: [...ctx.roles],
|
|
2927
|
+
workflows: [...ctx.workflows.keys()]
|
|
2928
|
+
});
|
|
2929
|
+
if (path[0] !== "v1") throw new NoRoute(method, url.pathname);
|
|
2930
|
+
if (path[1] === "tasks" && path[2] === "push" && path.length === 3) {
|
|
2931
|
+
if (method !== "POST") throw new NoRoute(method, url.pathname);
|
|
2932
|
+
if (![...ctx.roles].some((role) => role.startsWith("worker:"))) throw new NotServed("worker");
|
|
2933
|
+
return postPush(ctx, request, inFlight);
|
|
2934
|
+
}
|
|
2935
|
+
const signed = signedSignalRoute(ctx, request, url, method, path);
|
|
2936
|
+
if (signed !== null) return signed;
|
|
2937
|
+
requireBearer(request, ctx.auth.token);
|
|
2938
|
+
if (path[1] === "timers" && path[2] === "tick" && path.length === 3) {
|
|
2939
|
+
if (method !== "POST") throw new NoRoute(method, url.pathname);
|
|
2940
|
+
if (!ctx.roles.has("orchestrator") || ctx.tick === void 0 || ctx.drain === void 0) throw new NotServed("orchestrator");
|
|
2941
|
+
if (!truthy(url.searchParams.get("drain"))) return json(await ctx.tick());
|
|
2942
|
+
return json(await ctx.drain(drainOptions(url)));
|
|
2943
|
+
}
|
|
2944
|
+
if (!ctx.roles.has("api")) throw new NotServed("api");
|
|
2945
|
+
if (path[1] === "tasks" && path[2] === "poll" && path.length === 3) {
|
|
2946
|
+
if (method !== "POST") throw new NoRoute(method, url.pathname);
|
|
2947
|
+
return postPoll(ctx, request);
|
|
2948
|
+
}
|
|
2949
|
+
if (path[1] === "runs") return runRoute(ctx, request, url, method, path);
|
|
2950
|
+
if (path[1] === "tasks") return taskRoute(ctx, request, method, path);
|
|
2951
|
+
throw new NoRoute(method, url.pathname);
|
|
2952
|
+
}
|
|
2953
|
+
/**
|
|
2954
|
+
* `?token=` on the signal route, or null when this is not that route or the token is absent.
|
|
2955
|
+
* An invalid or expired token falls through to the bearer check, so a stale link gets the
|
|
2956
|
+
* same 401 as no credential at all rather than leaking that the run exists.
|
|
2957
|
+
*/
|
|
2958
|
+
function signedSignalRoute(ctx, request, url, method, path) {
|
|
2959
|
+
const [, section, runId, action, name] = path;
|
|
2960
|
+
if (section !== "runs" || action !== "signals" || runId === void 0 || name === void 0) return null;
|
|
2961
|
+
const token = url.searchParams.get("token");
|
|
2962
|
+
const secret = linkSecret(ctx.auth);
|
|
2963
|
+
if (token === null || secret === void 0) return null;
|
|
2964
|
+
if (!verifySignalLink(secret, token, runId, name, ctx.now())) return null;
|
|
2965
|
+
if (!ctx.roles.has("api")) throw new NotServed("api");
|
|
2966
|
+
if (method === "GET") return Promise.resolve(renderConfirmation(runId, name, token, ctx.basePath ?? ""));
|
|
2967
|
+
if (method === "POST") return postSignal(ctx, runId, name, request);
|
|
2968
|
+
throw new NoRoute(method, url.pathname);
|
|
2969
|
+
}
|
|
2970
|
+
function runRoute(ctx, request, url, method, path) {
|
|
2971
|
+
const [, , runId, action, name] = path;
|
|
2972
|
+
if (runId === void 0) {
|
|
2973
|
+
if (method === "POST") return createRun(ctx, request);
|
|
2974
|
+
if (method === "GET") return indexRuns(ctx, url);
|
|
2975
|
+
throw new NoRoute(method, url.pathname);
|
|
2976
|
+
}
|
|
2977
|
+
if (action === void 0 && method === "GET") return showRun(ctx, runId);
|
|
2978
|
+
if (action === "events" && method === "GET") return wantsStream(request, url) ? streamRunEvents(ctx, runId, url, request) : showEvents(ctx, runId, url);
|
|
2979
|
+
if (action === "cancel" && method === "POST") return postCancel(ctx, runId);
|
|
2980
|
+
if (action === "signals" && name !== void 0 && method === "POST") return postSignal(ctx, runId, name, request);
|
|
2981
|
+
if (action === "links" && name !== void 0 && method === "POST") return postSignalLink(ctx, request, url, runId, name);
|
|
2982
|
+
throw new NoRoute(method, url.pathname);
|
|
2983
|
+
}
|
|
2984
|
+
/**
|
|
2985
|
+
* Drops the mount prefix so the routes below are written as `/v1/…` whatever the host is
|
|
2986
|
+
* mounted under. A path that does not carry the prefix is matched as it stands, which is
|
|
2987
|
+
* what lets an in-process client call `/v1/runs` on a host mounted at `/api/vlo`.
|
|
2988
|
+
*/
|
|
2989
|
+
function stripBase(path, basePath) {
|
|
2990
|
+
if (basePath === void 0) return path;
|
|
2991
|
+
const base = basePath.slice(1).split("/");
|
|
2992
|
+
if (base.some((segment, at) => path[at] !== segment)) return path;
|
|
2993
|
+
return path.slice(base.length);
|
|
2994
|
+
}
|
|
2995
|
+
function truthy(value) {
|
|
2996
|
+
return value !== null && value !== "0" && value !== "false";
|
|
2997
|
+
}
|
|
2998
|
+
function drainOptions(url) {
|
|
2999
|
+
const raw = url.searchParams.get("max_ms");
|
|
3000
|
+
if (raw === null) return {};
|
|
3001
|
+
const maxMs = Number(raw);
|
|
3002
|
+
if (!Number.isInteger(maxMs) || maxMs <= 0) throw new BadRequest(`"max_ms" must be a positive integer`);
|
|
3003
|
+
return { maxMs };
|
|
3004
|
+
}
|
|
3005
|
+
function taskRoute(ctx, request, method, path) {
|
|
3006
|
+
const [, , taskId, action] = path;
|
|
3007
|
+
if (taskId === void 0 || method !== "POST") throw new NoRoute(method, path.join("/"));
|
|
3008
|
+
switch (action) {
|
|
3009
|
+
case "complete": return postComplete(ctx, taskId, request);
|
|
3010
|
+
case "fail": return postFail(ctx, taskId, request);
|
|
3011
|
+
case "heartbeat": return postHeartbeat(ctx, taskId, request);
|
|
3012
|
+
default: throw new NoRoute(method, path.join("/"));
|
|
3013
|
+
}
|
|
3014
|
+
}
|
|
3015
|
+
// src/host/deadlines.ts
|
|
3016
|
+
/** The number of timers that actually fired. */
|
|
3017
|
+
async function fireTimers(ctx, o) {
|
|
3018
|
+
const nowMs = ctx.now();
|
|
3019
|
+
const timers = await ctx.journal.transaction((tx) => tx.claimDueTimers(nowMs, o.batch, o.claimHoldMs));
|
|
3020
|
+
let fired = 0;
|
|
3021
|
+
for (const timer of timers) try {
|
|
3022
|
+
await fireOne(ctx, timer);
|
|
3023
|
+
fired += 1;
|
|
3024
|
+
} catch (error) {
|
|
3025
|
+
if (!isStepGone(error)) {
|
|
3026
|
+
o.warn(`could not fire timer ${timer.run_id}/${timer.step_id}`, error);
|
|
3027
|
+
continue;
|
|
3028
|
+
}
|
|
3029
|
+
await retire(ctx, timer, o);
|
|
3030
|
+
}
|
|
3031
|
+
return fired;
|
|
3032
|
+
}
|
|
3033
|
+
/** The fired flag and the timer event share one transaction: `false` means someone else won. */
|
|
3034
|
+
function fireOne(ctx, timer) {
|
|
3035
|
+
return applyEvent(ctx, timer.run_id, async (tx) => {
|
|
3036
|
+
const nowMs = ctx.now();
|
|
3037
|
+
return await tx.markTimerFired(timer.run_id, timer.step_id, nowMs) ? timerFiredEvent({
|
|
3038
|
+
runId: timer.run_id,
|
|
3039
|
+
nowMs
|
|
3040
|
+
}, timer.step_id) : null;
|
|
3041
|
+
});
|
|
3042
|
+
}
|
|
3043
|
+
async function retire(ctx, timer, o) {
|
|
3044
|
+
try {
|
|
3045
|
+
await ctx.journal.transaction((tx) => tx.markTimerFired(timer.run_id, timer.step_id, ctx.now()));
|
|
3046
|
+
} catch (error) {
|
|
3047
|
+
o.warn(`could not retire timer ${timer.run_id}/${timer.step_id}`, error);
|
|
3048
|
+
}
|
|
3049
|
+
}
|
|
3050
|
+
/**
|
|
3051
|
+
* Fails every attempt whose lease has lapsed, which retries it on a fresh attempt or ends the
|
|
3052
|
+
* run once the policy is spent. No claim column is needed: `failTask` reads the task first and
|
|
3053
|
+
* `liveTask` returns null once the attempt has moved on, so a second reaper writes nothing.
|
|
3054
|
+
*
|
|
3055
|
+
* Returns the number of lapsed attempts this reaper was the one to fail.
|
|
3056
|
+
*/
|
|
3057
|
+
async function reapLeases(ctx, o) {
|
|
3058
|
+
return reap(ctx, o, await ctx.journal.expiredLeases(ctx.now(), o.batch), "lease expired without heartbeat", "heartbeat_lost", "lease");
|
|
3059
|
+
}
|
|
3060
|
+
/**
|
|
3061
|
+
* The host's half of `activity({ timeoutMs })`. The worker arms its own timer, which is what
|
|
3062
|
+
* normally ends an over-running attempt; this catches the case where the worker is gone, or
|
|
3063
|
+
* never got far enough to arm anything. Same no-claim argument as the lease reaper.
|
|
3064
|
+
*/
|
|
3065
|
+
async function reapTimeouts(ctx, o) {
|
|
3066
|
+
const nowMs = ctx.now();
|
|
3067
|
+
const tasks = await ctx.journal.expiredTimeouts(nowMs, o.batch);
|
|
3068
|
+
let reaped = 0;
|
|
3069
|
+
for (const task of tasks) {
|
|
3070
|
+
const elapsed = nowMs - (task.dispatched_at_ms ?? nowMs);
|
|
3071
|
+
reaped += await reap(ctx, o, [task], `activity "${task.activity}" timed out after ${elapsed} ms without a result`, "timeout", "timeout");
|
|
3072
|
+
}
|
|
3073
|
+
return reaped;
|
|
3074
|
+
}
|
|
3075
|
+
/** Fails each attempt and counts the ones this process was the first to settle. */
|
|
3076
|
+
async function reap(ctx, o, tasks, error, cause, label) {
|
|
3077
|
+
let reaped = 0;
|
|
3078
|
+
for (const task of tasks) try {
|
|
3079
|
+
if (!(await failTask(ctx, task.task_id, task.attempt, error, true, cause)).duplicate) reaped += 1;
|
|
3080
|
+
} catch (failure) {
|
|
3081
|
+
o.warn(`could not reap the ${label} on task ${task.task_id}`, failure);
|
|
3082
|
+
}
|
|
3083
|
+
return reaped;
|
|
3084
|
+
}
|
|
3085
|
+
// src/host/transport/http-push.ts
|
|
3086
|
+
const TIMEOUT_MS = 5e3;
|
|
3087
|
+
/** 4xx codes that mean "not now" rather than "never": auth, timeout, rate limit. */
|
|
3088
|
+
const RETRYABLE_4XX = /* @__PURE__ */ new Set([
|
|
3089
|
+
401,
|
|
3090
|
+
403,
|
|
3091
|
+
408,
|
|
3092
|
+
429
|
|
3093
|
+
]);
|
|
3094
|
+
/** Pushes tasks to a remote worker over signed HTTP. Built by the dispatcher per configured queue. */
|
|
3095
|
+
var HttpPushTransport = class {
|
|
3096
|
+
/** Always `http-push`. */
|
|
3097
|
+
kind = "http-push";
|
|
3098
|
+
url;
|
|
3099
|
+
secret;
|
|
3100
|
+
now;
|
|
3101
|
+
fetchImpl;
|
|
3102
|
+
timeoutMs;
|
|
3103
|
+
/** Throws a plain `Error` when `secret` is empty: tasks are never pushed unsigned. */
|
|
3104
|
+
constructor(options) {
|
|
3105
|
+
if (!options.secret) throw new Error(`queue "${options.url}" has no push secret; refusing to push unsigned tasks`);
|
|
3106
|
+
this.url = options.url;
|
|
3107
|
+
this.secret = options.secret;
|
|
3108
|
+
this.now = options.now ?? Date.now;
|
|
3109
|
+
this.fetchImpl = options.fetch ?? globalThis.fetch;
|
|
3110
|
+
this.timeoutMs = options.timeoutMs ?? TIMEOUT_MS;
|
|
3111
|
+
}
|
|
3112
|
+
/**
|
|
3113
|
+
* POSTs the task with the four `vlo-*` headers. Never throws: a network error, a timeout
|
|
3114
|
+
* or a 5xx is `accepted: false` without `fatal`; a non-retryable 4xx sets `fatal`.
|
|
3115
|
+
*/
|
|
3116
|
+
async push(task) {
|
|
3117
|
+
const body = JSON.stringify(task);
|
|
3118
|
+
const tsMs = this.now();
|
|
3119
|
+
let response;
|
|
3120
|
+
try {
|
|
3121
|
+
response = await this.fetchImpl(this.url, {
|
|
3122
|
+
method: "POST",
|
|
3123
|
+
headers: {
|
|
3124
|
+
"content-type": "application/json",
|
|
3125
|
+
[TASK_ID_HEADER]: task.task_id,
|
|
3126
|
+
[ATTEMPT_HEADER]: String(task.attempt),
|
|
3127
|
+
[TIMESTAMP_HEADER]: String(tsMs),
|
|
3128
|
+
[SIGNATURE_HEADER]: signPush(this.secret, task.task_id, task.attempt, tsMs, body)
|
|
3129
|
+
},
|
|
3130
|
+
body,
|
|
3131
|
+
signal: AbortSignal.timeout(this.timeoutMs)
|
|
3132
|
+
});
|
|
3133
|
+
} catch (error) {
|
|
3134
|
+
return {
|
|
3135
|
+
accepted: false,
|
|
3136
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
3137
|
+
};
|
|
3138
|
+
}
|
|
3139
|
+
if (response.status === 202 || response.status === 409) {
|
|
3140
|
+
await response.body?.cancel();
|
|
3141
|
+
return { accepted: true };
|
|
3142
|
+
}
|
|
3143
|
+
if (response.status === 200) {
|
|
3144
|
+
const payload = await response.json().catch(() => null);
|
|
3145
|
+
return payload !== null && payload.output !== void 0 ? {
|
|
3146
|
+
accepted: true,
|
|
3147
|
+
inlineOutput: payload.output
|
|
3148
|
+
} : { accepted: true };
|
|
3149
|
+
}
|
|
3150
|
+
return {
|
|
3151
|
+
accepted: false,
|
|
3152
|
+
reason: `${response.status} ${(await response.text().catch(() => "")).slice(0, 500)}`,
|
|
3153
|
+
fatal: response.status >= 400 && response.status < 500 && !RETRYABLE_4XX.has(response.status)
|
|
3154
|
+
};
|
|
3155
|
+
}
|
|
3156
|
+
};
|
|
3157
|
+
// src/host/transport/in-process.ts
|
|
3158
|
+
/**
|
|
3159
|
+
* Counts handlers this process still owes a result for. One tracker is shared by every
|
|
3160
|
+
* in-process transport a host builds, because `Host.drain` has to tell "the dispatcher
|
|
3161
|
+
* moved nothing" apart from "the dispatcher moved nothing *yet*: a handler is running and
|
|
3162
|
+
* its result will schedule the next task".
|
|
3163
|
+
*/
|
|
3164
|
+
var InProcessTracker = class {
|
|
3165
|
+
running = 0;
|
|
3166
|
+
done = 0;
|
|
3167
|
+
waiting = /* @__PURE__ */ new Set();
|
|
3168
|
+
/** Handlers started and not yet reported. */
|
|
3169
|
+
get inFlight() {
|
|
3170
|
+
return this.running;
|
|
3171
|
+
}
|
|
3172
|
+
/** Monotonic count of handlers that reported. A change across a tick means work landed. */
|
|
3173
|
+
get finished() {
|
|
3174
|
+
return this.done;
|
|
3175
|
+
}
|
|
3176
|
+
/** Counts a handler as started. */
|
|
3177
|
+
enter() {
|
|
3178
|
+
this.running += 1;
|
|
3179
|
+
}
|
|
3180
|
+
/** Counts a handler as reported; wakes `settled()` waiters when none are left. */
|
|
3181
|
+
leave() {
|
|
3182
|
+
this.running -= 1;
|
|
3183
|
+
this.done += 1;
|
|
3184
|
+
if (this.running > 0) return;
|
|
3185
|
+
for (const resolve of this.waiting) resolve();
|
|
3186
|
+
this.waiting.clear();
|
|
3187
|
+
}
|
|
3188
|
+
/** Resolves once no in-process handler is outstanding. */
|
|
3189
|
+
settled() {
|
|
3190
|
+
if (this.running === 0) return Promise.resolve();
|
|
3191
|
+
return new Promise((resolve) => this.waiting.add(resolve));
|
|
3192
|
+
}
|
|
3193
|
+
};
|
|
3194
|
+
/** Runs tasks on a worker in this process. Built by the dispatcher for each `worker:<queue>` role. */
|
|
3195
|
+
var InProcessTransport = class {
|
|
3196
|
+
worker;
|
|
3197
|
+
reporter;
|
|
3198
|
+
options;
|
|
3199
|
+
/** Always `in-process`. */
|
|
3200
|
+
kind = "in-process";
|
|
3201
|
+
/** `reporter` is where the handler's result goes; usually `localReporter(ctx)`. */
|
|
3202
|
+
constructor(worker, reporter, options = {}) {
|
|
3203
|
+
this.worker = worker;
|
|
3204
|
+
this.reporter = reporter;
|
|
3205
|
+
this.options = options;
|
|
3206
|
+
}
|
|
3207
|
+
/** Always accepts. The handler starts on the next macrotask, after the dispatcher has committed `running`. */
|
|
3208
|
+
async push(task) {
|
|
3209
|
+
const tracker = this.options.tracker;
|
|
3210
|
+
tracker?.enter();
|
|
3211
|
+
setImmediate(() => {
|
|
3212
|
+
handleTask(this.worker, task, this.reporter).catch((error) => this.options.onError?.(error)).finally(() => tracker?.leave());
|
|
3213
|
+
});
|
|
3214
|
+
return { accepted: true };
|
|
3215
|
+
}
|
|
3216
|
+
};
|
|
3217
|
+
// src/host/dispatcher.ts
|
|
3218
|
+
/**
|
|
3219
|
+
* The outbox dispatcher: the only thing that turns durable rows into effects.
|
|
3220
|
+
*
|
|
3221
|
+
* Nothing here is on the write path. A transition commits rows — a `created` run, a
|
|
3222
|
+
* `scheduled` task, a closed child — and the dispatcher picks them up on its next tick.
|
|
3223
|
+
* That is what makes a crash between "persisted" and "pushed" recoverable: the row is
|
|
3224
|
+
* still there, unclaimed, and any process holding the `orchestrator` role will find it.
|
|
3225
|
+
*
|
|
3226
|
+
* Every stage is idempotent and claim results are unordered sets, so several orchestrators
|
|
3227
|
+
* can run at once.
|
|
3228
|
+
*
|
|
3229
|
+
* Five stages, in tick order:
|
|
3230
|
+
* 1. **start runs** — a `created` run row becomes a `started` event.
|
|
3231
|
+
* 2. **push tasks** — a `scheduled` task is handed to the transport that serves its queue.
|
|
3232
|
+
* Queues configured `mode: "pull"` are skipped entirely: pollers own those rows, and a
|
|
3233
|
+
* claim here would burn dispatch attempts on work this process is never going to deliver.
|
|
3234
|
+
* 3. **fire timers** — a due timer becomes a `timer/succeeded` event. The fired flag and the
|
|
3235
|
+
* event commit together, so a timer fires exactly once however many orchestrators claim it.
|
|
3236
|
+
* 4. **reap leases** — a `running` task whose lease lapsed is failed with `heartbeat_lost`,
|
|
3237
|
+
* which retries it on a fresh attempt or ends the run once the policy is spent.
|
|
3238
|
+
* 5. **reap timeouts** — a `running` task past its `timeout_ms` is failed with `timeout`. The
|
|
3239
|
+
* worker arms the same deadline locally; this is the backstop for a worker that is gone.
|
|
3240
|
+
* 6. **notify parents** — a closed child run becomes a `child` event on its parent.
|
|
3241
|
+
*
|
|
3242
|
+
* Stages 1, 2, 3 and 6 take a claim for `claimHoldMs` so two orchestrators do not do the same
|
|
3243
|
+
* work at the same time. The reapers need no claim column: `failTask` reads the task first and
|
|
3244
|
+
* `liveTask` returns null once the attempt has moved on or the task is terminal, so a second
|
|
3245
|
+
* orchestrator reaping the same expired attempt writes nothing.
|
|
3246
|
+
*
|
|
3247
|
+
* Stages 3, 4 and 5 are driven by the clock rather than by a freshly written row; they live in
|
|
3248
|
+
* `deadlines.ts`.
|
|
3249
|
+
*/
|
|
3250
|
+
/**
|
|
3251
|
+
* The outbox dispatcher. `createHost` builds one per host holding the `orchestrator` role;
|
|
3252
|
+
* only tests and custom hosts construct it directly.
|
|
3253
|
+
*/
|
|
3254
|
+
var Dispatcher = class {
|
|
3255
|
+
ctx;
|
|
3256
|
+
options;
|
|
3257
|
+
mode;
|
|
3258
|
+
tickMs;
|
|
3259
|
+
batch;
|
|
3260
|
+
claimHoldMs;
|
|
3261
|
+
backoffBaseMs;
|
|
3262
|
+
maxBackoffMs;
|
|
3263
|
+
unroutableBackoffMs;
|
|
3264
|
+
workerId;
|
|
3265
|
+
deadlines;
|
|
3266
|
+
transports = /* @__PURE__ */ new Map();
|
|
3267
|
+
/** Queues served by pollers: the push stage must leave their tasks unclaimed. */
|
|
3268
|
+
pullQueues;
|
|
3269
|
+
timer;
|
|
3270
|
+
current = null;
|
|
3271
|
+
again = false;
|
|
3272
|
+
stopped = true;
|
|
3273
|
+
/** Passes still running, whoever started them — the loop, a tick route, a drain. */
|
|
3274
|
+
passes = /* @__PURE__ */ new Set();
|
|
3275
|
+
/** Reads the options once; nothing runs until {@link Dispatcher.start}. */
|
|
3276
|
+
constructor(ctx, options = {}) {
|
|
3277
|
+
this.ctx = ctx;
|
|
3278
|
+
this.options = options;
|
|
3279
|
+
this.mode = options.mode ?? "loop";
|
|
3280
|
+
this.tickMs = options.tickMs ?? 500;
|
|
3281
|
+
this.batch = options.batch ?? 50;
|
|
3282
|
+
this.claimHoldMs = options.claimHoldMs ?? 3e4;
|
|
3283
|
+
this.backoffBaseMs = options.backoffBaseMs ?? 1e3;
|
|
3284
|
+
this.maxBackoffMs = options.maxBackoffMs ?? 6e4;
|
|
3285
|
+
this.unroutableBackoffMs = options.unroutableBackoffMs ?? 6e4;
|
|
3286
|
+
this.workerId = options.workerId ?? `vlo-${randomHex().slice(0, 8)}`;
|
|
3287
|
+
this.pullQueues = Object.entries(ctx.queues).filter(([, queue]) => queue.mode === "pull").map(([name]) => name);
|
|
3288
|
+
this.deadlines = {
|
|
3289
|
+
batch: this.batch,
|
|
3290
|
+
claimHoldMs: this.claimHoldMs,
|
|
3291
|
+
warn: (message, error) => this.warn(message, error)
|
|
3292
|
+
};
|
|
3293
|
+
}
|
|
3294
|
+
/** Begins ticking (`loop` mode) or merely arms `tick()` (`manual` mode). Idempotent. */
|
|
3295
|
+
start() {
|
|
3296
|
+
if (!this.stopped) return;
|
|
3297
|
+
this.stopped = false;
|
|
3298
|
+
if (this.mode === "manual") return;
|
|
3299
|
+
this.timer = setInterval(() => this.schedule(), this.tickMs);
|
|
3300
|
+
this.timer.unref();
|
|
3301
|
+
this.schedule();
|
|
3302
|
+
}
|
|
3303
|
+
/**
|
|
3304
|
+
* Stops ticking and waits for every pass still in flight. The wait is what makes shutdown
|
|
3305
|
+
* safe: the host closes the journal next, and a stage halfway through a claim must not be
|
|
3306
|
+
* left reading a connection that is gone.
|
|
3307
|
+
*/
|
|
3308
|
+
async stop() {
|
|
3309
|
+
this.stopped = true;
|
|
3310
|
+
if (this.timer !== void 0) clearInterval(this.timer);
|
|
3311
|
+
this.timer = void 0;
|
|
3312
|
+
await this.current;
|
|
3313
|
+
while (this.passes.size > 0) await Promise.allSettled([...this.passes]);
|
|
3314
|
+
}
|
|
3315
|
+
/** Runs a tick soon. Safe to call from inside a tick: it queues one more pass. */
|
|
3316
|
+
kick() {
|
|
3317
|
+
if (this.stopped || this.mode === "manual") return;
|
|
3318
|
+
this.schedule();
|
|
3319
|
+
}
|
|
3320
|
+
/** One pass over every stage. The tick route and the tests drive the outbox with it. */
|
|
3321
|
+
async tick() {
|
|
3322
|
+
const pass = this.pass();
|
|
3323
|
+
this.passes.add(pass);
|
|
3324
|
+
try {
|
|
3325
|
+
return await pass;
|
|
3326
|
+
} finally {
|
|
3327
|
+
this.passes.delete(pass);
|
|
3328
|
+
}
|
|
3329
|
+
}
|
|
3330
|
+
async pass() {
|
|
3331
|
+
return {
|
|
3332
|
+
started: await this.startRuns(),
|
|
3333
|
+
pushed: await this.pushTasks(),
|
|
3334
|
+
timers: await fireTimers(this.ctx, this.deadlines),
|
|
3335
|
+
reaped: await reapLeases(this.ctx, this.deadlines),
|
|
3336
|
+
timeouts: await reapTimeouts(this.ctx, this.deadlines),
|
|
3337
|
+
notified: await this.notifyParents()
|
|
3338
|
+
};
|
|
3339
|
+
}
|
|
3340
|
+
schedule() {
|
|
3341
|
+
if (this.stopped) return;
|
|
3342
|
+
if (this.current !== null) {
|
|
3343
|
+
this.again = true;
|
|
3344
|
+
return;
|
|
3345
|
+
}
|
|
3346
|
+
this.current = this.drain().finally(() => {
|
|
3347
|
+
this.current = null;
|
|
3348
|
+
});
|
|
3349
|
+
}
|
|
3350
|
+
async drain() {
|
|
3351
|
+
do {
|
|
3352
|
+
this.again = false;
|
|
3353
|
+
try {
|
|
3354
|
+
await this.tick();
|
|
3355
|
+
} catch (error) {
|
|
3356
|
+
this.warn("tick failed", error);
|
|
3357
|
+
}
|
|
3358
|
+
} while (this.again && !this.stopped);
|
|
3359
|
+
}
|
|
3360
|
+
async startRuns() {
|
|
3361
|
+
const nowMs = this.ctx.now();
|
|
3362
|
+
const runs = await this.ctx.journal.transaction((tx) => tx.claimCreatedRuns(nowMs, this.batch, this.claimHoldMs));
|
|
3363
|
+
let started = 0;
|
|
3364
|
+
for (const run of runs) try {
|
|
3365
|
+
const input = await inlineOrBlob(this.ctx, run.input, run.input_ref);
|
|
3366
|
+
await applyEvent(this.ctx, run.run_id, startedEvent({
|
|
3367
|
+
runId: run.run_id,
|
|
3368
|
+
nowMs: this.ctx.now()
|
|
3369
|
+
}, input ?? "null"));
|
|
3370
|
+
started += 1;
|
|
3371
|
+
} catch (error) {
|
|
3372
|
+
this.warn(`could not start run ${run.run_id}`, error);
|
|
3373
|
+
}
|
|
3374
|
+
return started;
|
|
3375
|
+
}
|
|
3376
|
+
async pushTasks() {
|
|
3377
|
+
const nowMs = this.ctx.now();
|
|
3378
|
+
const tasks = await this.ctx.journal.transaction((tx) => tx.claimUndispatchedTasks(nowMs, this.batch, this.claimHoldMs, { excludeQueues: this.pullQueues }));
|
|
3379
|
+
return (await Promise.all(tasks.map((task) => this.pushOne(task).catch((error) => {
|
|
3380
|
+
this.warn(`could not push task ${task.task_id}`, error);
|
|
3381
|
+
return false;
|
|
3382
|
+
})))).filter(Boolean).length;
|
|
3383
|
+
}
|
|
3384
|
+
/** True when the task was accepted by a worker and recorded as running. */
|
|
3385
|
+
async pushOne(task) {
|
|
3386
|
+
const transport = this.transportFor(task);
|
|
3387
|
+
if (transport === null) {
|
|
3388
|
+
this.warn(`no transport for queue "${task.queue}"; deferring task ${task.task_id}`);
|
|
3389
|
+
await this.defer(task, this.unroutableBackoffMs);
|
|
3390
|
+
return false;
|
|
3391
|
+
}
|
|
3392
|
+
const result = await transport.push(await toPushedTask(this.ctx, task));
|
|
3393
|
+
if (!result.accepted) {
|
|
3394
|
+
if (result.fatal === true) {
|
|
3395
|
+
await applyEvent(this.ctx, task.run_id, taskFailedEvent({
|
|
3396
|
+
runId: task.run_id,
|
|
3397
|
+
nowMs: this.ctx.now()
|
|
3398
|
+
}, task.step_id, task.attempt, "schema_violation", `worker rejected the push: ${result.reason}`));
|
|
3399
|
+
return false;
|
|
3400
|
+
}
|
|
3401
|
+
await this.defer(task, this.backoff(task.dispatch_attempts));
|
|
3402
|
+
return false;
|
|
3403
|
+
}
|
|
3404
|
+
await markTaskRunning(this.ctx, task, this.workerId);
|
|
3405
|
+
if (result.inlineOutput !== void 0) await completeTask(this.ctx, task.task_id, task.attempt, result.inlineOutput);
|
|
3406
|
+
return true;
|
|
3407
|
+
}
|
|
3408
|
+
backoff(dispatchAttempts) {
|
|
3409
|
+
const exponent = Math.max(0, Math.min(dispatchAttempts, 20));
|
|
3410
|
+
return Math.min(this.backoffBaseMs * 2 ** exponent, this.maxBackoffMs);
|
|
3411
|
+
}
|
|
3412
|
+
defer(task, delayMs) {
|
|
3413
|
+
const notBefore = this.ctx.now() + delayMs;
|
|
3414
|
+
return this.ctx.journal.transaction((tx) => tx.deferDispatch(task.task_id, task.attempt, notBefore));
|
|
3415
|
+
}
|
|
3416
|
+
transportFor(task) {
|
|
3417
|
+
const key = `${task.queue}\u0000${task.activity}`;
|
|
3418
|
+
const cached = this.transports.get(key);
|
|
3419
|
+
if (cached !== void 0) return cached;
|
|
3420
|
+
const transport = this.buildTransport(task);
|
|
3421
|
+
this.transports.set(key, transport);
|
|
3422
|
+
return transport;
|
|
3423
|
+
}
|
|
3424
|
+
buildTransport(task) {
|
|
3425
|
+
if (this.ctx.roles.has(`worker:${task.queue}`)) {
|
|
3426
|
+
const worker = findWorker(this.ctx.workers, task.queue, task.activity);
|
|
3427
|
+
if (worker !== void 0) return new InProcessTransport(worker, localReporter(this.ctx), {
|
|
3428
|
+
tracker: this.ctx.inProcess,
|
|
3429
|
+
onError: (error) => this.warn(`could not report task on queue "${task.queue}"`, error)
|
|
3430
|
+
});
|
|
3431
|
+
}
|
|
3432
|
+
const queue = this.ctx.queues[task.queue];
|
|
3433
|
+
if (queue?.url === void 0) return null;
|
|
3434
|
+
return new HttpPushTransport({
|
|
3435
|
+
url: queue.url,
|
|
3436
|
+
secret: queue.secret ?? "",
|
|
3437
|
+
now: this.ctx.now,
|
|
3438
|
+
...this.options.fetch !== void 0 ? { fetch: this.options.fetch } : {}
|
|
3439
|
+
});
|
|
3440
|
+
}
|
|
3441
|
+
async notifyParents() {
|
|
3442
|
+
const nowMs = this.ctx.now();
|
|
3443
|
+
const children = await this.ctx.journal.transaction((tx) => tx.claimClosedUnnotified(nowMs, this.batch, this.claimHoldMs));
|
|
3444
|
+
let notified = 0;
|
|
3445
|
+
for (const child of children) try {
|
|
3446
|
+
await this.notifyParent(child);
|
|
3447
|
+
notified += 1;
|
|
3448
|
+
} catch (error) {
|
|
3449
|
+
this.warn(`could not notify the parent of ${child.run_id}`, error);
|
|
3450
|
+
}
|
|
3451
|
+
return notified;
|
|
3452
|
+
}
|
|
3453
|
+
async notifyParent(child) {
|
|
3454
|
+
const parentRunId = child.parent_run_id;
|
|
3455
|
+
const parentStepId = child.parent_step_id;
|
|
3456
|
+
const status = childStatusOf(child.status);
|
|
3457
|
+
if (parentRunId === void 0 || parentStepId === void 0 || status === null) {
|
|
3458
|
+
await this.markNotified(child.run_id);
|
|
3459
|
+
return;
|
|
3460
|
+
}
|
|
3461
|
+
const output = await inlineOrBlob(this.ctx, child.output, child.output_ref);
|
|
3462
|
+
await applyEvent(this.ctx, parentRunId, childEvent({
|
|
3463
|
+
runId: parentRunId,
|
|
3464
|
+
nowMs: this.ctx.now()
|
|
3465
|
+
}, parentStepId, status, output), async (tx) => {
|
|
3466
|
+
await tx.markParentNotified(child.run_id, this.ctx.now());
|
|
3467
|
+
});
|
|
3468
|
+
}
|
|
3469
|
+
markNotified(runId) {
|
|
3470
|
+
return this.ctx.journal.transaction((tx) => tx.markParentNotified(runId, this.ctx.now()));
|
|
3471
|
+
}
|
|
3472
|
+
/**
|
|
3473
|
+
* Never throws and never writes to stdout: hosts listen on `events` if they care.
|
|
3474
|
+
* A closed journal is shutdown, not a fault — the host stopped while this was in flight —
|
|
3475
|
+
* so it is dropped rather than reported.
|
|
3476
|
+
*/
|
|
3477
|
+
warn(message, error) {
|
|
3478
|
+
if (error instanceof JournalClosed) return;
|
|
3479
|
+
this.ctx.events.emit("warning", {
|
|
3480
|
+
message,
|
|
3481
|
+
...error !== void 0 ? { error } : {}
|
|
3482
|
+
});
|
|
3483
|
+
}
|
|
3484
|
+
};
|
|
3485
|
+
// src/host/drain.ts
|
|
3486
|
+
/** Wall-clock budget of a drain when `maxMs` is absent: 25 s, under a typical serverless `maxDuration`. */
|
|
3487
|
+
const DEFAULT_DRAIN_MAX_MS = 25e3;
|
|
3488
|
+
/**
|
|
3489
|
+
* Ticks until a pass is quiet or the budget runs out. `Host.drain` wraps this and additionally
|
|
3490
|
+
* shares one drain between concurrent callers; call that unless you hold a `HostContext`.
|
|
3491
|
+
* Throws a plain `Error` on a context without the `orchestrator` role.
|
|
3492
|
+
*
|
|
3493
|
+
* @example
|
|
3494
|
+
* ```ts
|
|
3495
|
+
* // Inside a request on a `manual`-mode host: carry the run as far as it goes right now.
|
|
3496
|
+
* const result = await host.drain({ maxMs: 20_000 });
|
|
3497
|
+
* if (!result.idle) console.warn(`still busy after ${result.passes} passes`);
|
|
3498
|
+
* ```
|
|
3499
|
+
*/
|
|
3500
|
+
async function drainHost(ctx, options = {}) {
|
|
3501
|
+
const tick = ctx.tick;
|
|
3502
|
+
if (tick === void 0) throw new Error("vlo host: drain() needs the \"orchestrator\" role");
|
|
3503
|
+
const tracker = ctx.inProcess;
|
|
3504
|
+
const deadline = Date.now() + (options.maxMs ?? 25e3);
|
|
3505
|
+
let passes = 0;
|
|
3506
|
+
for (;;) {
|
|
3507
|
+
const finishedBefore = tracker.finished;
|
|
3508
|
+
const counts = await tick();
|
|
3509
|
+
passes += 1;
|
|
3510
|
+
await settle(tracker, deadline - Date.now());
|
|
3511
|
+
if (moved(counts) === 0 && tracker.inFlight === 0 && tracker.finished === finishedBefore) return {
|
|
3512
|
+
passes,
|
|
3513
|
+
idle: true,
|
|
3514
|
+
counts
|
|
3515
|
+
};
|
|
3516
|
+
if (Date.now() >= deadline) return {
|
|
3517
|
+
passes,
|
|
3518
|
+
idle: false,
|
|
3519
|
+
counts
|
|
3520
|
+
};
|
|
3521
|
+
}
|
|
3522
|
+
}
|
|
3523
|
+
/** Waits for the in-process handlers, but never past the drain's own deadline. */
|
|
3524
|
+
function settle(tracker, remainingMs) {
|
|
3525
|
+
if (tracker.inFlight === 0 || remainingMs <= 0) return Promise.resolve();
|
|
3526
|
+
return Promise.race([tracker.settled(), after(remainingMs)]);
|
|
3527
|
+
}
|
|
3528
|
+
function after(ms) {
|
|
3529
|
+
return new Promise((resolve) => {
|
|
3530
|
+
setTimeout(resolve, ms).unref();
|
|
3531
|
+
});
|
|
3532
|
+
}
|
|
3533
|
+
function moved(counts) {
|
|
3534
|
+
return counts.started + counts.pushed + counts.timers + counts.reaped + counts.timeouts + counts.notified;
|
|
3535
|
+
}
|
|
3536
|
+
// src/host/node-server.ts
|
|
3537
|
+
/**
|
|
3538
|
+
* node:http ↔ fetch adapter. The router speaks `Request`/`Response`; this is the ~80 lines
|
|
3539
|
+
* that let it listen on a port without pulling in a framework.
|
|
3540
|
+
*
|
|
3541
|
+
* The body is piped, never buffered: an SSE response never ends, so waiting for it would
|
|
3542
|
+
* hang the request instead of streaming it. A socket that goes away aborts the request
|
|
3543
|
+
* signal, which is how an open stream learns its reader left.
|
|
3544
|
+
*/
|
|
3545
|
+
/**
|
|
3546
|
+
* Serves a fetch-style handler on `port` (`0` picks a free one) and `host` (default
|
|
3547
|
+
* `127.0.0.1`). Rejects when the port cannot be bound. Response bodies are streamed, so an
|
|
3548
|
+
* SSE response works without a framework.
|
|
3549
|
+
*/
|
|
3550
|
+
async function listen(handler, port, host = "127.0.0.1") {
|
|
3551
|
+
const server = createServer((req, res) => {
|
|
3552
|
+
respond(handler, req, res);
|
|
3553
|
+
});
|
|
3554
|
+
await new Promise((resolve, reject) => {
|
|
3555
|
+
server.once("error", reject);
|
|
3556
|
+
server.listen(port, host, () => {
|
|
3557
|
+
server.removeListener("error", reject);
|
|
3558
|
+
resolve();
|
|
3559
|
+
});
|
|
3560
|
+
});
|
|
3561
|
+
const address = server.address();
|
|
3562
|
+
const actual = typeof address === "object" && address !== null ? address.port : port;
|
|
3563
|
+
return {
|
|
3564
|
+
url: `http://${host}:${actual}`,
|
|
3565
|
+
port: actual,
|
|
3566
|
+
close: () => closeServer(server)
|
|
3567
|
+
};
|
|
3568
|
+
}
|
|
3569
|
+
async function respond(handler, req, res) {
|
|
3570
|
+
const gone = new AbortController();
|
|
3571
|
+
res.on("close", () => gone.abort());
|
|
3572
|
+
try {
|
|
3573
|
+
const response = await handler(toRequest(req, gone.signal));
|
|
3574
|
+
res.writeHead(response.status, Object.fromEntries(response.headers));
|
|
3575
|
+
if (response.body === null) {
|
|
3576
|
+
res.end();
|
|
3577
|
+
return;
|
|
3578
|
+
}
|
|
3579
|
+
res.flushHeaders();
|
|
3580
|
+
await pipeline(Readable.fromWeb(response.body), res);
|
|
3581
|
+
} catch (error) {
|
|
3582
|
+
if (res.writableEnded || res.headersSent) {
|
|
3583
|
+
res.end();
|
|
3584
|
+
return;
|
|
3585
|
+
}
|
|
3586
|
+
res.writeHead(500, { "content-type": "application/json" });
|
|
3587
|
+
res.end(JSON.stringify({ error: {
|
|
3588
|
+
code: "internal",
|
|
3589
|
+
message: String(error)
|
|
3590
|
+
} }));
|
|
3591
|
+
}
|
|
3592
|
+
}
|
|
3593
|
+
function toRequest(req, signal) {
|
|
3594
|
+
const url = `http://${req.headers.host ?? "localhost"}${req.url ?? "/"}`;
|
|
3595
|
+
const method = req.method ?? "GET";
|
|
3596
|
+
const hasBody = method !== "GET" && method !== "HEAD";
|
|
3597
|
+
return new Request(url, {
|
|
3598
|
+
method,
|
|
3599
|
+
headers: headersOf(req),
|
|
3600
|
+
signal,
|
|
3601
|
+
...hasBody ? {
|
|
3602
|
+
body: Readable.toWeb(req),
|
|
3603
|
+
duplex: "half"
|
|
3604
|
+
} : {}
|
|
3605
|
+
});
|
|
3606
|
+
}
|
|
3607
|
+
function headersOf(req) {
|
|
3608
|
+
const headers = new Headers();
|
|
3609
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
3610
|
+
if (value === void 0) continue;
|
|
3611
|
+
for (const item of Array.isArray(value) ? value : [value]) headers.append(name, item);
|
|
3612
|
+
}
|
|
3613
|
+
return headers;
|
|
3614
|
+
}
|
|
3615
|
+
function closeServer(server) {
|
|
3616
|
+
return new Promise((resolve, reject) => {
|
|
3617
|
+
server.closeAllConnections();
|
|
3618
|
+
server.close((error) => error ? reject(error) : resolve());
|
|
3619
|
+
});
|
|
3620
|
+
}
|
|
3621
|
+
// src/host/schemas.ts
|
|
3622
|
+
async function registerSchemas(ctx) {
|
|
3623
|
+
const nowMs = ctx.now();
|
|
3624
|
+
const rows = [...[...ctx.activities.values()].flatMap((a) => a.hash === void 0 || a.jsonSchema === void 0 ? [] : [{
|
|
3625
|
+
name: a.name,
|
|
3626
|
+
version: a.hash,
|
|
3627
|
+
json_schema: JSON.stringify(a.jsonSchema),
|
|
3628
|
+
...a.retry !== void 0 ? { retry_policy: JSON.stringify(a.retry) } : {}
|
|
3629
|
+
}]), ...[...ctx.signals.values()].flatMap((s) => s.hash === void 0 || s.jsonSchema === void 0 ? [] : [{
|
|
3630
|
+
name: s.name,
|
|
3631
|
+
version: s.hash,
|
|
3632
|
+
json_schema: JSON.stringify(s.jsonSchema)
|
|
3633
|
+
}])];
|
|
3634
|
+
if (rows.length === 0) return;
|
|
3635
|
+
await ctx.journal.transaction(async (tx) => {
|
|
3636
|
+
for (const row of rows) await tx.upsertSchema(row, nowMs);
|
|
3637
|
+
});
|
|
3638
|
+
}
|
|
3639
|
+
// src/host/roles.ts
|
|
3640
|
+
/**
|
|
3641
|
+
* `createHost` — one process, some subset of the engine's roles.
|
|
3642
|
+
*
|
|
3643
|
+
* - `orchestrator` runs the outbox dispatcher.
|
|
3644
|
+
* - `api` serves the control plane.
|
|
3645
|
+
* - `worker:<queue>` runs activities for that queue, in-process and over inbound push.
|
|
3646
|
+
*
|
|
3647
|
+
* Splitting them is how the same code becomes a laptop all-in-one, a Cloud Run service and
|
|
3648
|
+
* a fleet of workers. Nothing else in the host reads roles: the dispatcher asks whether a
|
|
3649
|
+
* queue is served locally, the router asks whether it may answer.
|
|
3650
|
+
*/
|
|
3651
|
+
/** Blob store used when {@link CreateHostOptions.blob} is absent: a `file://` directory relative to the working directory. */
|
|
3652
|
+
const DEFAULT_BLOB_URL = "file://.vlo/blobs";
|
|
3653
|
+
/** Port {@link serve} binds when `port` is absent. */
|
|
3654
|
+
const DEFAULT_PORT = 4100;
|
|
3655
|
+
/** How often an open SSE stream re-reads the journal when `streamPollMs` is absent, in milliseconds. */
|
|
3656
|
+
const DEFAULT_STREAM_POLL_MS = 500;
|
|
3657
|
+
/** How long `stop()` gives in-process handlers to report before the journal closes. */
|
|
3658
|
+
const SHUTDOWN_GRACE_MS = 5e3;
|
|
3659
|
+
/** `tick` and `drain` move the outbox, which only an orchestrator owns. */
|
|
3660
|
+
var NoOrchestrator = class extends Error {
|
|
3661
|
+
constructor(what, roles) {
|
|
3662
|
+
super(`vlo host: ${what}() needs the "orchestrator" role; this host holds [${[...roles].join(", ")}]`);
|
|
3663
|
+
this.name = "NoOrchestrator";
|
|
3664
|
+
}
|
|
3665
|
+
};
|
|
3666
|
+
const NOT_STARTED = new Proxy({}, { get() {
|
|
3667
|
+
throw new Error("vlo host: call start() (or serve()) before submitting events");
|
|
3668
|
+
} });
|
|
3669
|
+
/**
|
|
3670
|
+
* Builds a host without binding a port or starting it. Nothing is loaded or migrated until
|
|
3671
|
+
* `start()` (or the first `fetch`). A `journal` given as a URL is opened here and closed by
|
|
3672
|
+
* `stop()`; a `Journal` instance is left to its owner.
|
|
3673
|
+
*
|
|
3674
|
+
* @example
|
|
3675
|
+
* ```ts
|
|
3676
|
+
* import { createClient, createHost, defineWorker } from "@oona/vlo/host";
|
|
3677
|
+
*
|
|
3678
|
+
* const host = createHost({
|
|
3679
|
+
* journal: "sqlite://./.vlo/dev.db",
|
|
3680
|
+
* workflows: [pipeline],
|
|
3681
|
+
* activities: [render],
|
|
3682
|
+
* workers: [defineWorker({ "pull.render": (input: { clip: string }) => ({ rendered: input.clip }) })],
|
|
3683
|
+
* });
|
|
3684
|
+
* await host.start();
|
|
3685
|
+
*
|
|
3686
|
+
* const client = createClient({ fetch: host.fetch });
|
|
3687
|
+
* const run = await client.start(pipeline, { clip: "reel" });
|
|
3688
|
+
* await client.waitFor(run.run_id, "completed");
|
|
3689
|
+
* await host.stop();
|
|
3690
|
+
* ```
|
|
3691
|
+
*/
|
|
3692
|
+
function createHost(options) {
|
|
3693
|
+
const ownsJournal = typeof options.journal === "string";
|
|
3694
|
+
const journal = ownsJournal ? openJournal(options.journal) : options.journal;
|
|
3695
|
+
const blob = typeof options.blob === "string" || options.blob === void 0 ? openBlobStore(options.blob ?? "file://.vlo/blobs") : options.blob;
|
|
3696
|
+
const registries = mergeDomains(options);
|
|
3697
|
+
const workers = [...registries.workers];
|
|
3698
|
+
const roles = new Set(options.roles ?? defaultRoles(workers));
|
|
3699
|
+
const events = new EventEmitter();
|
|
3700
|
+
events.setMaxListeners(0);
|
|
3701
|
+
let dispatcher;
|
|
3702
|
+
const ctx = {
|
|
3703
|
+
journal,
|
|
3704
|
+
blob,
|
|
3705
|
+
kernel: options.kernel ?? NOT_STARTED,
|
|
3706
|
+
now: options.now ?? Date.now,
|
|
3707
|
+
namespace: options.namespace ?? "default",
|
|
3708
|
+
workflows: byName(registries.workflows),
|
|
3709
|
+
activities: byName(registries.activities),
|
|
3710
|
+
signals: byName(registries.signals),
|
|
3711
|
+
workers,
|
|
3712
|
+
queues: options.queues ?? {},
|
|
3713
|
+
auth: options.auth ?? {},
|
|
3714
|
+
roles,
|
|
3715
|
+
...options.publicUrl !== void 0 ? { publicUrl: options.publicUrl } : {},
|
|
3716
|
+
...withBasePath(options.basePath),
|
|
3717
|
+
streamPollMs: options.streamPollMs ?? 500,
|
|
3718
|
+
events,
|
|
3719
|
+
kick: () => dispatcher?.kick(),
|
|
3720
|
+
inProcess: new InProcessTracker()
|
|
3721
|
+
};
|
|
3722
|
+
/** One drain at a time per host: a second caller joins the one already running. */
|
|
3723
|
+
let draining = null;
|
|
3724
|
+
if (roles.has("orchestrator")) {
|
|
3725
|
+
dispatcher = new Dispatcher(ctx, options.dispatcher ?? {});
|
|
3726
|
+
const orchestrator = dispatcher;
|
|
3727
|
+
ctx.tick = async () => {
|
|
3728
|
+
await start();
|
|
3729
|
+
return orchestrator.tick();
|
|
3730
|
+
};
|
|
3731
|
+
ctx.drain = (drainOptions = {}) => {
|
|
3732
|
+
if (draining !== null) return draining;
|
|
3733
|
+
const pending = drainHost(ctx, drainOptions);
|
|
3734
|
+
draining = pending;
|
|
3735
|
+
pending.catch(() => void 0).then(() => {
|
|
3736
|
+
if (draining === pending) draining = null;
|
|
3737
|
+
});
|
|
3738
|
+
return pending;
|
|
3739
|
+
};
|
|
3740
|
+
}
|
|
3741
|
+
const router = createRouter(ctx);
|
|
3742
|
+
let ready = null;
|
|
3743
|
+
let closing = null;
|
|
3744
|
+
const start = () => ready ??= boot(ctx, options, dispatcher);
|
|
3745
|
+
return {
|
|
3746
|
+
fetch: async (request) => {
|
|
3747
|
+
await start();
|
|
3748
|
+
return router(request);
|
|
3749
|
+
},
|
|
3750
|
+
start,
|
|
3751
|
+
tick() {
|
|
3752
|
+
if (ctx.tick === void 0) return Promise.reject(new NoOrchestrator("tick", roles));
|
|
3753
|
+
return ctx.tick();
|
|
3754
|
+
},
|
|
3755
|
+
drain(drainOptions = {}) {
|
|
3756
|
+
if (ctx.drain === void 0) return Promise.reject(new NoOrchestrator("drain", roles));
|
|
3757
|
+
return ctx.drain(drainOptions);
|
|
3758
|
+
},
|
|
3759
|
+
/** Idempotent: a host may be stopped by its owner and again by a shutdown hook. */
|
|
3760
|
+
stop() {
|
|
3761
|
+
closing ??= (async () => {
|
|
3762
|
+
await dispatcher?.stop();
|
|
3763
|
+
await Promise.race([ctx.inProcess.settled(), timeout(SHUTDOWN_GRACE_MS)]);
|
|
3764
|
+
if (ownsJournal) await journal.close();
|
|
3765
|
+
ready = null;
|
|
3766
|
+
})();
|
|
3767
|
+
return closing;
|
|
3768
|
+
},
|
|
3769
|
+
events,
|
|
3770
|
+
journal,
|
|
3771
|
+
roles,
|
|
3772
|
+
get publicUrl() {
|
|
3773
|
+
return ctx.publicUrl;
|
|
3774
|
+
},
|
|
3775
|
+
set publicUrl(url) {
|
|
3776
|
+
if (url === void 0) delete ctx.publicUrl;
|
|
3777
|
+
else ctx.publicUrl = url;
|
|
3778
|
+
}
|
|
3779
|
+
};
|
|
3780
|
+
}
|
|
3781
|
+
async function boot(ctx, options, dispatcher) {
|
|
3782
|
+
ctx.kernel = options.kernel ?? await loadKernel();
|
|
3783
|
+
await ctx.journal.migrate();
|
|
3784
|
+
await registerSchemas(ctx);
|
|
3785
|
+
dispatcher?.start();
|
|
3786
|
+
}
|
|
3787
|
+
/**
|
|
3788
|
+
* Binds a port, tells the host its own URL, then starts it. `publicUrl` is set to the
|
|
3789
|
+
* listener's URL unless the options give one, so pushed tasks carry a working `complete_url`.
|
|
3790
|
+
*
|
|
3791
|
+
* @example
|
|
3792
|
+
* ```ts
|
|
3793
|
+
* import { serve } from "@oona/vlo/host";
|
|
3794
|
+
*
|
|
3795
|
+
* const server = await serve({
|
|
3796
|
+
* journal: "postgres://user:pass@localhost/app",
|
|
3797
|
+
* workflows: [pipeline],
|
|
3798
|
+
* activities: [render],
|
|
3799
|
+
* auth: { token: "control-plane-token" },
|
|
3800
|
+
* port: 4100,
|
|
3801
|
+
* });
|
|
3802
|
+
* console.log(server.url); // http://127.0.0.1:4100
|
|
3803
|
+
* await server.close();
|
|
3804
|
+
* ```
|
|
3805
|
+
*/
|
|
3806
|
+
async function serve(options) {
|
|
3807
|
+
const host = createHost(options);
|
|
3808
|
+
const listener = await listen(host.fetch, options.port ?? 4100, options.hostname);
|
|
3809
|
+
host.publicUrl = options.publicUrl ?? listener.url;
|
|
3810
|
+
await host.start();
|
|
3811
|
+
return {
|
|
3812
|
+
...listener,
|
|
3813
|
+
host,
|
|
3814
|
+
async close() {
|
|
3815
|
+
await listener.close();
|
|
3816
|
+
await host.stop();
|
|
3817
|
+
}
|
|
3818
|
+
};
|
|
3819
|
+
}
|
|
3820
|
+
/**
|
|
3821
|
+
* Next route file: `export const { GET, POST } = handler({ … })`. The host is created on the
|
|
3822
|
+
* first request and shared by every request after, so a serverless function pays for the
|
|
3823
|
+
* kernel load once per instance. Pair it with `dispatcher: { mode: "manual" }` and a cron on
|
|
3824
|
+
* `POST /v1/timers/tick`.
|
|
3825
|
+
*
|
|
3826
|
+
* @example
|
|
3827
|
+
* ```ts
|
|
3828
|
+
* // app/api/vlo/[[...path]]/route.ts
|
|
3829
|
+
* import { handler } from "@oona/vlo/host";
|
|
3830
|
+
*
|
|
3831
|
+
* export const { GET, POST } = handler({
|
|
3832
|
+
* journal: process.env.DATABASE_URL ?? "sqlite://./.vlo/dev.db",
|
|
3833
|
+
* workflows: [pipeline],
|
|
3834
|
+
* activities: [render],
|
|
3835
|
+
* basePath: "/api/vlo",
|
|
3836
|
+
* dispatcher: { mode: "manual" },
|
|
3837
|
+
* });
|
|
3838
|
+
* ```
|
|
3839
|
+
*/
|
|
3840
|
+
function handler(options) {
|
|
3841
|
+
let host;
|
|
3842
|
+
const serveOne = (request) => {
|
|
3843
|
+
host ??= createHost(options);
|
|
3844
|
+
return host.fetch(request);
|
|
3845
|
+
};
|
|
3846
|
+
return {
|
|
3847
|
+
GET: serveOne,
|
|
3848
|
+
POST: serveOne
|
|
3849
|
+
};
|
|
3850
|
+
}
|
|
3851
|
+
function timeout(ms) {
|
|
3852
|
+
return new Promise((resolve) => {
|
|
3853
|
+
setTimeout(resolve, ms).unref();
|
|
3854
|
+
});
|
|
3855
|
+
}
|
|
3856
|
+
/** `exactOptionalPropertyTypes`: an absent base path must be an absent key, not `undefined`. */
|
|
3857
|
+
function withBasePath(value) {
|
|
3858
|
+
const basePath = normalizeBasePath(value);
|
|
3859
|
+
return basePath === void 0 ? {} : { basePath };
|
|
3860
|
+
}
|
|
3861
|
+
function defaultRoles(workers) {
|
|
3862
|
+
const roles = ["orchestrator", "api"];
|
|
3863
|
+
for (const worker of workers) for (const queue of worker.queues) roles.push(`worker:${queue}`);
|
|
3864
|
+
return roles;
|
|
3865
|
+
}
|
|
3866
|
+
function byName(items) {
|
|
3867
|
+
return new Map(items.map((item) => [item.name, item]));
|
|
3868
|
+
}
|
|
3869
|
+
export { loadKernel as $, getRunView as A, signSignalLink as B, localReporter as C, failTask as D, completeTask as E, applyEvent as F, Nondeterminism as G, BadRequest as H, foldEvent as I, RunTerminal as J, ReducerFailed as K, rebuildCheckpoint as L, readRunEvents as M, signalRun as N, heartbeatTask as O, startRun as P, WorkflowRejected as Q, DEFAULT_LINK_TTL_MS as R, verifySignature as S, handleTask as T, IllegalEvent as U, verifySignalLink as V, LeaseLost as W, Unauthorized as X, TaskNotFound as Y, VloError as Z, ATTEMPT_HEADER as _, createHost as a, TIMESTAMP_HEADER as b, listen as c, Dispatcher as d, openJournal as et, InProcessTracker as f, normalizeBasePath as g, createRouter as h, SHUTDOWN_GRACE_MS as i, listRuns as j, cancelRun as k, DEFAULT_DRAIN_MAX_MS as l, HttpPushTransport as m, DEFAULT_PORT as n, openBlobStore as nt, handler as o, InProcessTransport as p, RunNotFound as q, DEFAULT_STREAM_POLL_MS as r, GcsBlobStore as rt, serve as s, DEFAULT_BLOB_URL as t, JournalClosed as tt, drainHost as u, SIGNATURE_HEADER as v, remoteReporter as w, signPush as x, TASK_ID_HEADER as y, linkSecret as z };
|