@genroc/eval-node 0.0.0-edge.f85ea85 → 0.0.0-edge.f8ffa72f

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/realm.ts CHANGED
@@ -2,88 +2,45 @@
2
2
  // thread the host can kill mid-loop — the only thing that bounds a synchronous busy loop.
3
3
  // eval.ts owns the budget and does the killing; nothing here knows about time.
4
4
  //
5
- // Everything that touches the script's VALUE lives on this side of the boundary — compiling,
5
+ // Everything that touches the script's VALUE lives on this side of the boundary — loading,
6
6
  // classifying, serialising — because this is the only realm the value exists in.
7
7
 
8
- import { createRequire } from "node:module";
8
+ import { registerHooks } from "node:module";
9
9
  import { parentPort } from "node:worker_threads";
10
10
 
11
11
  import type { EvalFailure, FailureKind, WorkerReply, WorkerRequest } from "./eval.ts";
12
12
 
13
- const AsyncFunction = async function () {}.constructor as new (
14
- ...args: string[]
15
- ) => (...args: unknown[]) => Promise<unknown>;
16
-
17
- const STRICT = '"use strict";\n';
18
-
19
- // Bundled `node:*` imports survive as `require` calls — the importer externalises builtins and
20
- // inlines everything else — and a function built by the AsyncFunction constructor has no
21
- // `require` in scope. Passing one in is what makes an import of a builtin work at runtime rather than at
22
- // typecheck only. Resolution is anchored here, which is right: only builtins reach it.
23
- const scriptRequire = createRequire(import.meta.url);
13
+ // The script is IMPORTED as a module under a URL of our own, not compiled from a string: its
14
+ // frames then carry the author's own line numbers, and an `import` of a node builtin resolves
15
+ // the way it does everywhere else.
16
+ const SCRIPT_URL = "script:main";
24
17
  const STACK_BYTES = 2_048;
25
18
 
