@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
package/dist/host.js
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import { $ as loadKernel, A as getRunView, B as signSignalLink, C as localReporter, D as failTask, E as completeTask, F as applyEvent, G as Nondeterminism, H as BadRequest, I as foldEvent, J as RunTerminal, K as ReducerFailed, L as rebuildCheckpoint, M as readRunEvents, N as signalRun, O as heartbeatTask, P as startRun, Q as WorkflowRejected, R as DEFAULT_LINK_TTL_MS, S as verifySignature, T as handleTask, U as IllegalEvent, V as verifySignalLink, W as LeaseLost, X as Unauthorized, Y as TaskNotFound, Z as VloError, _ as ATTEMPT_HEADER, a as createHost, b as TIMESTAMP_HEADER, c as listen, d as Dispatcher, et as openJournal, f as InProcessTracker, g as normalizeBasePath, h as createRouter, i as SHUTDOWN_GRACE_MS, j as listRuns, k as cancelRun, l as DEFAULT_DRAIN_MAX_MS, m as HttpPushTransport, n as DEFAULT_PORT, nt as openBlobStore, o as handler, p as InProcessTransport, q as RunNotFound, r as DEFAULT_STREAM_POLL_MS, rt as GcsBlobStore, s as serve, t as DEFAULT_BLOB_URL, tt as JournalClosed, u as drainHost, v as SIGNATURE_HEADER, w as remoteReporter, x as signPush, y as TASK_ID_HEADER, z as linkSecret } from "./roles-D25bG980.js";
|
|
2
|
+
import { a as withRetryInput, i as findWorker, n as mergeDomains, o as TERMINAL_RUN_STATUSES, r as defineWorker, s as isTerminalRunStatus, t as defineDomain } from "./domain-Bs8TeDCv.js";
|
|
3
|
+
import { randomBytes } from "node:crypto";
|
|
4
|
+
// src/host/worker/pull.ts
|
|
5
|
+
/**
|
|
6
|
+
* `runPullWorker` — a worker process that asks a host for work instead of being pushed to.
|
|
7
|
+
*
|
|
8
|
+
* Everything after the poll is the push path unchanged: `handleTask` runs the activity and
|
|
9
|
+
* `remoteReporter` calls the result back over the same three verbs. Only the delivery differs,
|
|
10
|
+
* which is what keeps a pull queue a deployment choice rather than a second execution model.
|
|
11
|
+
*/
|
|
12
|
+
const DEFAULT_WAIT_MS = 2e4;
|
|
13
|
+
const DEFAULT_CONCURRENCY = 4;
|
|
14
|
+
const MAX_PER_POLL = 10;
|
|
15
|
+
/** Backoff after a failed poll, so an unreachable host is not hammered. */
|
|
16
|
+
const RETRY_MS = 1e3;
|
|
17
|
+
/** Pause after an empty zero-wait poll. */
|
|
18
|
+
const IDLE_MS = 50;
|
|
19
|
+
/**
|
|
20
|
+
* Runs until `signal` aborts, then resolves once the tasks in flight have reported. Throws
|
|
21
|
+
* a `TypeError` when there is no queue to poll. A failed poll goes to `onError` and the loop
|
|
22
|
+
* retries after 1 s. Runs on the worker side; the host only needs the `api` role.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```ts
|
|
26
|
+
* import { defineWorker, runPullWorker } from "@oona/vlo/host";
|
|
27
|
+
*
|
|
28
|
+
* const abort = new AbortController();
|
|
29
|
+
* const loop = runPullWorker({
|
|
30
|
+
* baseUrl: "https://vlo.example.com",
|
|
31
|
+
* token: "control-plane-token",
|
|
32
|
+
* worker: defineWorker(
|
|
33
|
+
* { "pull.render": (input: { clip: string }) => ({ rendered: input.clip.toUpperCase() }) },
|
|
34
|
+
* { queues: ["media"] },
|
|
35
|
+
* ),
|
|
36
|
+
* waitMs: 5_000,
|
|
37
|
+
* signal: abort.signal,
|
|
38
|
+
* onError: (error) => console.error(error),
|
|
39
|
+
* });
|
|
40
|
+
* process.once("SIGTERM", () => abort.abort());
|
|
41
|
+
* await loop;
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
async function runPullWorker(options) {
|
|
45
|
+
const baseUrl = options.baseUrl.replace(/\/$/, "");
|
|
46
|
+
const queues = options.queues ?? options.worker.queues;
|
|
47
|
+
if (queues.length === 0) throw new TypeError("runPullWorker: no queues to poll");
|
|
48
|
+
const waitMs = options.waitMs ?? DEFAULT_WAIT_MS;
|
|
49
|
+
const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY);
|
|
50
|
+
const workerId = options.workerId ?? `vlo-pull-${randomBytes(4).toString("hex")}`;
|
|
51
|
+
const signal = options.signal;
|
|
52
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
53
|
+
const inFlight = /* @__PURE__ */ new Set();
|
|
54
|
+
const aborted = () => signal?.aborted === true;
|
|
55
|
+
let next = 0;
|
|
56
|
+
while (!aborted()) {
|
|
57
|
+
if (inFlight.size >= concurrency) {
|
|
58
|
+
await Promise.race(inFlight);
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
const queue = queues[next % queues.length];
|
|
62
|
+
next += 1;
|
|
63
|
+
let tasks;
|
|
64
|
+
try {
|
|
65
|
+
tasks = await poll(fetchImpl, {
|
|
66
|
+
baseUrl,
|
|
67
|
+
queue,
|
|
68
|
+
workerId,
|
|
69
|
+
waitMs,
|
|
70
|
+
max: Math.min(concurrency - inFlight.size, MAX_PER_POLL),
|
|
71
|
+
...options.token !== void 0 ? { token: options.token } : {},
|
|
72
|
+
...signal !== void 0 ? { signal } : {}
|
|
73
|
+
});
|
|
74
|
+
} catch (error) {
|
|
75
|
+
if (aborted()) break;
|
|
76
|
+
options.onError?.(error);
|
|
77
|
+
await sleep(RETRY_MS, signal);
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (tasks.length === 0) {
|
|
81
|
+
if (waitMs === 0) await sleep(IDLE_MS, signal);
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
for (const task of tasks) {
|
|
85
|
+
const reporter = remoteReporter(completeUrl(baseUrl, task), options.token, fetchImpl);
|
|
86
|
+
const running = handleTask(options.worker, task, reporter, { ...signal !== void 0 ? { signal } : {} }).catch((error) => options.onError?.(error)).finally(() => inFlight.delete(running));
|
|
87
|
+
inFlight.add(running);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
await Promise.all(inFlight);
|
|
91
|
+
}
|
|
92
|
+
async function poll(fetchImpl, a) {
|
|
93
|
+
const response = await fetchImpl(`${a.baseUrl}/v1/tasks/poll`, {
|
|
94
|
+
method: "POST",
|
|
95
|
+
headers: {
|
|
96
|
+
"content-type": "application/json",
|
|
97
|
+
...a.token !== void 0 ? { authorization: `Bearer ${a.token}` } : {}
|
|
98
|
+
},
|
|
99
|
+
body: JSON.stringify({
|
|
100
|
+
queue: a.queue,
|
|
101
|
+
worker_id: a.workerId,
|
|
102
|
+
wait_ms: a.waitMs,
|
|
103
|
+
max: a.max
|
|
104
|
+
}),
|
|
105
|
+
...a.signal !== void 0 ? { signal: a.signal } : {}
|
|
106
|
+
});
|
|
107
|
+
if (!response.ok) throw new Error(`poll ${a.queue} failed: ${response.status} ${await response.text()}`);
|
|
108
|
+
return (await response.json()).tasks ?? [];
|
|
109
|
+
}
|
|
110
|
+
/** The host fills `complete_url` when it knows its own URL; otherwise we know it. */
|
|
111
|
+
function completeUrl(baseUrl, task) {
|
|
112
|
+
return task.complete_url ?? `${baseUrl}/v1/tasks/${encodeURIComponent(task.task_id)}`;
|
|
113
|
+
}
|
|
114
|
+
function sleep(ms, signal) {
|
|
115
|
+
return new Promise((resolve) => {
|
|
116
|
+
const timer = setTimeout(done, ms);
|
|
117
|
+
timer.unref();
|
|
118
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
119
|
+
function done() {
|
|
120
|
+
clearTimeout(timer);
|
|
121
|
+
signal?.removeEventListener("abort", done);
|
|
122
|
+
resolve();
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
// src/client/sse.ts
|
|
127
|
+
/** Yields one frame per blank-line-terminated block. Releases the reader when the consumer stops. */
|
|
128
|
+
async function* parseSse(body) {
|
|
129
|
+
const reader = body.getReader();
|
|
130
|
+
const decoder = new TextDecoder();
|
|
131
|
+
let buffer = "";
|
|
132
|
+
try {
|
|
133
|
+
for (;;) {
|
|
134
|
+
const { done, value } = await reader.read();
|
|
135
|
+
if (done) break;
|
|
136
|
+
buffer += decoder.decode(value, { stream: true });
|
|
137
|
+
let split = buffer.indexOf("\n\n");
|
|
138
|
+
while (split !== -1) {
|
|
139
|
+
const frame = parseFrame(buffer.slice(0, split));
|
|
140
|
+
buffer = buffer.slice(split + 2);
|
|
141
|
+
if (frame !== null) yield frame;
|
|
142
|
+
split = buffer.indexOf("\n\n");
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
} finally {
|
|
146
|
+
reader.releaseLock();
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
function parseFrame(block) {
|
|
150
|
+
const frame = { data: "" };
|
|
151
|
+
const data = [];
|
|
152
|
+
for (const raw of block.split("\n")) {
|
|
153
|
+
const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
|
|
154
|
+
if (line.length === 0 || line.startsWith(":")) continue;
|
|
155
|
+
const colon = line.indexOf(":");
|
|
156
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
157
|
+
const value = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");
|
|
158
|
+
if (field === "id") frame.id = value;
|
|
159
|
+
else if (field === "event") frame.event = value;
|
|
160
|
+
else if (field === "data") data.push(value);
|
|
161
|
+
}
|
|
162
|
+
if (data.length === 0 && frame.event === void 0) return null;
|
|
163
|
+
frame.data = data.join("\n");
|
|
164
|
+
return frame;
|
|
165
|
+
}
|
|
166
|
+
// src/client/index.ts
|
|
167
|
+
const IN_PROCESS_BASE = "http://vlo.localhost";
|
|
168
|
+
const POLL_MS = 50;
|
|
169
|
+
const DEFAULT_MAX_CHAIN = 50;
|
|
170
|
+
/**
|
|
171
|
+
* Builds a {@link Client}. With no options it talks to `http://vlo.localhost` over
|
|
172
|
+
* `globalThis.fetch`, which is only useful together with `fetch: host.fetch`.
|
|
173
|
+
*
|
|
174
|
+
* @example
|
|
175
|
+
* ```ts
|
|
176
|
+
* import { createClient } from "@oona/vlo/host";
|
|
177
|
+
*
|
|
178
|
+
* const client = createClient({ baseUrl: "http://127.0.0.1:4100", token: "control-plane-token" });
|
|
179
|
+
* const run = await client.start(pipeline, { clip: "reel" });
|
|
180
|
+
* await client.signal(run.run_id, "approve", { by: "me" });
|
|
181
|
+
* const done = await client.waitFor(run.run_id, "completed");
|
|
182
|
+
* console.log(done.output);
|
|
183
|
+
* ```
|
|
184
|
+
*/
|
|
185
|
+
function createClient(options = {}) {
|
|
186
|
+
const base = (options.baseUrl ?? IN_PROCESS_BASE).replace(/\/$/, "");
|
|
187
|
+
const call = options.fetch ?? ((request) => globalThis.fetch(request));
|
|
188
|
+
async function send(method, path, body) {
|
|
189
|
+
const init = {
|
|
190
|
+
method,
|
|
191
|
+
headers: {
|
|
192
|
+
...body !== void 0 ? { "content-type": "application/json" } : {},
|
|
193
|
+
...options.token !== void 0 ? { authorization: `Bearer ${options.token}` } : {}
|
|
194
|
+
},
|
|
195
|
+
...body !== void 0 ? { body: JSON.stringify(body) } : {}
|
|
196
|
+
};
|
|
197
|
+
const response = await call(new Request(`${base}${path}`, init));
|
|
198
|
+
return {
|
|
199
|
+
response,
|
|
200
|
+
text: await response.text()
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
async function request(method, path, body) {
|
|
204
|
+
const { response, text } = await send(method, path, body);
|
|
205
|
+
if (!response.ok) throw new Error(`${method} ${path} → ${response.status} ${text}`);
|
|
206
|
+
return text.length > 0 ? JSON.parse(text) : null;
|
|
207
|
+
}
|
|
208
|
+
const runPath = (runId) => `/v1/runs/${encodeURIComponent(runId)}`;
|
|
209
|
+
const nameOf = (name) => typeof name === "string" ? name : name.name;
|
|
210
|
+
const client = {
|
|
211
|
+
async start(workflow, input, startOptions) {
|
|
212
|
+
const { run_id } = await request("POST", "/v1/runs", {
|
|
213
|
+
workflow: typeof workflow === "string" ? workflow : workflow.name,
|
|
214
|
+
input,
|
|
215
|
+
...startOptions?.runId !== void 0 ? { run_id: startOptions.runId } : {},
|
|
216
|
+
...startOptions?.search !== void 0 ? { search: startOptions.search } : {}
|
|
217
|
+
});
|
|
218
|
+
return client.get(run_id);
|
|
219
|
+
},
|
|
220
|
+
signal(runId, name, payload) {
|
|
221
|
+
return request("POST", `${runPath(runId)}/signals/${encodeURIComponent(nameOf(name))}`, payload);
|
|
222
|
+
},
|
|
223
|
+
signalLink(runId, name, linkOptions = {}) {
|
|
224
|
+
return request("POST", `${runPath(runId)}/links/${encodeURIComponent(nameOf(name))}`, linkOptions.expiresInMs !== void 0 ? { expires_in_ms: linkOptions.expiresInMs } : {});
|
|
225
|
+
},
|
|
226
|
+
async startFresh(workflow, input, freshOptions) {
|
|
227
|
+
const maxChain = freshOptions.maxChain ?? DEFAULT_MAX_CHAIN;
|
|
228
|
+
for (let n = 1; n <= maxChain; n += 1) {
|
|
229
|
+
const runId = n === 1 ? freshOptions.runId : `${freshOptions.runId}_${String(n)}`;
|
|
230
|
+
const existing = await client.find(runId);
|
|
231
|
+
if (existing === null) return {
|
|
232
|
+
run: await client.start(workflow, input, {
|
|
233
|
+
runId,
|
|
234
|
+
...freshOptions.search !== void 0 ? { search: freshOptions.search } : {}
|
|
235
|
+
}),
|
|
236
|
+
joined: false
|
|
237
|
+
};
|
|
238
|
+
if (!isTerminalRunStatus(existing.status)) return {
|
|
239
|
+
run: existing,
|
|
240
|
+
joined: true
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
throw new Error(`startFresh: ${String(maxChain)} runs under "${freshOptions.runId}" have ended; raise maxChain`);
|
|
244
|
+
},
|
|
245
|
+
get: (runId) => request("GET", runPath(runId)),
|
|
246
|
+
async find(runId) {
|
|
247
|
+
const { response, text } = await send("GET", runPath(runId));
|
|
248
|
+
if (response.status === 404) return null;
|
|
249
|
+
if (!response.ok) throw new Error(`GET ${runPath(runId)} → ${response.status} ${text}`);
|
|
250
|
+
return JSON.parse(text);
|
|
251
|
+
},
|
|
252
|
+
events: (runId, since = 0) => request("GET", `${runPath(runId)}/events?since=${since}`),
|
|
253
|
+
stream(runId, streamOptions = {}) {
|
|
254
|
+
return streamRun(call, {
|
|
255
|
+
url: `${base}${runPath(runId)}/events?stream=1&since=${streamOptions.since ?? 0}`,
|
|
256
|
+
...options.token !== void 0 ? { token: options.token } : {},
|
|
257
|
+
...streamOptions.signal !== void 0 ? { signal: streamOptions.signal } : {}
|
|
258
|
+
});
|
|
259
|
+
},
|
|
260
|
+
cancel: (runId) => request("POST", `${runPath(runId)}/cancel`, {}),
|
|
261
|
+
list(query = {}) {
|
|
262
|
+
const search = new URLSearchParams();
|
|
263
|
+
if (query.status !== void 0) search.set("status", query.status);
|
|
264
|
+
if (query.workflow !== void 0) search.set("workflow", query.workflow);
|
|
265
|
+
if (query.limit !== void 0) search.set("limit", String(query.limit));
|
|
266
|
+
return request("GET", `/v1/runs${search.size > 0 ? `?${search.toString()}` : ""}`);
|
|
267
|
+
},
|
|
268
|
+
async waitFor(runId, status, timeoutMs = 1e4) {
|
|
269
|
+
const wanted = new Set(Array.isArray(status) ? status : [status]);
|
|
270
|
+
const deadline = Date.now() + timeoutMs;
|
|
271
|
+
for (;;) {
|
|
272
|
+
const view = await client.get(runId);
|
|
273
|
+
if (wanted.has(view.status)) return view;
|
|
274
|
+
if (Date.now() >= deadline) throw new Error(`run ${runId} is ${view.status} after ${timeoutMs}ms, waiting for ${[...wanted].join("|")}`);
|
|
275
|
+
await new Promise((resolve) => setTimeout(resolve, POLL_MS));
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
return client;
|
|
280
|
+
}
|
|
281
|
+
async function* streamRun(call, o) {
|
|
282
|
+
const response = await call(new Request(o.url, {
|
|
283
|
+
headers: {
|
|
284
|
+
accept: "text/event-stream",
|
|
285
|
+
...o.token !== void 0 ? { authorization: `Bearer ${o.token}` } : {}
|
|
286
|
+
},
|
|
287
|
+
...o.signal !== void 0 ? { signal: o.signal } : {}
|
|
288
|
+
}));
|
|
289
|
+
if (!response.ok || response.body === null) throw new Error(`GET ${o.url} → ${response.status} ${await response.text()}`);
|
|
290
|
+
for await (const frame of parseSse(response.body)) {
|
|
291
|
+
const message = decode(frame.event, frame.data, frame.id);
|
|
292
|
+
if (message !== null) yield message;
|
|
293
|
+
if (message?.type === "end") return;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
function decode(event, data, id) {
|
|
297
|
+
switch (event) {
|
|
298
|
+
case "journal": return {
|
|
299
|
+
type: "journal",
|
|
300
|
+
seq: Number(id ?? 0),
|
|
301
|
+
data: JSON.parse(data)
|
|
302
|
+
};
|
|
303
|
+
case "emit": return {
|
|
304
|
+
type: "emit",
|
|
305
|
+
data: JSON.parse(data)
|
|
306
|
+
};
|
|
307
|
+
case "end": return {
|
|
308
|
+
type: "end",
|
|
309
|
+
data: JSON.parse(data)
|
|
310
|
+
};
|
|
311
|
+
default: return null;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
export { ATTEMPT_HEADER, BadRequest, DEFAULT_BLOB_URL, DEFAULT_DRAIN_MAX_MS, DEFAULT_LINK_TTL_MS, DEFAULT_PORT, DEFAULT_STREAM_POLL_MS, Dispatcher, GcsBlobStore, HttpPushTransport, IllegalEvent, InProcessTracker, InProcessTransport, JournalClosed, LeaseLost, Nondeterminism, ReducerFailed, RunNotFound, RunTerminal, SHUTDOWN_GRACE_MS, SIGNATURE_HEADER, TASK_ID_HEADER, TERMINAL_RUN_STATUSES, TIMESTAMP_HEADER, TaskNotFound, Unauthorized, VloError, WorkflowRejected, applyEvent, cancelRun, completeTask, createClient, createHost, createRouter, defineDomain, defineWorker, drainHost, failTask, findWorker, foldEvent, getRunView, handleTask, handler, heartbeatTask, isTerminalRunStatus, linkSecret, listRuns, listen, loadKernel, localReporter, mergeDomains, normalizeBasePath, openBlobStore, openJournal, readRunEvents, rebuildCheckpoint, remoteReporter, runPullWorker, serve, signPush, signSignalLink, signalRun, startRun, verifySignalLink, verifySignature, withRetryInput };
|