@genroc/eval-node 0.0.0-edge.d8176a7 → 0.0.0-edge.ee19083
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -35
- package/dist/eval.js +65 -0
- package/dist/import.js +348 -0
- package/dist/realm.js +113 -0
- package/dist/worker.js +285 -0
- package/eval.ts +11 -4
- package/import.ts +17 -18
- package/package.json +6 -4
- package/realm.ts +61 -77
- package/worker.ts +8 -1
- package/bin/import.mjs +0 -4
- package/bin/worker.mjs +0 -2
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 —
|
|
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 {
|
|
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
|
-
|
|
14
|
-
|
|
15
|
-
|
|
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
|
-
|
|
28
|
-
|
|
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
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
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
|
-
/**
|
|
64
|
-
*
|
|
65
|
-
|
|
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
|
|
70
|
-
for (let i = 0; i < lines.length; i++) if (
|
|
71
|
-
const
|
|
72
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
66
|
+
source = req.code;
|
|
102
67
|
|
|
103
|
-
let
|
|
68
|
+
let main: unknown;
|
|
104
69
|
try {
|
|
105
|
-
|
|
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"
|
|
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
|
|
88
|
+
value = await (main as (input: unknown) => unknown)(req.input);
|
|
115
89
|
} catch (err) {
|
|
116
|
-
return { ok: false, failure: describe(err, "threw"
|
|
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"
|
|
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
|
-
|
|
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,9 +1,11 @@
|
|
|
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
|
|
|
8
|
+
import { readFileSync } from "node:fs";
|
|
7
9
|
import { evaluate, type EvalRequest, type FailureKind } from "./eval.ts";
|
|
8
10
|
|
|
9
11
|
const SERVER = (process.env.GENROC_SERVER ?? "http://localhost:8448").replace(/\/$/, "");
|
|
@@ -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
|
-
|
|
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
|
package/bin/import.mjs
DELETED
package/bin/worker.mjs
DELETED