26
- /**
27
- * Line offset the AsyncFunction preamble adds, measured rather than assumed: the generated
28
- * wrapper's shape is engine-specific, and a hardcoded number silently misreports every
29
- * script's error location the day it changes.
30
- */
31
- const lineOffset: Promise<number> = (async () => {
32
- // Same parameter list as a real compile: the preamble is what is being measured.
33
- const probe = new AsyncFunction("input", "require", STRICT + "throw new Error('probe');");
34
- try {
35
- await probe();
36
- return 0;
37
- } catch (err) {
38
- return reportedLine(err) - 1;
39
- }
40
- })();
41
-
42
- // V8 marks a frame compiled by the AsyncFunction constructor with the site that CALLED the
43
- // constructor, then the script's OWN position:
44
- // at inner (eval at run (file:///…/worker.ts:107:10), <anonymous>:6:9)
45
- // `eval at` is therefore what separates script frames from runner plumbing — matched without
46
- // the function name, which is whatever encloses the `new AsyncFunction` below. The LAST such
47
- // frame is the body's top level: frames interleave, since a script can throw inside a native
48
- // callback.
49
- const SCRIPT_FRAME = /\(eval at /;
50
- // The trailing `<anonymous>:LINE:COL` — the script's position, after the host file's own.
51
- const POSITION = /<anonymous>:(\d+):(\d+)\)?\s*$/;
52
- // ` at name (` — absent on the top-level frame, which V8 names `eval`.
53
- const FRAME_NAME = /^\s*at\s+(?:async\s+)?([^\s(]+)\s*\(/;
19
+ // The only channel a load hook has to the source. Written per request and read once — a realm
20
+ // evaluates one script and is then discarded, so no second execution can observe it.
21
+ let source = "";
54
22
 
55
- /** Line number of the throw as the engine reported it, or 1 if the stack is unreadable. */
56
- function reportedLine(err: unknown): number {
57
- const stack = err instanceof Error && typeof err.stack === "string" ? err.stack : "";
58
- const frame = stack.split("\n").find((l) => SCRIPT_FRAME.test(l)) ?? "";
59
- const m = frame.match(POSITION);
60
- return m ? Number(m[1]) : 1;
61
- }
23
+ registerHooks({
24
+ resolve: (specifier, context, next) =>
25
+ specifier === SCRIPT_URL ? { url: SCRIPT_URL, shortCircuit: true } : next(specifier, context),
26
+ load: (url, context, next) =>
27
+ url === SCRIPT_URL ? { format: "module", source, shortCircuit: true } : next(url, context),
28
+ });
62
29
 
63
- /** Renumbers each script frame to the line the AUTHOR wrote and drops the runner's own.
64
- * Rewriting the whole location is also what keeps the runner's path out of a script's
65
- * stack — V8 puts it inside every compiled frame. */
66
- function scriptStack(err: unknown, offset: number): string | undefined {
30
+ /** Keeps the frames that are the script's own. Everything below the last of them is runner
31
+ * plumbing the author cannot act on, and V8 puts this file's path in it. */
32
+ function scriptStack(err: unknown): string | undefined {
67
33
  if (!(err instanceof Error) || typeof err.stack !== "string") return undefined;
68
34
  const lines = err.stack.split("\n");
69
- let boundary = -1;
70
- for (let i = 0; i < lines.length; i++) if (SCRIPT_FRAME.test(lines[i]!)) boundary = i;
71
- const frames = (boundary >= 0 ? lines.slice(0, boundary + 1) : lines.slice(0, 1))
72
- .map((line) => {
73
- const pos = line.match(POSITION);
74
- if (!pos) return line; // the `Error: message` header and native frames, kept as-is
75
- const name = line.match(FRAME_NAME)?.[1];
76
- const at = name && name !== "eval" && name !== "anonymous" ? `at ${name} ` : "at ";
77
- const indent = line.match(/^\s*/)![0];
78
- return `${indent}${at}(script:${Math.max(1, Number(pos[1]) - offset)}:${pos[2]})`;
79
- })
80
- .join("\n");
81
- return frames.length > STACK_BYTES ? frames.slice(0, STACK_BYTES) : frames;
35
+ let last = 0;
36
+ for (let i = 0; i < lines.length; i++) if (lines[i]!.includes(SCRIPT_URL)) last = i;
37
+ const stack = lines.slice(0, last + 1).join("\n");
38
+ return stack.length > STACK_BYTES ? stack.slice(0, STACK_BYTES) : stack;
82
39
  }
83
40
 
84
- function describe(err: unknown, kind: FailureKind, offset: number): EvalFailure {
41
+ function describe(err: unknown, kind: FailureKind): EvalFailure {
85
42
  if (err instanceof Error) {
86
- return { kind, name: err.name, message: err.message, stack: scriptStack(err, offset) };
43
+ return { kind, name: err.name, message: err.message, stack: scriptStack(err) };
87
44
  }
88
45
  // A script may throw a non-Error (`throw {code: "x"}`), so name/message must not assume one.
89
46
  return { kind, name: "Thrown", message: safeText(err) };
@@ -97,23 +54,40 @@ function safeText(v: unknown): string {
97
54
  }
98
55
  }
99
56
 
57
+ /** A module that will not parse, or names an import nothing resolves, is broken code — only
58
+ * editing it helps. Anything else thrown by the import is the module's top level running,
59
+ * which is the script throwing. */
60
+ function unloadable(err: unknown): boolean {
61
+ const code = (err as { code?: unknown } | null)?.code;
62
+ return err instanceof SyntaxError || (typeof code === "string" && code.startsWith("ERR_MODULE"));
63
+ }
64
+
100
65
  async function run(req: WorkerRequest): Promise<WorkerReply> {
101
- const offset = await lineOffset;
66
+ source = req.code;
102
67
 
103
- let fn: (...args: unknown[]) => Promise<unknown>;
68
+ let main: unknown;
104
69
  try {
105
- // No compile cache: the realm is discarded after this execution, so a cache in it could
106
- // never be hit. Repeated compilation is the price of the fresh global object.
107
- fn = new AsyncFunction("input", "require", STRICT + req.code);
70
+ main = (await import(SCRIPT_URL)).default;
108
71
  } catch (err) {
109
- return { ok: false, failure: describe(err, "compile_error", offset) };
72
+ return { ok: false, failure: describe(err, unloadable(err) ? "compile_error" : "threw") };
73
+ }
74
+ if (typeof main !== "function") {
75
+ const got = main === undefined ? "no default export" : `a ${typeof main}`;
76
+ return {
77
+ ok: false,
78
+ failure: {
79
+ kind: "compile_error",
80
+ name: "NoDefaultExport",
81
+ message: `a script must export default a function; this one has ${got}`,
82
+ },
83
+ };
110
84
  }
111
85
 
112
86
  let value: unknown;
113
87
  try {
114
- value = await fn(req.input, scriptRequire);
88
+ value = await (main as (input: unknown) => unknown)(req.input);
115
89
  } catch (err) {
116
- return { ok: false, failure: describe(err, "threw", offset) };
90
+ return { ok: false, failure: describe(err, "threw") };
117
91
  }
118
92
 
119
93
  try {
@@ -121,12 +95,22 @@ async function run(req: WorkerRequest): Promise<WorkerReply> {
121
95
  // spells null, which is the right reading of a script that returned nothing.
122
96
  return { ok: true, body: value === undefined ? "" : JSON.stringify(value) ?? "" };
123
97
  } catch (err) {
124
- return { ok: false, failure: describe(err, "nonserializable", offset) };
98
+ return { ok: false, failure: describe(err, "nonserializable") };
125
99
  }
126
100
  }
127
101
 
102
+ // The realm's stdio is a pipe to the host thread, and eval.ts terminates this thread the moment
103
+ // the reply lands — so whatever a script wrote last is still in the pipe when it dies. An empty
104
+ // write's callback fires once the queue ahead of it has drained, which makes the reply a barrier
105
+ // for `console` and a direct process.stdout.write alike: both are this stream.
106
+ function flush(stream: NodeJS.WriteStream): Promise<void> {
107
+ return new Promise((resolve) => stream.write("", () => resolve()));
108
+ }
109
+
128
110
  // Non-null because this module only ever runs as a worker entry point; a null port here
129
111
  // would mean eval.ts loaded it as a plain module, which nothing does.
130
112
  parentPort!.on("message", async (req: WorkerRequest) => {
131
- parentPort!.postMessage(await run(req));
113
+ const reply = await run(req);
114
+ await Promise.all([flush(process.stdout), flush(process.stderr)]);
115
+ parentPort!.postMessage(reply);
132
116
  });
package/worker.ts CHANGED
@@ -1,10 +1,12 @@
1
+ #!/usr/bin/env node
1
2
  // The queue worker: claims parked `external` script tasks from genroc, evaluates each in its
2
3
  // own realm, and answers. This is the whole genroc-facing half — eval.ts and realm.ts know
3
4
  // nothing about the queue, which is what keeps the containment strategy swappable.
4
5
  //
5
6
  // See README.md for the contract, and specs/external-task-queue.md for the queue itself.
6
7
 
7
- import { evaluate, type EvalRequest, type FailureKind } from "./eval.ts";
8
+ import { readFileSync } from "node:fs";
9
+ import { Cancelled, evaluate, type EvalRequest, type FailureKind } from "./eval.ts";
8
10
 
9
11
  const SERVER = (process.env.GENROC_SERVER ?? "http://localhost:8448").replace(/\/$/, "");
10
12
  const WORKER_ID = process.env.WORKER_ID ?? `evaluator-${process.pid}`;
@@ -16,7 +18,12 @@ const WORKER_ID = process.env.WORKER_ID ?? `evaluator-${process.pid}`;
16
18
  // Sent as a header rather than in the URL because Node's fetch REFUSES a URL carrying
17
19
  // credentials ("Request cannot be constructed from a URL that includes credentials"), so the
18
20
  // basic-auth-in-the-URL trick that works for genctl is not available here.
19
- const TOKEN = process.env.GENROC_TOKEN ?? "";
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() : "");
20
27
  const authHeaders: Record<string, string> = TOKEN ? { authorization: `Bearer ${TOKEN}` } : {};
21
28
  // Concurrency is the worker's to set, and that is the point of pulling: under the old fetch
22
29
  // shape genroc decided how many scripts ran at once (--max-concurrent, default 200) and the
@@ -36,8 +43,8 @@ type ObjectEntry = { path: (string | number)[]; ref: string; size: number };
36
43
  type QueueTask = {
37
44
  token: string;
38
45
  process: string;
39
- task_id: string;
40
- input: unknown;
46
+ task: string;
47
+ external_input: unknown;
41
48
  objects?: ObjectEntry[];
42
49
  raises?: Record<string, unknown>;
43
50
  };
@@ -69,15 +76,15 @@ async function fetchObject(ref: string): Promise<unknown> {
69
76
  /** Put each listed value back where its path says it belongs. Paths are arrays of keys, so this
70
77
  * needs no parser: the whole reason they are not JSON Pointer strings. */
71
78
  async function resolveObjects(job: QueueTask): Promise<unknown> {
72
- let input: any = job.input;
79
+ let input: any = job.external_input;
73
80
  for (const e of job.objects ?? []) {
74
81
  const value = await fetchObject(e.ref);
75
82
  if (e.path.length === 0) {
76
83
  input = value;
77
84
  continue;
78
85
  }
79
- // The path is rooted at the entry and starts with "input", which is the value being rebuilt.
80
- const rest = e.path[0] === "input" ? e.path.slice(1) : e.path;
86
+ // The path is rooted at the entry and starts with "external_input", the value being rebuilt.
87
+ const rest = e.path[0] === "external_input" ? e.path.slice(1) : e.path;
81
88
  if (rest.length === 0) {
82
89
  input = value;
83
90
  continue;
@@ -128,7 +135,12 @@ function asEvalRequest(input: unknown): EvalRequest | string {
128
135
  };
129
136
  }
130
137
 
131
- const inFlight = new Map<string, QueueTask>();
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>();
132
144
  let running = true;
133
145
 
134
146
  // Whether the last claim reached genroc. A worker polls several times a second, so an
@@ -196,7 +208,7 @@ async function answer(token: string, outcome: Record<string, unknown>): Promise<
196
208
  await release(token);
197
209
  }
198
210
 
199
- async function run(job: QueueTask): Promise<void> {
211
+ async function run(job: QueueTask, signal: AbortSignal): Promise<void> {
200
212
  let resolved: unknown;
201
213
  try {
202
214
  resolved = await resolveObjects(job);
@@ -217,8 +229,16 @@ async function run(job: QueueTask): Promise<void> {
217
229
 
218
230
  let result;
219
231
  try {
220
- result = await evaluate(req);
232
+ result = await evaluate(req, signal);
221
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
+ }
222
242
  // The RUNNER faulted, not the script — the one class where a retry can help. There is no
223
243
  // error code for it on purpose: releasing the claim is how a queue spells "retryable", and
224
244
  // it puts the task in front of a different worker instead of burning the definition's
@@ -256,11 +276,22 @@ async function renewLoop(): Promise<void> {
256
276
  tokens,
257
277
  lease_ms: LEASE_MS,
258
278
  });
259
- // A short count means a claim lapsed and was taken over. Nothing to do about it — the work
260
- // continues and its answer will be refused — but say so, because it is the signal that
261
- // LEASE_MS is too short for what these scripts actually take.
262
- if (ok && data?.renewed < tokens.length) {
263
- console.error(`renewed ${data.renewed}/${tokens.length} claims; a lease lapsed under load`);
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`);
264
295
  }
265
296
  }
266
297
  }
@@ -270,8 +301,9 @@ async function pollLoop(): Promise<void> {
270
301
  const free = CONCURRENCY - inFlight.size;
271
302
  const jobs = free > 0 ? await claim(free) : [];
272
303
  for (const job of jobs) {
273
- inFlight.set(job.token, job);
274
- void run(job).finally(() => inFlight.delete(job.token));
304
+ const abort = new AbortController();
305
+ inFlight.set(job.token, { job, abort });
306
+ void run(job, abort.signal).finally(() => inFlight.delete(job.token));
275
307
  }
276
308
  // Only idle when there was nothing to take: a full queue should be drained at the speed the
277
309
  // realms allow, not at the poll interval.
package/bin/import.mjs DELETED
@@ -1,4 +0,0 @@
1
- #!/usr/bin/env node
2
- // npm `bin` entries need a shebang and a stable extension; Node's type stripping handles the
3
- // .ts behind it. .genroc points here: command: [npx, genroc-import]
4
- import "../import.ts";
package/bin/worker.mjs DELETED
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import "../worker.ts";