@genroc/eval-node 0.0.0-edge.d8176a7 → 0.0.0-edge.dc4ff88
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 +54 -36
- package/dist/eval.js +65 -0
- package/dist/import.js +361 -0
- package/dist/realm.js +113 -0
- package/dist/worker.js +285 -0
- package/eval.ts +11 -4
- package/import.ts +89 -39
- 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/import.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
1
2
|
// The code-phase resolver: manifest on stdin, `{"code": [...]}` on stdout, non-zero exit
|
|
2
3
|
// with the diagnostic on stderr. genctl never parses TypeScript and this never parses YAML
|
|
3
4
|
// — the manifest is the whole contract. See specs/source-resolution.md.
|
|
@@ -51,7 +52,7 @@ async function exists(path: string): Promise<boolean> {
|
|
|
51
52
|
}
|
|
52
53
|
}
|
|
53
54
|
|
|
54
|
-
/** Creates the parent directory, which `.genroc/` relies on: nothing else makes it. */
|
|
55
|
+
/** Creates the parent directory, which `.genroc-cache/` relies on: nothing else makes it. */
|
|
55
56
|
async function write(path: string, content: string): Promise<void> {
|
|
56
57
|
await mkdir(dirname(path), { recursive: true });
|
|
57
58
|
await writeFile(path, content);
|
|
@@ -71,13 +72,16 @@ function tsType(s: Schema | undefined, used: Set<string>): string {
|
|
|
71
72
|
if (Array.isArray(s.enum)) {
|
|
72
73
|
return s.enum.map((v: unknown) => JSON.stringify(v)).join(" | ") || "never";
|
|
73
74
|
}
|
|
74
|
-
if (Array.isArray(s.anyOf))
|
|
75
|
-
|
|
75
|
+
if (Array.isArray(s.anyOf))
|
|
76
|
+
return union(s.anyOf.map((a: Schema) => tsType(a, used)));
|
|
77
|
+
if (Array.isArray(s.oneOf))
|
|
78
|
+
return union(s.oneOf.map((a: Schema) => tsType(a, used)));
|
|
76
79
|
if (Array.isArray(s.allOf)) {
|
|
77
80
|
return s.allOf.map((a: Schema) => tsType(a, used)).join(" & ") || "unknown";
|
|
78
81
|
}
|
|
79
82
|
|
|
80
|
-
const types: string[] =
|
|
83
|
+
const types: string[] =
|
|
84
|
+
s.type === undefined ? [] : Array.isArray(s.type) ? s.type : [s.type];
|
|
81
85
|
if (types.length === 0) {
|
|
82
86
|
// The top type: `{}` means unknown, not "an empty object". specs/unknown-type.md.
|
|
83
87
|
return s.properties ? objectType(s, used) : "unknown";
|
|
@@ -110,8 +114,13 @@ function objectType(s: Schema, used: Set<string>): string {
|
|
|
110
114
|
const required = new Set<string>(s.required ?? []);
|
|
111
115
|
const lines: string[] = [];
|
|
112
116
|
for (const [key, sub] of Object.entries(props)) {
|
|
113
|
-
const doc =
|
|
114
|
-
|
|
117
|
+
const doc =
|
|
118
|
+
typeof sub.description === "string"
|
|
119
|
+
? ` /** ${sub.description} */\n`
|
|
120
|
+
: "";
|
|
121
|
+
lines.push(
|
|
122
|
+
`${doc} ${propKey(key)}${required.has(key) ? "" : "?"}: ${tsType(sub, used)};`,
|
|
123
|
+
);
|
|
115
124
|
}
|
|
116
125
|
if (s.additionalProperties && typeof s.additionalProperties === "object") {
|
|
117
126
|
lines.push(` [key: string]: ${tsType(s.additionalProperties, used)};`);
|
|
@@ -127,9 +136,13 @@ function union(parts: string[]): string {
|
|
|
127
136
|
|
|
128
137
|
const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
129
138
|
const propKey = (k: string) => (IDENT.test(k) ? k : JSON.stringify(k));
|
|
130
|
-
const identifier = (n: string) =>
|
|
139
|
+
const identifier = (n: string) =>
|
|
140
|
+
IDENT.test(n) ? n : `Def_${n.replace(/[^A-Za-z0-9_$]/g, "_")}`;
|
|
131
141
|
|
|
132
|
-
function deref(
|
|
142
|
+
function deref(
|
|
143
|
+
s: Schema | undefined,
|
|
144
|
+
defs: Record<string, Schema>,
|
|
145
|
+
): Schema | undefined {
|
|
133
146
|
let cur = s;
|
|
134
147
|
for (let i = 0; cur && typeof cur.$ref === "string" && i < 16; i++) {
|
|
135
148
|
cur = defs[cur.$ref.replace(/^#\/\$defs\//, "")];
|
|
@@ -141,7 +154,10 @@ function deref(s: Schema | undefined, defs: Record<string, Schema>): Schema | un
|
|
|
141
154
|
* `{code, input, timeout_ms, …}`, and only its `input` field is bound as the script's
|
|
142
155
|
* parameter. genroc cannot know that; this file owns the evaluator's wire contract, so
|
|
143
156
|
* the navigation belongs here rather than in genctl. */
|
|
144
|
-
function scriptInput(
|
|
157
|
+
function scriptInput(
|
|
158
|
+
site: Site,
|
|
159
|
+
defs: Record<string, Schema>,
|
|
160
|
+
): Schema | undefined {
|
|
145
161
|
const action = deref(site.input, defs);
|
|
146
162
|
const bound = action?.properties?.input;
|
|
147
163
|
return bound ?? site.input;
|
|
@@ -188,7 +204,10 @@ function typesPathFor(scriptPath: string): string {
|
|
|
188
204
|
/** The nearest tsconfig above the script — the one the author's editor already reads. Two
|
|
189
205
|
* different configs mean a red editor over a clean apply, or the reverse. The walk stops at
|
|
190
206
|
* the project root: above it is not this project. */
|
|
191
|
-
async function nearestTsconfig(
|
|
207
|
+
async function nearestTsconfig(
|
|
208
|
+
from: string,
|
|
209
|
+
root: string,
|
|
210
|
+
): Promise<string | null> {
|
|
192
211
|
for (let dir = from; ; dir = dirname(dir)) {
|
|
193
212
|
const candidate = join(dir, "tsconfig.json");
|
|
194
213
|
if (await exists(candidate)) return candidate;
|
|
@@ -197,7 +216,9 @@ async function nearestTsconfig(from: string, root: string): Promise<string | nul
|
|
|
197
216
|
}
|
|
198
217
|
|
|
199
218
|
async function typecheck(root: string, sites: Site[]): Promise<void> {
|
|
200
|
-
|
|
219
|
+
// NOT `.genroc`: that is the project config FILE, and a directory of the same name cannot
|
|
220
|
+
// coexist with it. The suffix is what keeps the scratch area out of its way.
|
|
221
|
+
const dir = join(root, ".genroc-cache");
|
|
201
222
|
await write(join(dir, ".gitignore"), "*\n");
|
|
202
223
|
|
|
203
224
|
// One tsc per distinct base config: `extends` takes a single base, so merging two would
|
|
@@ -229,12 +250,18 @@ async function typecheck(root: string, sites: Site[]): Promise<void> {
|
|
|
229
250
|
// base config there is nothing to opt in with, so the default stays none.
|
|
230
251
|
...(base ? {} : { types: [] }),
|
|
231
252
|
},
|
|
232
|
-
files: group.flatMap((s) => [
|
|
253
|
+
files: group.flatMap((s) => [
|
|
254
|
+
relative(dir, s.path),
|
|
255
|
+
relative(dir, typesPathFor(s.path)),
|
|
256
|
+
]),
|
|
233
257
|
// `files` overrides the base's, but a base `include` survives beside it and would
|
|
234
258
|
// drag the author's whole tree in, to be checked under the worker lib.
|
|
235
259
|
include: [],
|
|
236
260
|
};
|
|
237
|
-
const configPath = join(
|
|
261
|
+
const configPath = join(
|
|
262
|
+
dir,
|
|
263
|
+
groups.size === 1 ? "tsconfig.json" : `tsconfig.${n++}.json`,
|
|
264
|
+
);
|
|
238
265
|
await write(configPath, JSON.stringify(config, null, 2));
|
|
239
266
|
await runTsc(root, configPath);
|
|
240
267
|
}
|
|
@@ -282,7 +309,10 @@ const transpile: Plugin = {
|
|
|
282
309
|
},
|
|
283
310
|
};
|
|
284
311
|
|
|
285
|
-
const BUILTIN = new Set([
|
|
312
|
+
const BUILTIN = new Set([
|
|
313
|
+
...builtinModules,
|
|
314
|
+
...builtinModules.map((m) => `node:${m}`),
|
|
315
|
+
]);
|
|
286
316
|
|
|
287
317
|
/** Resolves imports through TYPESCRIPT, using the same config the typecheck ran under, so a
|
|
288
318
|
* `paths` alias that compiles also bundles. Reimplementing `paths` here would be a second
|
|
@@ -293,25 +323,37 @@ function tsResolve(configPath: string | null): Plugin {
|
|
|
293
323
|
let options: ts.CompilerOptions = {};
|
|
294
324
|
if (configPath) {
|
|
295
325
|
const read = ts.readConfigFile(configPath, ts.sys.readFile);
|
|
296
|
-
options = ts.parseJsonConfigFileContent(
|
|
326
|
+
options = ts.parseJsonConfigFileContent(
|
|
327
|
+
read.config ?? {},
|
|
328
|
+
ts.sys,
|
|
329
|
+
dirname(configPath),
|
|
330
|
+
).options;
|
|
297
331
|
}
|
|
298
332
|
return {
|
|
299
333
|
name: "genroc-ts-resolve",
|
|
300
334
|
resolveId(source, importer) {
|
|
301
335
|
if (!importer || BUILTIN.has(source)) return null;
|
|
302
|
-
const { resolvedModule } = ts.resolveModuleName(
|
|
303
|
-
|
|
304
|
-
|
|
336
|
+
const { resolvedModule } = ts.resolveModuleName(
|
|
337
|
+
source,
|
|
338
|
+
importer,
|
|
339
|
+
options,
|
|
340
|
+
ts.sys,
|
|
341
|
+
);
|
|
342
|
+
if (!resolvedModule || resolvedModule.isExternalLibraryImport)
|
|
343
|
+
return null;
|
|
344
|
+
return resolvedModule.resolvedFileName.endsWith(".d.ts")
|
|
345
|
+
? null
|
|
346
|
+
: resolvedModule.resolvedFileName;
|
|
305
347
|
},
|
|
306
348
|
};
|
|
307
349
|
}
|
|
308
350
|
|
|
309
|
-
/** Bundles to
|
|
310
|
-
*
|
|
311
|
-
*
|
|
351
|
+
/** Bundles to a self-contained ES module, which is what the evaluator imports: the default
|
|
352
|
+
* export it calls is the author's own, so nothing wraps or rewrites the code between the two.
|
|
353
|
+
* Bundling is entirely the importer's job, so a definition version pins its code forever. */
|
|
312
354
|
async function bundle(site: Site, root: string): Promise<string> {
|
|
313
|
-
// Builtins are EXTERNALISED as
|
|
314
|
-
// unresolved is a REFUSAL, not an external: rollup's default is to leave it as
|
|
355
|
+
// Builtins are EXTERNALISED as imports the realm resolves natively. Anything else
|
|
356
|
+
// unresolved is a REFUSAL, not an external: rollup's default is to leave it as an import
|
|
315
357
|
// of a module that will not be there, which bundles clean and fails at runtime.
|
|
316
358
|
const built = await rollup({
|
|
317
359
|
input: site.path,
|
|
@@ -327,23 +369,26 @@ async function bundle(site: Site, root: string): Promise<string> {
|
|
|
327
369
|
],
|
|
328
370
|
onwarn(warning) {
|
|
329
371
|
if (warning.code === "UNRESOLVED_IMPORT") {
|
|
330
|
-
die(
|
|
372
|
+
die(
|
|
373
|
+
`${site.path}: cannot resolve ${warning.exporter ?? "an import"} — is it installed?`,
|
|
374
|
+
);
|
|
331
375
|
}
|
|
332
376
|
},
|
|
333
|
-
}).catch((e: unknown) =>
|
|
377
|
+
}).catch((e: unknown) =>
|
|
378
|
+
die(`${site.path}: ${e instanceof Error ? e.message : String(e)}`),
|
|
379
|
+
);
|
|
334
380
|
|
|
335
|
-
const { output } = await built.generate({
|
|
381
|
+
const { output } = await built.generate({
|
|
382
|
+
format: "es",
|
|
383
|
+
inlineDynamicImports: true,
|
|
384
|
+
});
|
|
336
385
|
await built.close();
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
` throw new Error(${JSON.stringify(`${site.path} has no default export function`)});`,
|
|
344
|
-
"}",
|
|
345
|
-
"return await __genroc_main(input);",
|
|
346
|
-
].join("\n");
|
|
386
|
+
// Refused here rather than in the realm: the evaluator can only report it against a running
|
|
387
|
+
// instance, and the file it names is on this machine.
|
|
388
|
+
if (!output[0].exports.includes("default")) {
|
|
389
|
+
die(`${site.path}: a script must \`export default\` the function to run`);
|
|
390
|
+
}
|
|
391
|
+
return output[0].code;
|
|
347
392
|
}
|
|
348
393
|
|
|
349
394
|
// ── main ───────────────────────────────────────────────────────────────────────
|
|
@@ -356,14 +401,16 @@ const stdin: string = await new Promise((resolve, reject) => {
|
|
|
356
401
|
process.stdin.on("error", reject);
|
|
357
402
|
});
|
|
358
403
|
const manifest = JSON.parse(stdin) as Manifest;
|
|
359
|
-
if (!manifest || !Array.isArray(manifest.sites))
|
|
404
|
+
if (!manifest || !Array.isArray(manifest.sites))
|
|
405
|
+
die("stdin is not a genroc resolver manifest");
|
|
360
406
|
|
|
361
407
|
// One script at two sites with different input types is a refusal, not a union: the union
|
|
362
408
|
// is sound and would typecheck a body that is wrong at one of the sites.
|
|
363
409
|
const byPath = new Map<string, Site>();
|
|
364
410
|
for (const site of manifest.sites) {
|
|
365
411
|
const seen = byPath.get(site.path);
|
|
366
|
-
const defsOf = (x: Site) =>
|
|
412
|
+
const defsOf = (x: Site) =>
|
|
413
|
+
(manifest.schemas[x.process]?.$defs ?? {}) as Record<string, Schema>;
|
|
367
414
|
if (
|
|
368
415
|
seen &&
|
|
369
416
|
JSON.stringify(scriptInput(seen, defsOf(seen))) !==
|
|
@@ -378,7 +425,10 @@ for (const site of manifest.sites) {
|
|
|
378
425
|
}
|
|
379
426
|
|
|
380
427
|
for (const site of byPath.values()) {
|
|
381
|
-
const defs = (manifest.schemas[site.process]?.$defs ?? {}) as Record<
|
|
428
|
+
const defs = (manifest.schemas[site.process]?.$defs ?? {}) as Record<
|
|
429
|
+
string,
|
|
430
|
+
Schema
|
|
431
|
+
>;
|
|
382
432
|
await write(typesPathFor(site.path), declarations(site, defs));
|
|
383
433
|
}
|
|
384
434
|
|
package/package.json
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@genroc/eval-node",
|
|
3
|
-
"version": "0.0.0-edge.
|
|
3
|
+
"version": "0.0.0-edge.dc4ff88",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=24"
|
|
7
7
|
},
|
|
8
8
|
"scripts": {
|
|
9
|
+
"build": "tsc -p tsconfig.build.json",
|
|
10
|
+
"prepublishOnly": "npm run build",
|
|
9
11
|
"work": "node worker.ts",
|
|
10
12
|
"typecheck": "tsc --noEmit"
|
|
11
13
|
},
|
|
@@ -28,11 +30,11 @@
|
|
|
28
30
|
},
|
|
29
31
|
"homepage": "https://genroc.org",
|
|
30
32
|
"bin": {
|
|
31
|
-
"genroc-import": "
|
|
32
|
-
"genroc-eval-node": "
|
|
33
|
+
"genroc-import": "dist/import.js",
|
|
34
|
+
"genroc-eval-node": "dist/worker.js"
|
|
33
35
|
},
|
|
34
36
|
"files": [
|
|
35
|
-
"
|
|
37
|
+
"dist",
|
|
36
38
|
"*.ts",
|
|
37
39
|
"tsconfig.json",
|
|
38
40
|
"README.md"
|
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