@genroc/eval-node 0.0.0-edge.00ee483

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/worker.ts ADDED
@@ -0,0 +1,332 @@
1
+ #!/usr/bin/env node
2
+ // The queue worker: claims parked `external` script tasks from genroc, evaluates each in its
3
+ // own realm, and answers. This is the whole genroc-facing half — eval.ts and realm.ts know
4
+ // nothing about the queue, which is what keeps the containment strategy swappable.
5
+ //
6
+ // See README.md for the contract, and specs/external-task-queue.md for the queue itself.
7
+
8
+ import { readFileSync } from "node:fs";
9
+ import { Cancelled, evaluate, type EvalRequest, type FailureKind } from "./eval.ts";
10
+
11
+ const SERVER = (process.env.GENROC_SERVER ?? "http://localhost:8448").replace(/\/$/, "");
12
+ const WORKER_ID = process.env.WORKER_ID ?? `evaluator-${process.pid}`;
13
+ // The credential, when the server runs with --auth token. A worker needs exactly the `worker`
14
+ // permission — the four queue verbs plus GET /api/objects — so mint it scoped rather than
15
+ // handing a worker an admin token: this is the credential most likely to sit on a machine you
16
+ // trust least. specs/api-auth.md §5.
17
+ //
18
+ // Sent as a header rather than in the URL because Node's fetch REFUSES a URL carrying
19
+ // credentials ("Request cannot be constructed from a URL that includes credentials"), so the
20
+ // basic-auth-in-the-URL trick that works for genctl is not available here.
21
+ // GENROC_TOKEN_FILE is the mounted-secret shape: a credential in a file rather than an
22
+ // environment variable, so it stays out of `docker inspect` and out of the process environment
23
+ // any child inherits. The inline variable wins when both are set.
24
+ const TOKEN =
25
+ process.env.GENROC_TOKEN ??
26
+ (process.env.GENROC_TOKEN_FILE ? readFileSync(process.env.GENROC_TOKEN_FILE, "utf8").trim() : "");
27
+ const authHeaders: Record<string, string> = TOKEN ? { authorization: `Bearer ${TOKEN}` } : {};
28
+ // Concurrency is the worker's to set, and that is the point of pulling: under the old fetch
29
+ // shape genroc decided how many scripts ran at once (--max-concurrent, default 200) and the
30
+ // evaluator accepted every one of them. Here it claims what it can run and no more, so a
31
+ // backlog is a queue rather than 200 threads fighting over a core.
32
+ const CONCURRENCY = Number(process.env.CONCURRENCY ?? 4);
33
+ const POLL_MS = Number(process.env.POLL_MS ?? 250);
34
+ // The visibility timeout. Short, and renewed while work is in flight: a worker that dies
35
+ // should return its task quickly rather than holding it for the whole budget.
36
+ const LEASE_MS = Number(process.env.LEASE_MS ?? 30_000);
37
+ const RENEW_MS = Math.max(1_000, Math.floor(LEASE_MS / 3));
38
+ const PROCESS_FILTER = process.env.PROCESS ?? "";
39
+ const TASK_FILTER = process.env.TASK ?? "";
40
+
41
+ type ObjectEntry = { path: (string | number)[]; ref: string; size: number };
42
+
43
+ type QueueTask = {
44
+ token: string;
45
+ process: string;
46
+ task_id: string;
47
+ input: unknown;
48
+ objects?: ObjectEntry[];
49
+ raises?: Record<string, unknown>;
50
+ };
51
+
52
+ // Values too large to ship inline are listed rather than carried, and a bundle is exactly that:
53
+ // one object shared by every instance of a definition version, fetched once instead of copied
54
+ // into each task. A ref is a content hash, so it is immutable — the cache never invalidates.
55
+ const objectCache = new Map<string, unknown>();
56
+
57
+ async function fetchObject(ref: string): Promise<unknown> {
58
+ const cached = objectCache.get(ref);
59
+ if (cached !== undefined) return cached;
60
+ // Left to throw on purpose: this runs while a task is IN FLIGHT, and a task whose input
61
+ // cannot be fetched must fail rather than silently run against a missing value. The caller
62
+ // releases the claim, so the task returns to the queue.
63
+ const res = await fetch(`${SERVER}/api/objects/${encodeURIComponent(ref)}`, { headers: authHeaders });
64
+ if (!res.ok) throw new Error(`fetch object ${ref}: HTTP ${res.status}`);
65
+ const { data } = (await res.json()) as { data: string };
66
+ let value: unknown;
67
+ try {
68
+ value = JSON.parse(data);
69
+ } catch {
70
+ value = data;
71
+ }
72
+ objectCache.set(ref, value);
73
+ return value;
74
+ }
75
+
76
+ /** Put each listed value back where its path says it belongs. Paths are arrays of keys, so this
77
+ * needs no parser: the whole reason they are not JSON Pointer strings. */
78
+ async function resolveObjects(job: QueueTask): Promise<unknown> {
79
+ let input: any = job.input;
80
+ for (const e of job.objects ?? []) {
81
+ const value = await fetchObject(e.ref);
82
+ if (e.path.length === 0) {
83
+ input = value;
84
+ continue;
85
+ }
86
+ // The path is rooted at the entry and starts with "input", which is the value being rebuilt.
87
+ const rest = e.path[0] === "input" ? e.path.slice(1) : e.path;
88
+ if (rest.length === 0) {
89
+ input = value;
90
+ continue;
91
+ }
92
+ let cur: any = input;
93
+ for (let i = 0; i < rest.length - 1; i++) cur = cur?.[rest[i]!];
94
+ if (cur) cur[rest[rest.length - 1]!] = value;
95
+ }
96
+ return input;
97
+ }
98
+
99
+ async function call(path: string, body: unknown): Promise<{ ok: boolean; status: number; data: any }> {
100
+ // A network error is a REPLY, not a throw. A worker outlives the server it polls — a
101
+ // restart, a rolling deploy, a container coming up before genroc is listening — and an
102
+ // unhandled rejection here kills it for a condition the next poll would clear. Status 0
103
+ // says "never reached the server", which is distinct from anything genroc answers.
104
+ let res: Response;
105
+ try {
106
+ res = await fetch(SERVER + path, {
107
+ method: "POST",
108
+ headers: { "content-type": "application/json", ...authHeaders },
109
+ body: JSON.stringify(body),
110
+ });
111
+ } catch (err) {
112
+ return { ok: false, status: 0, data: { error: `${SERVER} unreachable: ${(err as Error).message}` } };
113
+ }
114
+ const text = await res.text();
115
+ let data: any = null;
116
+ try {
117
+ data = text ? JSON.parse(text) : null;
118
+ } catch {
119
+ data = { error: text };
120
+ }
121
+ return { ok: res.ok, status: res.status, data };
122
+ }
123
+
124
+ /** The task input IS an EvalRequest: `code` required, `input` and `timeout_ms` optional. A task
125
+ * whose input is not that shape is the definition's fault, not the script's, and is reported
126
+ * as a compile_error — the nearest permanent kind, since no retry can fix the definition. */
127
+ function asEvalRequest(input: unknown): EvalRequest | string {
128
+ if (typeof input !== "object" || input === null) return "the task input is not an object";
129
+ const r = input as Record<string, unknown>;
130
+ if (typeof r.code !== "string") return "the task input has no `code` string";
131
+ return {
132
+ code: r.code,
133
+ input: r.input,
134
+ timeout_ms: typeof r.timeout_ms === "number" ? r.timeout_ms : undefined,
135
+ };
136
+ }
137
+
138
+ /** A claim this worker is currently serving. The controller is how the renewal loop reaches
139
+ * the evaluation: genroc cannot call us, so a cancellation arrives as an answer to our own
140
+ * heartbeat and has to be delivered inward from there. */
141
+ type Running = { job: QueueTask; abort: AbortController };
142
+
143
+ const inFlight = new Map<string, Running>();
144
+ let running = true;
145
+
146
+ // Whether the last claim reached genroc. A worker polls several times a second, so an
147
+ // unreachable server would otherwise emit a line per poll — thousands during a restart, which
148
+ // buries the one line that mattered. Announce the TRANSITIONS instead: going away, and coming
149
+ // back. Silence in between is the report that nothing changed.
150
+ let serverReachable = true;
151
+
152
+ async function claim(n: number): Promise<QueueTask[]> {
153
+ const { ok, status, data } = await call("/api/external-tasks/claim", {
154
+ worker_id: WORKER_ID,
155
+ limit: n,
156
+ lease_ms: LEASE_MS,
157
+ ...(PROCESS_FILTER ? { process: PROCESS_FILTER } : {}),
158
+ ...(TASK_FILTER ? { task: TASK_FILTER } : {}),
159
+ });
160
+ if (!ok) {
161
+ // A credential problem is not transient, and polling through it looks like a healthy
162
+ // worker that never picks anything up — the worst shape for an operator to debug. Exit
163
+ // instead, so a supervisor restarts it and the failure is visible where it happened.
164
+ if (status === 401 || status === 403) {
165
+ console.error(
166
+ `claim rejected (${status}): ${JSON.stringify(data)}\n` +
167
+ `The server requires authentication. Set GENROC_TOKEN to a token with the 'worker' ` +
168
+ `permission — mint one with: genctl token create --perms worker --label evaluator -q`,
169
+ );
170
+ process.exit(1);
171
+ }
172
+ // status 0 is "never reached the server" (see call): a restart, a rolling deploy, a
173
+ // network blip. Not an error to act on — the next poll clears it — so it is reported once
174
+ // and then waited out.
175
+ if (status === 0) {
176
+ if (serverReachable) {
177
+ serverReachable = false;
178
+ console.error(
179
+ `genroc at ${SERVER} is unreachable — ${(data as { error?: string })?.error ?? ""}. ` +
180
+ `Still polling every ${POLL_MS}ms; work resumes when it comes back.`,
181
+ );
182
+ }
183
+ return [];
184
+ }
185
+ console.error(`claim failed: ${JSON.stringify(data)}`);
186
+ return [];
187
+ }
188
+ if (!serverReachable) {
189
+ serverReachable = true;
190
+ console.error(`genroc at ${SERVER} is reachable again — resuming.`);
191
+ }
192
+ return (data?.items ?? []) as QueueTask[];
193
+ }
194
+
195
+ async function release(token: string): Promise<void> {
196
+ const { ok, data } = await call("/api/external-tasks/release", { token });
197
+ if (!ok) console.error(`release failed: ${JSON.stringify(data)}`);
198
+ }
199
+
200
+ /** answer submits the outcome. A refusal is NOT retried with a different one: the definition
201
+ * declared a contract this worker does not satisfy (an undeclared code, a payload that does
202
+ * not fit `raises`), and guessing again would only pick a second wrong answer. Release it, so
203
+ * the task returns to the queue and an operator sees it waiting rather than silently gone. */
204
+ async function answer(token: string, outcome: Record<string, unknown>): Promise<void> {
205
+ const { ok, data } = await call("/api/external-tasks/resolve", { token, ...outcome });
206
+ if (ok) return;
207
+ console.error(`genroc refused the outcome for ${token}: ${JSON.stringify(data)}`);
208
+ await release(token);
209
+ }
210
+
211
+ async function run(job: QueueTask, signal: AbortSignal): Promise<void> {
212
+ let resolved: unknown;
213
+ try {
214
+ resolved = await resolveObjects(job);
215
+ } catch (err) {
216
+ // The values are there or they are not; this is the runner failing to read them, not the
217
+ // script failing, so hand the task back for someone else rather than reporting an outcome.
218
+ console.error(`resolving objects for ${job.token}: ${err instanceof Error ? err.message : String(err)}`);
219
+ await release(job.token);
220
+ return;
221
+ }
222
+ const req = asEvalRequest(resolved);
223
+ if (typeof req === "string") {
224
+ await answer(job.token, {
225
+ error: { code: "compile_error", message: req, data: { name: "BadTaskInput" } },
226
+ });
227
+ return;
228
+ }
229
+
230
+ let result;
231
+ try {
232
+ result = await evaluate(req, signal);
233
+ } catch (err) {
234
+ // Cancelled is not a fault: the process was stopped while this ran. The claim still goes
235
+ // back — the row is terminal, so nothing re-claims it, and the release is what stops it
236
+ // waiting out a lease nobody is serving.
237
+ if (err instanceof Cancelled) {
238
+ console.log(`cancelled: ${job.token}`);
239
+ await release(job.token);
240
+ return;
241
+ }
242
+ // The RUNNER faulted, not the script — the one class where a retry can help. There is no
243
+ // error code for it on purpose: releasing the claim is how a queue spells "retryable", and
244
+ // it puts the task in front of a different worker instead of burning the definition's
245
+ // on_error budget on this one's bad day.
246
+ console.error(`evaluator fault on ${job.token}: ${err instanceof Error ? err.message : String(err)}`);
247
+ await release(job.token);
248
+ return;
249
+ }
250
+
251
+ if (result.ok) {
252
+ // `body` is JSON text produced inside the realm; an empty body is a script that returned
253
+ // nothing, which genroc reads as null.
254
+ await answer(job.token, { result: result.body === "" ? null : JSON.parse(result.body) });
255
+ return;
256
+ }
257
+ const f = result.failure;
258
+ await answer(job.token, {
259
+ error: {
260
+ // The failure KIND is the code, so an on_error rule branches on what went wrong without
261
+ // reading a payload. Every kind is permanent; see eval.ts.
262
+ code: f.kind satisfies FailureKind,
263
+ message: f.message,
264
+ data: { name: f.name, ...(f.stack ? { stack: f.stack } : {}) },
265
+ },
266
+ });
267
+ }
268
+
269
+ async function renewLoop(): Promise<void> {
270
+ while (running) {
271
+ await new Promise((r) => setTimeout(r, RENEW_MS));
272
+ const tokens = [...inFlight.keys()];
273
+ if (!tokens.length) continue;
274
+ const { ok, data } = await call("/api/external-tasks/renew", {
275
+ worker_id: WORKER_ID,
276
+ tokens,
277
+ lease_ms: LEASE_MS,
278
+ });
279
+ if (!ok) continue;
280
+
281
+ // Cancelled: the process was stopped, so the evaluation is abandoned and the claim handed
282
+ // back. Aborting first is the point of the list — waiting for the script to finish would
283
+ // keep burning a core on work an operator has already stopped. The release rides run()'s
284
+ // own catch, so nothing is released twice.
285
+ for (const token of (data?.cancelled ?? []) as string[]) {
286
+ inFlight.get(token)?.abort.abort();
287
+ }
288
+ // Lost: someone else holds this claim now. The work continues and its answer will be
289
+ // refused — that is not fixable here — but say so, because it is the signal that LEASE_MS
290
+ // is too short for what these scripts actually take. Deliberately NOT released: the claim
291
+ // is the new holder's, and releasing would bump the epoch out from under it.
292
+ const lost = (data?.lost ?? []) as string[];
293
+ if (lost.length) {
294
+ console.error(`lost ${lost.length}/${tokens.length} claims; a lease lapsed under load`);
295
+ }
296
+ }
297
+ }
298
+
299
+ async function pollLoop(): Promise<void> {
300
+ while (running) {
301
+ const free = CONCURRENCY - inFlight.size;
302
+ const jobs = free > 0 ? await claim(free) : [];
303
+ for (const job of jobs) {
304
+ const abort = new AbortController();
305
+ inFlight.set(job.token, { job, abort });
306
+ void run(job, abort.signal).finally(() => inFlight.delete(job.token));
307
+ }
308
+ // Only idle when there was nothing to take: a full queue should be drained at the speed the
309
+ // realms allow, not at the poll interval.
310
+ if (jobs.length === 0) await new Promise((r) => setTimeout(r, POLL_MS));
311
+ }
312
+ }
313
+
314
+ async function shutdown(signal: string): Promise<void> {
315
+ if (!running) return;
316
+ running = false;
317
+ const tokens = [...inFlight.keys()];
318
+ console.log(`${signal}: releasing ${tokens.length} claim(s)`);
319
+ // Hand work back rather than letting it sit out its lease. The evaluations still running are
320
+ // abandoned, which is exactly what the release says: nobody answered.
321
+ await Promise.all(tokens.map(release));
322
+ process.exit(0);
323
+ }
324
+
325
+ process.on("SIGINT", () => void shutdown("SIGINT"));
326
+ process.on("SIGTERM", () => void shutdown("SIGTERM"));
327
+
328
+ console.log(
329
+ `evaluator worker ${WORKER_ID} polling ${SERVER} (concurrency=${CONCURRENCY}, lease=${LEASE_MS}ms)`,
330
+ );
331
+ void renewLoop();
332
+ void pollLoop();