@genroc/eval-node 0.0.0-edge.e32e188 → 0.0.0-edge.e4a77190
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 +1 -1
- package/dist/eval.js +9 -17
- package/dist/import.js +50 -88
- package/dist/realm.js +8 -16
- package/dist/worker.js +33 -65
- package/eval.ts +13 -23
- package/import.ts +63 -101
- package/package.json +1 -1
- package/realm.ts +8 -16
- package/worker.ts +37 -70
package/README.md
CHANGED
|
@@ -26,7 +26,7 @@ resolver's exit code, so a stored definition cannot hold code that failed to typ
|
|
|
26
26
|
|
|
27
27
|
## Building
|
|
28
28
|
|
|
29
|
-
|
|
29
|
+
pnpm run build # tsc -p tsconfig.build.json -> dist/
|
|
30
30
|
|
|
31
31
|
The published package is JavaScript, not TypeScript. **Node refuses to strip types for files
|
|
32
32
|
under `node_modules`**, so shipping `.ts` works from a checkout and fails for every consumer —
|
package/dist/eval.js
CHANGED
|
@@ -1,28 +1,21 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
// the containment stays swappable.
|
|
5
|
-
//
|
|
6
|
-
// The containment is a Worker per execution (realm.ts). It is what makes the budget real:
|
|
7
|
-
// a synchronous busy loop never yields, so no in-process timer can interrupt it, and only a
|
|
8
|
-
// thread the host can kill bounds it.
|
|
1
|
+
// Imports a script module in its own realm (a Worker per execution, realm.ts), calls its default
|
|
2
|
+
// export, and classifies every outcome (README.md). Only a killable thread bounds a synchronous
|
|
3
|
+
// busy loop, which is what makes the budget real. Knows nothing of genroc; worker.ts does.
|
|
9
4
|
import { Worker } from "node:worker_threads";
|
|
10
5
|
const DEFAULT_TIMEOUT_MS = 5_000;
|
|
11
6
|
// Resolved from THIS file's own extension: run from a checkout it is `.ts`, and from the
|
|
12
7
|
// published package `.js`, because Node will not strip types under node_modules.
|
|
13
8
|
const REALM_URL = new URL(import.meta.url.endsWith(".ts") ? "./realm.ts" : "./realm.js", import.meta.url);
|
|
14
|
-
/** Thrown, not returned: a realm that fails to start is the
|
|
15
|
-
* answers by releasing the claim
|
|
16
|
-
* return value. */
|
|
9
|
+
/** Thrown, not returned: a realm that fails to start is the runner faulting, which worker.ts
|
|
10
|
+
* answers by releasing the claim. */
|
|
17
11
|
class RealmFault extends Error {
|
|
18
12
|
constructor(message) {
|
|
19
13
|
super(message);
|
|
20
14
|
this.name = "RealmFault";
|
|
21
15
|
}
|
|
22
16
|
}
|
|
23
|
-
/** Thrown when `signal` aborts: the
|
|
24
|
-
*
|
|
25
|
-
* runner did not fault -- nothing is wrong, the answer is simply no longer wanted. */
|
|
17
|
+
/** Thrown when `signal` aborts: the answer is no longer wanted, so worker.ts releases rather
|
|
18
|
+
* than answers. Not a RealmFault: nothing is wrong. */
|
|
26
19
|
export class Cancelled extends Error {
|
|
27
20
|
constructor() {
|
|
28
21
|
super("cancelled");
|
|
@@ -46,9 +39,8 @@ export async function evaluate(req, signal) {
|
|
|
46
39
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
47
40
|
}
|
|
48
41
|
worker.once("message", (reply) => resolve(reply));
|
|
49
|
-
// A script may
|
|
50
|
-
//
|
|
51
|
-
// this too, by which time the promise has settled and the first result stands.
|
|
42
|
+
// A script may `process.exit()`, which would otherwise look like a hang until the budget.
|
|
43
|
+
// Our own terminate() fires this too, after the promise has settled.
|
|
52
44
|
worker.once("exit", (code) => resolve(exited(code)));
|
|
53
45
|
worker.once("error", (err) => reject(new RealmFault(errorText(err))));
|
|
54
46
|
worker.postMessage({ code: req.code, input: req.input });
|
package/dist/import.js
CHANGED
|
@@ -1,17 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// The code-phase resolver: manifest on stdin, `{"code": [...]}` on stdout,
|
|
3
|
-
// with
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
// Two modes, one binary: "types" writes the declarations an editor needs and returns no
|
|
7
|
-
// code; "build" typechecks and bundles. A separate types hook would mean a second `tsc`
|
|
8
|
-
// over the same project.
|
|
9
|
-
import { spawn } from "node:child_process";
|
|
2
|
+
// The code-phase resolver: manifest on stdin, `{"code": [...]}` on stdout, diagnostic on stderr
|
|
3
|
+
// with a non-zero exit (specs/source-resolution.md). Two modes share one `tsc` pass: "types"
|
|
4
|
+
// writes declarations only, "build" typechecks and bundles.
|
|
10
5
|
import { existsSync } from "node:fs";
|
|
11
|
-
import { access,
|
|
6
|
+
import { access, writeFile } from "node:fs/promises";
|
|
12
7
|
import { builtinModules } from "node:module";
|
|
13
|
-
import { dirname, join,
|
|
14
|
-
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { dirname, join, resolve } from "node:path";
|
|
15
9
|
import commonjs from "@rollup/plugin-commonjs";
|
|
16
10
|
import json from "@rollup/plugin-json";
|
|
17
11
|
import { nodeResolve } from "@rollup/plugin-node-resolve";
|
|
@@ -30,11 +24,6 @@ async function exists(path) {
|
|
|
30
24
|
return false;
|
|
31
25
|
}
|
|
32
26
|
}
|
|
33
|
-
/** Creates the parent directory, which `.genroc-cache/` relies on: nothing else makes it. */
|
|
34
|
-
async function write(path, content) {
|
|
35
|
-
await mkdir(dirname(path), { recursive: true });
|
|
36
|
-
await writeFile(path, content);
|
|
37
|
-
}
|
|
38
27
|
// ── JSON Schema → TypeScript ───────────────────────────────────────────────────
|
|
39
28
|
/** Only genroc's keyword set is handled; anything else its strict decoder would have
|
|
40
29
|
* refused before this ran (internal/schema, allowedKeywords). */
|
|
@@ -90,15 +79,17 @@ function objectType(s, used) {
|
|
|
90
79
|
const doc = typeof sub.description === "string"
|
|
91
80
|
? ` /** ${sub.description} */\n`
|
|
92
81
|
: "";
|
|
93
|
-
lines.push(`${doc} ${propKey(key)}${required.has(key) ? "" : "?"}: ${tsType(sub, used)};`);
|
|
82
|
+
lines.push(`${doc} ${propKey(key)}${required.has(key) ? "" : "?"}: ${nest(tsType(sub, used))};`);
|
|
94
83
|
}
|
|
95
84
|
if (s.additionalProperties && typeof s.additionalProperties === "object") {
|
|
96
|
-
lines.push(` [key: string]: ${tsType(s.additionalProperties, used)};`);
|
|
85
|
+
lines.push(` [key: string]: ${nest(tsType(s.additionalProperties, used))};`);
|
|
97
86
|
}
|
|
98
87
|
if (lines.length === 0)
|
|
99
88
|
return "Record<string, unknown>";
|
|
100
89
|
return `{\n${lines.join("\n")}\n}`;
|
|
101
90
|
}
|
|
91
|
+
/** Every line but the first, which is already placed by the property that opens it. */
|
|
92
|
+
const nest = (t) => t.replace(/\n/g, "\n ");
|
|
102
93
|
function union(parts) {
|
|
103
94
|
const seen = [...new Set(parts)];
|
|
104
95
|
return seen.length === 0 ? "unknown" : seen.join(" | ");
|
|
@@ -106,13 +97,6 @@ function union(parts) {
|
|
|
106
97
|
const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
107
98
|
const propKey = (k) => (IDENT.test(k) ? k : JSON.stringify(k));
|
|
108
99
|
const identifier = (n) => IDENT.test(n) ? n : `Def_${n.replace(/[^A-Za-z0-9_$]/g, "_")}`;
|
|
109
|
-
function deref(s, defs) {
|
|
110
|
-
let cur = s;
|
|
111
|
-
for (let i = 0; cur && typeof cur.$ref === "string" && i < 16; i++) {
|
|
112
|
-
cur = defs[cur.$ref.replace(/^#\/\$defs\//, "")];
|
|
113
|
-
}
|
|
114
|
-
return cur;
|
|
115
|
-
}
|
|
116
100
|
/** Emits one named type per reachable $def rather than inlining: a task output may
|
|
117
101
|
* reference itself (specs/recursive-type-inference.md) and inlining would not terminate. */
|
|
118
102
|
function declarations(at) {
|
|
@@ -149,9 +133,8 @@ function typesPathFor(scriptPath) {
|
|
|
149
133
|
return scriptPath.replace(/\.[^.\/]+$/, "") + ".genroc.d.ts";
|
|
150
134
|
}
|
|
151
135
|
// ── typecheck ──────────────────────────────────────────────────────────────────
|
|
152
|
-
/** The
|
|
153
|
-
*
|
|
154
|
-
* the project root: above it is not this project. */
|
|
136
|
+
/** The tsconfig the author's editor reads, so editor and apply agree. Stops at the project
|
|
137
|
+
* root. */
|
|
155
138
|
async function nearestTsconfig(from, root) {
|
|
156
139
|
for (let dir = from;; dir = dirname(dir)) {
|
|
157
140
|
const candidate = join(dir, "tsconfig.json");
|
|
@@ -162,11 +145,7 @@ async function nearestTsconfig(from, root) {
|
|
|
162
145
|
}
|
|
163
146
|
}
|
|
164
147
|
async function typecheck(sites) {
|
|
165
|
-
//
|
|
166
|
-
// coexist with it. The suffix is what keeps the scratch area out of its way.
|
|
167
|
-
const dir = join(root, ".genroc-cache");
|
|
168
|
-
await write(join(dir, ".gitignore"), "*\n");
|
|
169
|
-
// One tsc per distinct base config: `extends` takes a single base, so merging two would
|
|
148
|
+
// One program per distinct base config: `extends` takes a single base, so merging two would
|
|
170
149
|
// check each script under the other author's options.
|
|
171
150
|
const groups = new Map();
|
|
172
151
|
for (const at of sites) {
|
|
@@ -177,10 +156,10 @@ async function typecheck(sites) {
|
|
|
177
156
|
else
|
|
178
157
|
groups.set(base, [at]);
|
|
179
158
|
}
|
|
180
|
-
|
|
159
|
+
const diagnostics = [];
|
|
181
160
|
for (const [base, group] of groups) {
|
|
182
161
|
const config = {
|
|
183
|
-
...(base ? { extends:
|
|
162
|
+
...(base ? { extends: base } : {}),
|
|
184
163
|
compilerOptions: {
|
|
185
164
|
noEmit: true,
|
|
186
165
|
strict: true,
|
|
@@ -191,42 +170,36 @@ async function typecheck(sites) {
|
|
|
191
170
|
// `lib` DESCRIBES the realm and is written after `extends` so a base cannot widen it:
|
|
192
171
|
// a worker thread has no document, whatever an author's config claims.
|
|
193
172
|
lib: ["esnext", "webworker"],
|
|
194
|
-
// `types` is the author's
|
|
195
|
-
//
|
|
196
|
-
// base config there is nothing to opt in with, so the default stays none.
|
|
173
|
+
// `types` is the author's opt-in to node globals, which the realm has. With no base
|
|
174
|
+
// config there is nothing to opt in with, so it stays none.
|
|
197
175
|
...(base ? {} : { types: [] }),
|
|
198
176
|
},
|
|
199
|
-
files: group.flatMap((s) => [
|
|
200
|
-
relative(dir, s.file),
|
|
201
|
-
relative(dir, typesPathFor(s.file)),
|
|
202
|
-
]),
|
|
177
|
+
files: group.flatMap((s) => [s.file, typesPathFor(s.file)]),
|
|
203
178
|
// `files` overrides the base's, but a base `include` survives beside it and would
|
|
204
179
|
// drag the author's whole tree in, to be checked under the worker lib.
|
|
205
180
|
include: [],
|
|
206
181
|
};
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
182
|
+
// Never written; anchors `@types` lookup at the root. Not `tsconfig.json`: that is often the
|
|
183
|
+
// base it extends, and tsc refuses a circular extends.
|
|
184
|
+
const parsed = ts.parseJsonConfigFileContent(config, ts.sys, root, undefined, join(root, "tsconfig.genroc.json"));
|
|
185
|
+
const program = ts.createProgram({
|
|
186
|
+
rootNames: parsed.fileNames,
|
|
187
|
+
options: parsed.options,
|
|
188
|
+
projectReferences: parsed.projectReferences,
|
|
189
|
+
configFileParsingDiagnostics: parsed.errors,
|
|
190
|
+
});
|
|
191
|
+
diagnostics.push(...parsed.errors, ...ts.getPreEmitDiagnostics(program));
|
|
210
192
|
}
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
proc.stderr.on("data", (c) => (err += c));
|
|
222
|
-
const code = await new Promise((resolve, reject) => {
|
|
223
|
-
proc.on("error", reject);
|
|
224
|
-
proc.on("close", (c) => resolve(c ?? 1));
|
|
225
|
-
});
|
|
226
|
-
if (code !== 0) {
|
|
227
|
-
// tsc reports on stdout; the exit code IS the type check, so this is the diagnostic
|
|
228
|
-
// genctl surfaces and the reason a failed import never produces a string.
|
|
229
|
-
die([out, err].filter(Boolean).join("\n").trimEnd());
|
|
193
|
+
if (diagnostics.length > 0) {
|
|
194
|
+
// The diagnostics are the whole type check: this is what genctl surfaces, and the reason a
|
|
195
|
+
// failed import never produces a string.
|
|
196
|
+
die(ts
|
|
197
|
+
.formatDiagnostics(diagnostics, {
|
|
198
|
+
getCanonicalFileName: (f) => f,
|
|
199
|
+
getCurrentDirectory: () => root,
|
|
200
|
+
getNewLine: () => "\n",
|
|
201
|
+
})
|
|
202
|
+
.trimEnd());
|
|
230
203
|
}
|
|
231
204
|
}
|
|
232
205
|
// ── bundle ─────────────────────────────────────────────────────────────────────
|
|
@@ -253,11 +226,9 @@ const BUILTIN = new Set([
|
|
|
253
226
|
...builtinModules,
|
|
254
227
|
...builtinModules.map((m) => `node:${m}`),
|
|
255
228
|
]);
|
|
256
|
-
/** Resolves
|
|
257
|
-
*
|
|
258
|
-
*
|
|
259
|
-
* A package resolving to a `.d.ts` is declined — that is a type, not the implementation —
|
|
260
|
-
* which leaves node_modules to nodeResolve. */
|
|
229
|
+
/** Resolves through TYPESCRIPT under the typecheck's config, so a `paths` alias that compiles
|
|
230
|
+
* also bundles. A `.d.ts` resolution is declined (a type, not code), leaving node_modules to
|
|
231
|
+
* nodeResolve. */
|
|
261
232
|
function tsResolve(configPath) {
|
|
262
233
|
let options = {};
|
|
263
234
|
if (configPath) {
|
|
@@ -278,14 +249,12 @@ function tsResolve(configPath) {
|
|
|
278
249
|
},
|
|
279
250
|
};
|
|
280
251
|
}
|
|
281
|
-
/**
|
|
282
|
-
*
|
|
283
|
-
* Bundling is entirely the importer's job, so a definition version pins its code forever. */
|
|
252
|
+
/** A self-contained ES module whose default export is the author's own, unwrapped. Bundling here
|
|
253
|
+
* means a definition version pins its code forever. */
|
|
284
254
|
async function bundle(at) {
|
|
285
255
|
const site = at.site;
|
|
286
|
-
// Builtins are
|
|
287
|
-
//
|
|
288
|
-
// of a module that will not be there, which bundles clean and fails at runtime.
|
|
256
|
+
// Builtins are externalised; anything else unresolved is a REFUSAL, since rollup's default
|
|
257
|
+
// leaves an import that bundles clean and fails at runtime.
|
|
289
258
|
const built = await rollup({
|
|
290
259
|
input: at.file,
|
|
291
260
|
external: (id) => BUILTIN.has(id),
|
|
@@ -293,8 +262,7 @@ async function bundle(at) {
|
|
|
293
262
|
tsResolve(await nearestTsconfig(dirname(at.file), root)),
|
|
294
263
|
nodeResolve({ extensions: [".ts", ".tsx", ".mjs", ".js", ".json"] }),
|
|
295
264
|
commonjs(),
|
|
296
|
-
//
|
|
297
|
-
// did natively; without it rollup hands the JSON to the JS parser.
|
|
265
|
+
// Inlines `.json` imports; without it rollup hands JSON to the JS parser.
|
|
298
266
|
json(),
|
|
299
267
|
transpile,
|
|
300
268
|
],
|
|
@@ -344,15 +312,10 @@ const located = manifest.processes.flatMap((where) => where.sites.map((site) =>
|
|
|
344
312
|
where,
|
|
345
313
|
file: resolve(where.dir, site.argument),
|
|
346
314
|
})));
|
|
347
|
-
//
|
|
348
|
-
//
|
|
349
|
-
// `child` is the shape the scaffold uses — a call to a process that forwards to the evaluator —
|
|
350
|
-
// and `external` is the same request made directly.
|
|
315
|
+
// The `code`-field contract is this resolver's, not genctl's, so it checks the directive landed
|
|
316
|
+
// there: in a child call (the scaffold's shape) or an external task's input.
|
|
351
317
|
for (const at of located) {
|
|
352
|
-
//
|
|
353
|
-
// it the directive sits is the pointer. A child call is the shape the scaffold generates — to a
|
|
354
|
-
// process that forwards to the evaluator — and an external task is the same request made
|
|
355
|
-
// directly.
|
|
318
|
+
// The action's kind is a field; where in it the directive sits is the pointer.
|
|
356
319
|
const kind = at.site.level === "action" ? (at.site.action ?? "") : "";
|
|
357
320
|
const slot = at.site.pointer.slice(-2).join(".");
|
|
358
321
|
if ((kind !== "child" && kind !== "external") || slot !== "input.code") {
|
|
@@ -361,8 +324,7 @@ for (const at of located) {
|
|
|
361
324
|
`${kind ? `a ${kind} task's ` : ""}\`${slot}\`.`);
|
|
362
325
|
}
|
|
363
326
|
}
|
|
364
|
-
// genctl
|
|
365
|
-
// does is the one that must say when it is not there.
|
|
327
|
+
// genctl does not know the argument is a file, so this resolver reports a missing one.
|
|
366
328
|
for (const at of located) {
|
|
367
329
|
if (!existsSync(at.file)) {
|
|
368
330
|
die(`${join(at.where.dir, at.where.file)}: ${address(at.site.pointer)}: ` +
|
|
@@ -383,7 +345,7 @@ for (const at of located) {
|
|
|
383
345
|
byPath.set(at.file, at);
|
|
384
346
|
}
|
|
385
347
|
for (const at of byPath.values()) {
|
|
386
|
-
await
|
|
348
|
+
await writeFile(typesPathFor(at.file), declarations(at));
|
|
387
349
|
}
|
|
388
350
|
if (manifest.mode === "types") {
|
|
389
351
|
console.log(JSON.stringify(manifest, null, 2));
|
package/dist/realm.js
CHANGED
|
@@ -1,9 +1,5 @@
|
|
|
1
|
-
// The evaluation realm
|
|
2
|
-
//
|
|
3
|
-
// eval.ts owns the budget and does the killing; nothing here knows about time.
|
|
4
|
-
//
|
|
5
|
-
// Everything that touches the script's VALUE lives on this side of the boundary — loading,
|
|
6
|
-
// classifying, serialising — because this is the only realm the value exists in.
|
|
1
|
+
// The evaluation realm: one Worker per execution, killable mid-loop by eval.ts, which owns the
|
|
2
|
+
// budget. Everything touching the script's VALUE lives here, the only realm it exists in.
|
|
7
3
|
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
8
4
|
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
9
5
|
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
@@ -14,9 +10,8 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
|
|
|
14
10
|
};
|
|
15
11
|
import { registerHooks } from "node:module";
|
|
16
12
|
import { parentPort } from "node:worker_threads";
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
// the way it does everywhere else.
|
|
13
|
+
// IMPORTED under our own URL rather than compiled from a string, so frames carry the author's
|
|
14
|
+
// line numbers and builtin imports resolve normally.
|
|
20
15
|
const SCRIPT_URL = "script:main";
|
|
21
16
|
const STACK_BYTES = 2_048;
|
|
22
17
|
// The only channel a load hook has to the source. Written per request and read once — a realm
|
|
@@ -54,9 +49,8 @@ function safeText(v) {
|
|
|
54
49
|
return String(v);
|
|
55
50
|
}
|
|
56
51
|
}
|
|
57
|
-
/**
|
|
58
|
-
*
|
|
59
|
-
* which is the script throwing. */
|
|
52
|
+
/** Unparseable code or an unresolvable import is broken code; anything else the import throws is
|
|
53
|
+
* the module's top level running, i.e. the script throwing. */
|
|
60
54
|
function unloadable(err) {
|
|
61
55
|
const code = err?.code;
|
|
62
56
|
return err instanceof SyntaxError || (typeof code === "string" && code.startsWith("ERR_MODULE"));
|
|
@@ -97,10 +91,8 @@ async function run(req) {
|
|
|
97
91
|
return { ok: false, failure: describe(err, "nonserializable") };
|
|
98
92
|
}
|
|
99
93
|
}
|
|
100
|
-
//
|
|
101
|
-
//
|
|
102
|
-
// write's callback fires once the queue ahead of it has drained, which makes the reply a barrier
|
|
103
|
-
// for `console` and a direct process.stdout.write alike: both are this stream.
|
|
94
|
+
// eval.ts terminates this thread the moment the reply lands, while stdio may still be in the
|
|
95
|
+
// pipe. An empty write's callback fires once the queue drains, making the reply a barrier.
|
|
104
96
|
function flush(stream) {
|
|
105
97
|
return new Promise((resolve) => stream.write("", () => resolve()));
|
|
106
98
|
}
|
package/dist/worker.js
CHANGED
|
@@ -1,31 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// The queue worker: claims parked `external` script tasks
|
|
3
|
-
//
|
|
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.
|
|
2
|
+
// The queue worker: claims parked `external` script tasks, evaluates each in its own realm, and
|
|
3
|
+
// answers. The only genroc-facing half (README.md; specs/external-task-queue.md).
|
|
7
4
|
import { readFileSync } from "node:fs";
|
|
8
5
|
import { Cancelled, evaluate } from "./eval.js";
|
|
9
6
|
const SERVER = (process.env.GENROC_SERVER ?? "http://localhost:8448").replace(/\/$/, "");
|
|
10
7
|
const WORKER_ID = process.env.WORKER_ID ?? `evaluator-${process.pid}`;
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
// trust least. specs/api-auth.md §5.
|
|
15
|
-
//
|
|
16
|
-
// Sent as a header rather than in the URL because Node's fetch REFUSES a URL carrying
|
|
17
|
-
// credentials ("Request cannot be constructed from a URL that includes credentials"), so the
|
|
18
|
-
// basic-auth-in-the-URL trick that works for genctl is not available here.
|
|
19
|
-
// GENROC_TOKEN_FILE is the mounted-secret shape: a credential in a file rather than an
|
|
20
|
-
// environment variable, so it stays out of `docker inspect` and out of the process environment
|
|
21
|
-
// any child inherits. The inline variable wins when both are set.
|
|
8
|
+
// Needs only the `worker` permission (specs/api-auth.md §5): this credential sits on the machine
|
|
9
|
+
// you trust least. A header, because Node's fetch refuses credentials in a URL. The file form
|
|
10
|
+
// keeps it out of `docker inspect` and child environments; the inline variable wins.
|
|
22
11
|
const TOKEN = process.env.GENROC_TOKEN ??
|
|
23
12
|
(process.env.GENROC_TOKEN_FILE ? readFileSync(process.env.GENROC_TOKEN_FILE, "utf8").trim() : "");
|
|
24
13
|
const authHeaders = TOKEN ? { authorization: `Bearer ${TOKEN}` } : {};
|
|
25
|
-
//
|
|
26
|
-
//
|
|
27
|
-
// evaluator accepted every one of them. Here it claims what it can run and no more, so a
|
|
28
|
-
// backlog is a queue rather than 200 threads fighting over a core.
|
|
14
|
+
// The worker claims only what it can run, so a backlog is a queue rather than threads fighting
|
|
15
|
+
// over a core.
|
|
29
16
|
const CONCURRENCY = Number(process.env.CONCURRENCY ?? 4);
|
|
30
17
|
const POLL_MS = Number(process.env.POLL_MS ?? 250);
|
|
31
18
|
// The visibility timeout. Short, and renewed while work is in flight: a worker that dies
|
|
@@ -34,17 +21,15 @@ const LEASE_MS = Number(process.env.LEASE_MS ?? 30_000);
|
|
|
34
21
|
const RENEW_MS = Math.max(1_000, Math.floor(LEASE_MS / 3));
|
|
35
22
|
const PROCESS_FILTER = process.env.PROCESS ?? "";
|
|
36
23
|
const TASK_FILTER = process.env.TASK ?? "";
|
|
37
|
-
//
|
|
38
|
-
//
|
|
39
|
-
// into each task. A ref is a content hash, so it is immutable — the cache never invalidates.
|
|
24
|
+
// Large values arrive as refs; a bundle is one object per definition version, fetched once.
|
|
25
|
+
// Refs are content hashes, so the cache never invalidates.
|
|
40
26
|
const objectCache = new Map();
|
|
41
27
|
async function fetchObject(ref) {
|
|
42
28
|
const cached = objectCache.get(ref);
|
|
43
29
|
if (cached !== undefined)
|
|
44
30
|
return cached;
|
|
45
|
-
// Left to throw
|
|
46
|
-
//
|
|
47
|
-
// releases the claim, so the task returns to the queue.
|
|
31
|
+
// Left to throw: a task whose input cannot be fetched must not run against a missing value.
|
|
32
|
+
// The caller releases the claim.
|
|
48
33
|
const res = await fetch(`${SERVER}/api/objects/${encodeURIComponent(ref)}`, { headers: authHeaders });
|
|
49
34
|
if (!res.ok)
|
|
50
35
|
throw new Error(`fetch object ${ref}: HTTP ${res.status}`);
|
|
@@ -62,15 +47,15 @@ async function fetchObject(ref) {
|
|
|
62
47
|
/** Put each listed value back where its path says it belongs. Paths are arrays of keys, so this
|
|
63
48
|
* needs no parser: the whole reason they are not JSON Pointer strings. */
|
|
64
49
|
async function resolveObjects(job) {
|
|
65
|
-
let input = job.
|
|
50
|
+
let input = job.external_input;
|
|
66
51
|
for (const e of job.objects ?? []) {
|
|
67
52
|
const value = await fetchObject(e.ref);
|
|
68
53
|
if (e.path.length === 0) {
|
|
69
54
|
input = value;
|
|
70
55
|
continue;
|
|
71
56
|
}
|
|
72
|
-
// The path is rooted at the entry and starts with "
|
|
73
|
-
const rest = e.path[0] === "
|
|
57
|
+
// The path is rooted at the entry and starts with "external_input", the value being rebuilt.
|
|
58
|
+
const rest = e.path[0] === "external_input" ? e.path.slice(1) : e.path;
|
|
74
59
|
if (rest.length === 0) {
|
|
75
60
|
input = value;
|
|
76
61
|
continue;
|
|
@@ -84,10 +69,8 @@ async function resolveObjects(job) {
|
|
|
84
69
|
return input;
|
|
85
70
|
}
|
|
86
71
|
async function call(path, body) {
|
|
87
|
-
// A network error is a REPLY
|
|
88
|
-
//
|
|
89
|
-
// unhandled rejection here kills it for a condition the next poll would clear. Status 0
|
|
90
|
-
// says "never reached the server", which is distinct from anything genroc answers.
|
|
72
|
+
// A network error is a REPLY (status 0, "never reached the server"), not a throw: a worker
|
|
73
|
+
// outlives restarts and deploys, and an unhandled rejection would kill it.
|
|
91
74
|
let res;
|
|
92
75
|
try {
|
|
93
76
|
res = await fetch(SERVER + path, {
|
|
@@ -109,9 +92,8 @@ async function call(path, body) {
|
|
|
109
92
|
}
|
|
110
93
|
return { ok: res.ok, status: res.status, data };
|
|
111
94
|
}
|
|
112
|
-
/**
|
|
113
|
-
*
|
|
114
|
-
* as a compile_error — the nearest permanent kind, since no retry can fix the definition. */
|
|
95
|
+
/** A task input that is not an EvalRequest is the definition's fault, reported as compile_error:
|
|
96
|
+
* the nearest permanent kind, since no retry fixes the definition. */
|
|
115
97
|
function asEvalRequest(input) {
|
|
116
98
|
if (typeof input !== "object" || input === null)
|
|
117
99
|
return "the task input is not an object";
|
|
@@ -126,10 +108,8 @@ function asEvalRequest(input) {
|
|
|
126
108
|
}
|
|
127
109
|
const inFlight = new Map();
|
|
128
110
|
let running = true;
|
|
129
|
-
//
|
|
130
|
-
//
|
|
131
|
-
// buries the one line that mattered. Announce the TRANSITIONS instead: going away, and coming
|
|
132
|
-
// back. Silence in between is the report that nothing changed.
|
|
111
|
+
// Announce reachability TRANSITIONS only: polling several times a second would otherwise emit
|
|
112
|
+
// thousands of lines during a restart.
|
|
133
113
|
let serverReachable = true;
|
|
134
114
|
async function claim(n) {
|
|
135
115
|
const { ok, status, data } = await call("/api/external-tasks/claim", {
|
|
@@ -140,18 +120,15 @@ async function claim(n) {
|
|
|
140
120
|
...(TASK_FILTER ? { task: TASK_FILTER } : {}),
|
|
141
121
|
});
|
|
142
122
|
if (!ok) {
|
|
143
|
-
// A credential problem is not transient, and polling through it looks like a healthy
|
|
144
|
-
// worker
|
|
145
|
-
// instead, so a supervisor restarts it and the failure is visible where it happened.
|
|
123
|
+
// A credential problem is not transient, and polling through it looks like a healthy idle
|
|
124
|
+
// worker. Exit, so a supervisor restarts it visibly.
|
|
146
125
|
if (status === 401 || status === 403) {
|
|
147
126
|
console.error(`claim rejected (${status}): ${JSON.stringify(data)}\n` +
|
|
148
127
|
`The server requires authentication. Set GENROC_TOKEN to a token with the 'worker' ` +
|
|
149
128
|
`permission — mint one with: genctl token create --perms worker --label evaluator -q`);
|
|
150
129
|
process.exit(1);
|
|
151
130
|
}
|
|
152
|
-
// status 0
|
|
153
|
-
// network blip. Not an error to act on — the next poll clears it — so it is reported once
|
|
154
|
-
// and then waited out.
|
|
131
|
+
// status 0 (see call): a restart or blip the next poll clears, so it is reported once.
|
|
155
132
|
if (status === 0) {
|
|
156
133
|
if (serverReachable) {
|
|
157
134
|
serverReachable = false;
|
|
@@ -174,10 +151,8 @@ async function release(token) {
|
|
|
174
151
|
if (!ok)
|
|
175
152
|
console.error(`release failed: ${JSON.stringify(data)}`);
|
|
176
153
|
}
|
|
177
|
-
/**
|
|
178
|
-
*
|
|
179
|
-
* not fit `raises`), and guessing again would only pick a second wrong answer. Release it, so
|
|
180
|
-
* the task returns to the queue and an operator sees it waiting rather than silently gone. */
|
|
154
|
+
/** A refused outcome is not retried with another: the worker does not satisfy the declared
|
|
155
|
+
* contract. Released, so an operator sees the task waiting rather than gone. */
|
|
181
156
|
async function answer(token, outcome) {
|
|
182
157
|
const { ok, data } = await call("/api/external-tasks/resolve", { token, ...outcome });
|
|
183
158
|
if (ok)
|
|
@@ -209,18 +184,15 @@ async function run(job, signal) {
|
|
|
209
184
|
result = await evaluate(req, signal);
|
|
210
185
|
}
|
|
211
186
|
catch (err) {
|
|
212
|
-
// Cancelled is not a fault: the
|
|
213
|
-
//
|
|
214
|
-
// waiting out a lease nobody is serving.
|
|
187
|
+
// Cancelled is not a fault. Still released: the row is terminal so nothing re-claims it,
|
|
188
|
+
// but the release stops it waiting out a lease nobody serves.
|
|
215
189
|
if (err instanceof Cancelled) {
|
|
216
190
|
console.log(`cancelled: ${job.token}`);
|
|
217
191
|
await release(job.token);
|
|
218
192
|
return;
|
|
219
193
|
}
|
|
220
|
-
// The RUNNER faulted,
|
|
221
|
-
//
|
|
222
|
-
// it puts the task in front of a different worker instead of burning the definition's
|
|
223
|
-
// on_error budget on this one's bad day.
|
|
194
|
+
// The RUNNER faulted, the one retryable class. Releasing is how a queue spells "retryable",
|
|
195
|
+
// and it reaches another worker without spending the definition's on_error budget.
|
|
224
196
|
console.error(`evaluator fault on ${job.token}: ${err instanceof Error ? err.message : String(err)}`);
|
|
225
197
|
await release(job.token);
|
|
226
198
|
return;
|
|
@@ -255,17 +227,13 @@ async function renewLoop() {
|
|
|
255
227
|
});
|
|
256
228
|
if (!ok)
|
|
257
229
|
continue;
|
|
258
|
-
//
|
|
259
|
-
//
|
|
260
|
-
// keep burning a core on work an operator has already stopped. The release rides run()'s
|
|
261
|
-
// own catch, so nothing is released twice.
|
|
230
|
+
// Abort first rather than let a stopped script burn a core; the release rides run()'s
|
|
231
|
+
// catch, so nothing is released twice.
|
|
262
232
|
for (const token of (data?.cancelled ?? [])) {
|
|
263
233
|
inFlight.get(token)?.abort.abort();
|
|
264
234
|
}
|
|
265
|
-
// Lost:
|
|
266
|
-
//
|
|
267
|
-
// is too short for what these scripts actually take. Deliberately NOT released: the claim
|
|
268
|
-
// is the new holder's, and releasing would bump the epoch out from under it.
|
|
235
|
+
// Lost: another worker holds it now and our answer will be refused; logged as the sign that
|
|
236
|
+
// LEASE_MS is too short. NOT released: that would bump the epoch out from under the holder.
|
|
269
237
|
const lost = (data?.lost ?? []);
|
|
270
238
|
if (lost.length) {
|
|
271
239
|
console.error(`lost ${lost.length}/${tokens.length} claims; a lease lapsed under load`);
|
package/eval.ts
CHANGED
|
@@ -1,11 +1,6 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
// the containment stays swappable.
|
|
5
|
-
//
|
|
6
|
-
// The containment is a Worker per execution (realm.ts). It is what makes the budget real:
|
|
7
|
-
// a synchronous busy loop never yields, so no in-process timer can interrupt it, and only a
|
|
8
|
-
// thread the host can kill bounds it.
|
|
1
|
+
// Imports a script module in its own realm (a Worker per execution, realm.ts), calls its default
|
|
2
|
+
// export, and classifies every outcome (README.md). Only a killable thread bounds a synchronous
|
|
3
|
+
// busy loop, which is what makes the budget real. Knows nothing of genroc; worker.ts does.
|
|
9
4
|
|
|
10
5
|
import { Worker } from "node:worker_threads";
|
|
11
6
|
|
|
@@ -16,9 +11,8 @@ export type EvalRequest = {
|
|
|
16
11
|
timeout_ms?: number;
|
|
17
12
|
};
|
|
18
13
|
|
|
19
|
-
/** Every kind
|
|
20
|
-
*
|
|
21
|
-
* faults releases its claim and lets another worker take the task. */
|
|
14
|
+
/** Every kind is PERMANENT: a retry fails identically. A faulting runner is not an outcome; it
|
|
15
|
+
* releases its claim. */
|
|
22
16
|
export type FailureKind = "compile_error" | "threw" | "timeout" | "nonserializable" | "exited";
|
|
23
17
|
|
|
24
18
|
export type EvalFailure = {
|
|
@@ -28,9 +22,8 @@ export type EvalFailure = {
|
|
|
28
22
|
stack?: string;
|
|
29
23
|
};
|
|
30
24
|
|
|
31
|
-
/**
|
|
32
|
-
*
|
|
33
|
-
* crosses the worker boundary — structured clone would refuse a different set of values. */
|
|
25
|
+
/** JSON TEXT serialised in the realm, so a nonserializable return is a script fault, not a 500,
|
|
26
|
+
* and structured clone (which refuses a different set of values) never sees the value. */
|
|
34
27
|
export type EvalResult =
|
|
35
28
|
| { ok: true; body: string }
|
|
36
29
|
| { ok: false; failure: EvalFailure };
|
|
@@ -47,9 +40,8 @@ const REALM_URL = new URL(
|
|
|
47
40
|
import.meta.url,
|
|
48
41
|
);
|
|
49
42
|
|
|
50
|
-
/** Thrown, not returned: a realm that fails to start is the
|
|
51
|
-
* answers by releasing the claim
|
|
52
|
-
* return value. */
|
|
43
|
+
/** Thrown, not returned: a realm that fails to start is the runner faulting, which worker.ts
|
|
44
|
+
* answers by releasing the claim. */
|
|
53
45
|
class RealmFault extends Error {
|
|
54
46
|
constructor(message: string) {
|
|
55
47
|
super(message);
|
|
@@ -57,9 +49,8 @@ class RealmFault extends Error {
|
|
|
57
49
|
}
|
|
58
50
|
}
|
|
59
51
|
|
|
60
|
-
/** Thrown when `signal` aborts: the
|
|
61
|
-
*
|
|
62
|
-
* runner did not fault -- nothing is wrong, the answer is simply no longer wanted. */
|
|
52
|
+
/** Thrown when `signal` aborts: the answer is no longer wanted, so worker.ts releases rather
|
|
53
|
+
* than answers. Not a RealmFault: nothing is wrong. */
|
|
63
54
|
export class Cancelled extends Error {
|
|
64
55
|
constructor() {
|
|
65
56
|
super("cancelled");
|
|
@@ -84,9 +75,8 @@ export async function evaluate(req: EvalRequest, signal?: AbortSignal): Promise<
|
|
|
84
75
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
85
76
|
}
|
|
86
77
|
worker.once("message", (reply: WorkerReply) => resolve(reply));
|
|
87
|
-
// A script may
|
|
88
|
-
//
|
|
89
|
-
// this too, by which time the promise has settled and the first result stands.
|
|
78
|
+
// A script may `process.exit()`, which would otherwise look like a hang until the budget.
|
|
79
|
+
// Our own terminate() fires this too, after the promise has settled.
|
|
90
80
|
worker.once("exit", (code: number) => resolve(exited(code)));
|
|
91
81
|
worker.once("error", (err: Error) => reject(new RealmFault(errorText(err))));
|
|
92
82
|
worker.postMessage({ code: req.code, input: req.input } satisfies WorkerRequest);
|
package/import.ts
CHANGED
|
@@ -1,18 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// The code-phase resolver: manifest on stdin, `{"code": [...]}` on stdout,
|
|
3
|
-
// with
|
|
4
|
-
//
|
|
5
|
-
|
|
6
|
-
// Two modes, one binary: "types" writes the declarations an editor needs and returns no
|
|
7
|
-
// code; "build" typechecks and bundles. A separate types hook would mean a second `tsc`
|
|
8
|
-
// over the same project.
|
|
9
|
-
|
|
10
|
-
import { spawn } from "node:child_process";
|
|
2
|
+
// The code-phase resolver: manifest on stdin, `{"code": [...]}` on stdout, diagnostic on stderr
|
|
3
|
+
// with a non-zero exit (specs/source-resolution.md). Two modes share one `tsc` pass: "types"
|
|
4
|
+
// writes declarations only, "build" typechecks and bundles.
|
|
5
|
+
|
|
11
6
|
import { existsSync } from "node:fs";
|
|
12
|
-
import { access,
|
|
7
|
+
import { access, writeFile } from "node:fs/promises";
|
|
13
8
|
import { builtinModules } from "node:module";
|
|
14
|
-
import { dirname, join,
|
|
15
|
-
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { dirname, join, resolve } from "node:path";
|
|
16
10
|
|
|
17
11
|
import commonjs from "@rollup/plugin-commonjs";
|
|
18
12
|
import json from "@rollup/plugin-json";
|
|
@@ -70,12 +64,6 @@ async function exists(path: string): Promise<boolean> {
|
|
|
70
64
|
}
|
|
71
65
|
}
|
|
72
66
|
|
|
73
|
-
/** Creates the parent directory, which `.genroc-cache/` relies on: nothing else makes it. */
|
|
74
|
-
async function write(path: string, content: string): Promise<void> {
|
|
75
|
-
await mkdir(dirname(path), { recursive: true });
|
|
76
|
-
await writeFile(path, content);
|
|
77
|
-
}
|
|
78
|
-
|
|
79
67
|
// ── JSON Schema → TypeScript ───────────────────────────────────────────────────
|
|
80
68
|
|
|
81
69
|
/** Only genroc's keyword set is handled; anything else its strict decoder would have
|
|
@@ -137,16 +125,21 @@ function objectType(s: Schema, used: Set<string>): string {
|
|
|
137
125
|
? ` /** ${sub.description} */\n`
|
|
138
126
|
: "";
|
|
139
127
|
lines.push(
|
|
140
|
-
`${doc} ${propKey(key)}${required.has(key) ? "" : "?"}: ${tsType(sub, used)};`,
|
|
128
|
+
`${doc} ${propKey(key)}${required.has(key) ? "" : "?"}: ${nest(tsType(sub, used))};`,
|
|
141
129
|
);
|
|
142
130
|
}
|
|
143
131
|
if (s.additionalProperties && typeof s.additionalProperties === "object") {
|
|
144
|
-
lines.push(
|
|
132
|
+
lines.push(
|
|
133
|
+
` [key: string]: ${nest(tsType(s.additionalProperties, used))};`,
|
|
134
|
+
);
|
|
145
135
|
}
|
|
146
136
|
if (lines.length === 0) return "Record<string, unknown>";
|
|
147
137
|
return `{\n${lines.join("\n")}\n}`;
|
|
148
138
|
}
|
|
149
139
|
|
|
140
|
+
/** Every line but the first, which is already placed by the property that opens it. */
|
|
141
|
+
const nest = (t: string) => t.replace(/\n/g, "\n ");
|
|
142
|
+
|
|
150
143
|
function union(parts: string[]): string {
|
|
151
144
|
const seen = [...new Set(parts)];
|
|
152
145
|
return seen.length === 0 ? "unknown" : seen.join(" | ");
|
|
@@ -157,17 +150,6 @@ const propKey = (k: string) => (IDENT.test(k) ? k : JSON.stringify(k));
|
|
|
157
150
|
const identifier = (n: string) =>
|
|
158
151
|
IDENT.test(n) ? n : `Def_${n.replace(/[^A-Za-z0-9_$]/g, "_")}`;
|
|
159
152
|
|
|
160
|
-
function deref(
|
|
161
|
-
s: Schema | undefined,
|
|
162
|
-
defs: Record<string, Schema>,
|
|
163
|
-
): Schema | undefined {
|
|
164
|
-
let cur = s;
|
|
165
|
-
for (let i = 0; cur && typeof cur.$ref === "string" && i < 16; i++) {
|
|
166
|
-
cur = defs[cur.$ref.replace(/^#\/\$defs\//, "")];
|
|
167
|
-
}
|
|
168
|
-
return cur;
|
|
169
|
-
}
|
|
170
|
-
|
|
171
153
|
/** Emits one named type per reachable $def rather than inlining: a task output may
|
|
172
154
|
* reference itself (specs/recursive-type-inference.md) and inlining would not terminate. */
|
|
173
155
|
function declarations(at: Located): string {
|
|
@@ -208,9 +190,8 @@ function typesPathFor(scriptPath: string): string {
|
|
|
208
190
|
|
|
209
191
|
// ── typecheck ──────────────────────────────────────────────────────────────────
|
|
210
192
|
|
|
211
|
-
/** The
|
|
212
|
-
*
|
|
213
|
-
* the project root: above it is not this project. */
|
|
193
|
+
/** The tsconfig the author's editor reads, so editor and apply agree. Stops at the project
|
|
194
|
+
* root. */
|
|
214
195
|
async function nearestTsconfig(
|
|
215
196
|
from: string,
|
|
216
197
|
root: string,
|
|
@@ -223,12 +204,7 @@ async function nearestTsconfig(
|
|
|
223
204
|
}
|
|
224
205
|
|
|
225
206
|
async function typecheck(sites: Located[]): Promise<void> {
|
|
226
|
-
//
|
|
227
|
-
// coexist with it. The suffix is what keeps the scratch area out of its way.
|
|
228
|
-
const dir = join(root, ".genroc-cache");
|
|
229
|
-
await write(join(dir, ".gitignore"), "*\n");
|
|
230
|
-
|
|
231
|
-
// One tsc per distinct base config: `extends` takes a single base, so merging two would
|
|
207
|
+
// One program per distinct base config: `extends` takes a single base, so merging two would
|
|
232
208
|
// check each script under the other author's options.
|
|
233
209
|
const groups = new Map<string, Located[]>();
|
|
234
210
|
for (const at of sites) {
|
|
@@ -238,10 +214,10 @@ async function typecheck(sites: Located[]): Promise<void> {
|
|
|
238
214
|
else groups.set(base, [at]);
|
|
239
215
|
}
|
|
240
216
|
|
|
241
|
-
|
|
217
|
+
const diagnostics: ts.Diagnostic[] = [];
|
|
242
218
|
for (const [base, group] of groups) {
|
|
243
219
|
const config: Record<string, unknown> = {
|
|
244
|
-
...(base ? { extends:
|
|
220
|
+
...(base ? { extends: base } : {}),
|
|
245
221
|
compilerOptions: {
|
|
246
222
|
noEmit: true,
|
|
247
223
|
strict: true,
|
|
@@ -252,46 +228,45 @@ async function typecheck(sites: Located[]): Promise<void> {
|
|
|
252
228
|
// `lib` DESCRIBES the realm and is written after `extends` so a base cannot widen it:
|
|
253
229
|
// a worker thread has no document, whatever an author's config claims.
|
|
254
230
|
lib: ["esnext", "webworker"],
|
|
255
|
-
// `types` is the author's
|
|
256
|
-
//
|
|
257
|
-
// base config there is nothing to opt in with, so the default stays none.
|
|
231
|
+
// `types` is the author's opt-in to node globals, which the realm has. With no base
|
|
232
|
+
// config there is nothing to opt in with, so it stays none.
|
|
258
233
|
...(base ? {} : { types: [] }),
|
|
259
234
|
},
|
|
260
|
-
files: group.flatMap((s) => [
|
|
261
|
-
relative(dir, s.file),
|
|
262
|
-
relative(dir, typesPathFor(s.file)),
|
|
263
|
-
]),
|
|
235
|
+
files: group.flatMap((s) => [s.file, typesPathFor(s.file)]),
|
|
264
236
|
// `files` overrides the base's, but a base `include` survives beside it and would
|
|
265
237
|
// drag the author's whole tree in, to be checked under the worker lib.
|
|
266
238
|
include: [],
|
|
267
239
|
};
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
240
|
+
// Never written; anchors `@types` lookup at the root. Not `tsconfig.json`: that is often the
|
|
241
|
+
// base it extends, and tsc refuses a circular extends.
|
|
242
|
+
const parsed = ts.parseJsonConfigFileContent(
|
|
243
|
+
config,
|
|
244
|
+
ts.sys,
|
|
245
|
+
root,
|
|
246
|
+
undefined,
|
|
247
|
+
join(root, "tsconfig.genroc.json"),
|
|
271
248
|
);
|
|
272
|
-
|
|
273
|
-
|
|
249
|
+
const program = ts.createProgram({
|
|
250
|
+
rootNames: parsed.fileNames,
|
|
251
|
+
options: parsed.options,
|
|
252
|
+
projectReferences: parsed.projectReferences,
|
|
253
|
+
configFileParsingDiagnostics: parsed.errors,
|
|
254
|
+
});
|
|
255
|
+
diagnostics.push(...parsed.errors, ...ts.getPreEmitDiagnostics(program));
|
|
274
256
|
}
|
|
275
|
-
}
|
|
276
257
|
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
proc.on("close", (c) => resolve(c ?? 1));
|
|
290
|
-
});
|
|
291
|
-
if (code !== 0) {
|
|
292
|
-
// tsc reports on stdout; the exit code IS the type check, so this is the diagnostic
|
|
293
|
-
// genctl surfaces and the reason a failed import never produces a string.
|
|
294
|
-
die([out, err].filter(Boolean).join("\n").trimEnd());
|
|
258
|
+
if (diagnostics.length > 0) {
|
|
259
|
+
// The diagnostics are the whole type check: this is what genctl surfaces, and the reason a
|
|
260
|
+
// failed import never produces a string.
|
|
261
|
+
die(
|
|
262
|
+
ts
|
|
263
|
+
.formatDiagnostics(diagnostics, {
|
|
264
|
+
getCanonicalFileName: (f) => f,
|
|
265
|
+
getCurrentDirectory: () => root,
|
|
266
|
+
getNewLine: () => "\n",
|
|
267
|
+
})
|
|
268
|
+
.trimEnd(),
|
|
269
|
+
);
|
|
295
270
|
}
|
|
296
271
|
}
|
|
297
272
|
|
|
@@ -321,11 +296,9 @@ const BUILTIN = new Set([
|
|
|
321
296
|
...builtinModules.map((m) => `node:${m}`),
|
|
322
297
|
]);
|
|
323
298
|
|
|
324
|
-
/** Resolves
|
|
325
|
-
*
|
|
326
|
-
*
|
|
327
|
-
* A package resolving to a `.d.ts` is declined — that is a type, not the implementation —
|
|
328
|
-
* which leaves node_modules to nodeResolve. */
|
|
299
|
+
/** Resolves through TYPESCRIPT under the typecheck's config, so a `paths` alias that compiles
|
|
300
|
+
* also bundles. A `.d.ts` resolution is declined (a type, not code), leaving node_modules to
|
|
301
|
+
* nodeResolve. */
|
|
329
302
|
function tsResolve(configPath: string | null): Plugin {
|
|
330
303
|
let options: ts.CompilerOptions = {};
|
|
331
304
|
if (configPath) {
|
|
@@ -355,14 +328,12 @@ function tsResolve(configPath: string | null): Plugin {
|
|
|
355
328
|
};
|
|
356
329
|
}
|
|
357
330
|
|
|
358
|
-
/**
|
|
359
|
-
*
|
|
360
|
-
* Bundling is entirely the importer's job, so a definition version pins its code forever. */
|
|
331
|
+
/** A self-contained ES module whose default export is the author's own, unwrapped. Bundling here
|
|
332
|
+
* means a definition version pins its code forever. */
|
|
361
333
|
async function bundle(at: Located): Promise<string> {
|
|
362
334
|
const site = at.site;
|
|
363
|
-
// Builtins are
|
|
364
|
-
//
|
|
365
|
-
// of a module that will not be there, which bundles clean and fails at runtime.
|
|
335
|
+
// Builtins are externalised; anything else unresolved is a REFUSAL, since rollup's default
|
|
336
|
+
// leaves an import that bundles clean and fails at runtime.
|
|
366
337
|
const built = await rollup({
|
|
367
338
|
input: at.file,
|
|
368
339
|
external: (id) => BUILTIN.has(id),
|
|
@@ -370,8 +341,7 @@ async function bundle(at: Located): Promise<string> {
|
|
|
370
341
|
tsResolve(await nearestTsconfig(dirname(at.file), root)),
|
|
371
342
|
nodeResolve({ extensions: [".ts", ".tsx", ".mjs", ".js", ".json"] }),
|
|
372
343
|
commonjs(),
|
|
373
|
-
//
|
|
374
|
-
// did natively; without it rollup hands the JSON to the JS parser.
|
|
344
|
+
// Inlines `.json` imports; without it rollup hands JSON to the JS parser.
|
|
375
345
|
json(),
|
|
376
346
|
transpile,
|
|
377
347
|
],
|
|
@@ -414,10 +384,8 @@ const root = process.cwd();
|
|
|
414
384
|
if (!manifest || !Array.isArray(manifest.processes))
|
|
415
385
|
die("stdin is not a genroc resolver manifest");
|
|
416
386
|
|
|
417
|
-
/**
|
|
418
|
-
*
|
|
419
|
-
* joining it to the definition's directory is this resolver's business: only it knows the
|
|
420
|
-
* argument is a path at all. */
|
|
387
|
+
/** Sites in manifest order, the order `code` must answer in. The argument is joined to the
|
|
388
|
+
* definition's directory here: only this resolver knows it is a path. */
|
|
421
389
|
type Located = { site: Site; where: ManifestProcess; file: string };
|
|
422
390
|
|
|
423
391
|
/** A pointer as the address it is, so a generated comment or an error can be pasted into
|
|
@@ -440,15 +408,10 @@ const located: Located[] = manifest.processes.flatMap((where) =>
|
|
|
440
408
|
})),
|
|
441
409
|
);
|
|
442
410
|
|
|
443
|
-
//
|
|
444
|
-
//
|
|
445
|
-
// `child` is the shape the scaffold uses — a call to a process that forwards to the evaluator —
|
|
446
|
-
// and `external` is the same request made directly.
|
|
411
|
+
// The `code`-field contract is this resolver's, not genctl's, so it checks the directive landed
|
|
412
|
+
// there: in a child call (the scaffold's shape) or an external task's input.
|
|
447
413
|
for (const at of located) {
|
|
448
|
-
//
|
|
449
|
-
// it the directive sits is the pointer. A child call is the shape the scaffold generates — to a
|
|
450
|
-
// process that forwards to the evaluator — and an external task is the same request made
|
|
451
|
-
// directly.
|
|
414
|
+
// The action's kind is a field; where in it the directive sits is the pointer.
|
|
452
415
|
const kind = at.site.level === "action" ? (at.site.action ?? "") : "";
|
|
453
416
|
const slot = at.site.pointer.slice(-2).join(".");
|
|
454
417
|
if ((kind !== "child" && kind !== "external") || slot !== "input.code") {
|
|
@@ -460,8 +423,7 @@ for (const at of located) {
|
|
|
460
423
|
}
|
|
461
424
|
}
|
|
462
425
|
|
|
463
|
-
// genctl
|
|
464
|
-
// does is the one that must say when it is not there.
|
|
426
|
+
// genctl does not know the argument is a file, so this resolver reports a missing one.
|
|
465
427
|
for (const at of located) {
|
|
466
428
|
if (!existsSync(at.file)) {
|
|
467
429
|
die(
|
|
@@ -490,7 +452,7 @@ for (const at of located) {
|
|
|
490
452
|
}
|
|
491
453
|
|
|
492
454
|
for (const at of byPath.values()) {
|
|
493
|
-
await
|
|
455
|
+
await writeFile(typesPathFor(at.file), declarations(at));
|
|
494
456
|
}
|
|
495
457
|
|
|
496
458
|
if (manifest.mode === "types") {
|
package/package.json
CHANGED
package/realm.ts
CHANGED
|
@@ -1,18 +1,13 @@
|
|
|
1
|
-
// The evaluation realm
|
|
2
|
-
//
|
|
3
|
-
// eval.ts owns the budget and does the killing; nothing here knows about time.
|
|
4
|
-
//
|
|
5
|
-
// Everything that touches the script's VALUE lives on this side of the boundary — loading,
|
|
6
|
-
// classifying, serialising — because this is the only realm the value exists in.
|
|
1
|
+
// The evaluation realm: one Worker per execution, killable mid-loop by eval.ts, which owns the
|
|
2
|
+
// budget. Everything touching the script's VALUE lives here, the only realm it exists in.
|
|
7
3
|
|
|
8
4
|
import { registerHooks } from "node:module";
|
|
9
5
|
import { parentPort } from "node:worker_threads";
|
|
10
6
|
|
|
11
7
|
import type { EvalFailure, FailureKind, WorkerReply, WorkerRequest } from "./eval.ts";
|
|
12
8
|
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
// the way it does everywhere else.
|
|
9
|
+
// IMPORTED under our own URL rather than compiled from a string, so frames carry the author's
|
|
10
|
+
// line numbers and builtin imports resolve normally.
|
|
16
11
|
const SCRIPT_URL = "script:main";
|
|
17
12
|
const STACK_BYTES = 2_048;
|
|
18
13
|
|
|
@@ -54,9 +49,8 @@ function safeText(v: unknown): string {
|
|
|
54
49
|
}
|
|
55
50
|
}
|
|
56
51
|
|
|
57
|
-
/**
|
|
58
|
-
*
|
|
59
|
-
* which is the script throwing. */
|
|
52
|
+
/** Unparseable code or an unresolvable import is broken code; anything else the import throws is
|
|
53
|
+
* the module's top level running, i.e. the script throwing. */
|
|
60
54
|
function unloadable(err: unknown): boolean {
|
|
61
55
|
const code = (err as { code?: unknown } | null)?.code;
|
|
62
56
|
return err instanceof SyntaxError || (typeof code === "string" && code.startsWith("ERR_MODULE"));
|
|
@@ -99,10 +93,8 @@ async function run(req: WorkerRequest): Promise<WorkerReply> {
|
|
|
99
93
|
}
|
|
100
94
|
}
|
|
101
95
|
|
|
102
|
-
//
|
|
103
|
-
//
|
|
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.
|
|
96
|
+
// eval.ts terminates this thread the moment the reply lands, while stdio may still be in the
|
|
97
|
+
// pipe. An empty write's callback fires once the queue drains, making the reply a barrier.
|
|
106
98
|
function flush(stream: NodeJS.WriteStream): Promise<void> {
|
|
107
99
|
return new Promise((resolve) => stream.write("", () => resolve()));
|
|
108
100
|
}
|
package/worker.ts
CHANGED
|
@@ -1,34 +1,21 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// The queue worker: claims parked `external` script tasks
|
|
3
|
-
//
|
|
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.
|
|
2
|
+
// The queue worker: claims parked `external` script tasks, evaluates each in its own realm, and
|
|
3
|
+
// answers. The only genroc-facing half (README.md; specs/external-task-queue.md).
|
|
7
4
|
|
|
8
5
|
import { readFileSync } from "node:fs";
|
|
9
6
|
import { Cancelled, evaluate, type EvalRequest, type FailureKind } from "./eval.ts";
|
|
10
7
|
|
|
11
8
|
const SERVER = (process.env.GENROC_SERVER ?? "http://localhost:8448").replace(/\/$/, "");
|
|
12
9
|
const WORKER_ID = process.env.WORKER_ID ?? `evaluator-${process.pid}`;
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
//
|
|
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.
|
|
10
|
+
// Needs only the `worker` permission (specs/api-auth.md §5): this credential sits on the machine
|
|
11
|
+
// you trust least. A header, because Node's fetch refuses credentials in a URL. The file form
|
|
12
|
+
// keeps it out of `docker inspect` and child environments; the inline variable wins.
|
|
24
13
|
const TOKEN =
|
|
25
14
|
process.env.GENROC_TOKEN ??
|
|
26
15
|
(process.env.GENROC_TOKEN_FILE ? readFileSync(process.env.GENROC_TOKEN_FILE, "utf8").trim() : "");
|
|
27
16
|
const authHeaders: Record<string, string> = TOKEN ? { authorization: `Bearer ${TOKEN}` } : {};
|
|
28
|
-
//
|
|
29
|
-
//
|
|
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.
|
|
17
|
+
// The worker claims only what it can run, so a backlog is a queue rather than threads fighting
|
|
18
|
+
// over a core.
|
|
32
19
|
const CONCURRENCY = Number(process.env.CONCURRENCY ?? 4);
|
|
33
20
|
const POLL_MS = Number(process.env.POLL_MS ?? 250);
|
|
34
21
|
// The visibility timeout. Short, and renewed while work is in flight: a worker that dies
|
|
@@ -43,23 +30,21 @@ type ObjectEntry = { path: (string | number)[]; ref: string; size: number };
|
|
|
43
30
|
type QueueTask = {
|
|
44
31
|
token: string;
|
|
45
32
|
process: string;
|
|
46
|
-
|
|
47
|
-
|
|
33
|
+
task: string;
|
|
34
|
+
external_input: unknown;
|
|
48
35
|
objects?: ObjectEntry[];
|
|
49
36
|
raises?: Record<string, unknown>;
|
|
50
37
|
};
|
|
51
38
|
|
|
52
|
-
//
|
|
53
|
-
//
|
|
54
|
-
// into each task. A ref is a content hash, so it is immutable — the cache never invalidates.
|
|
39
|
+
// Large values arrive as refs; a bundle is one object per definition version, fetched once.
|
|
40
|
+
// Refs are content hashes, so the cache never invalidates.
|
|
55
41
|
const objectCache = new Map<string, unknown>();
|
|
56
42
|
|
|
57
43
|
async function fetchObject(ref: string): Promise<unknown> {
|
|
58
44
|
const cached = objectCache.get(ref);
|
|
59
45
|
if (cached !== undefined) return cached;
|
|
60
|
-
// Left to throw
|
|
61
|
-
//
|
|
62
|
-
// releases the claim, so the task returns to the queue.
|
|
46
|
+
// Left to throw: a task whose input cannot be fetched must not run against a missing value.
|
|
47
|
+
// The caller releases the claim.
|
|
63
48
|
const res = await fetch(`${SERVER}/api/objects/${encodeURIComponent(ref)}`, { headers: authHeaders });
|
|
64
49
|
if (!res.ok) throw new Error(`fetch object ${ref}: HTTP ${res.status}`);
|
|
65
50
|
const { data } = (await res.json()) as { data: string };
|
|
@@ -76,15 +61,15 @@ async function fetchObject(ref: string): Promise<unknown> {
|
|
|
76
61
|
/** Put each listed value back where its path says it belongs. Paths are arrays of keys, so this
|
|
77
62
|
* needs no parser: the whole reason they are not JSON Pointer strings. */
|
|
78
63
|
async function resolveObjects(job: QueueTask): Promise<unknown> {
|
|
79
|
-
let input: any = job.
|
|
64
|
+
let input: any = job.external_input;
|
|
80
65
|
for (const e of job.objects ?? []) {
|
|
81
66
|
const value = await fetchObject(e.ref);
|
|
82
67
|
if (e.path.length === 0) {
|
|
83
68
|
input = value;
|
|
84
69
|
continue;
|
|
85
70
|
}
|
|
86
|
-
// The path is rooted at the entry and starts with "
|
|
87
|
-
const rest = e.path[0] === "
|
|
71
|
+
// The path is rooted at the entry and starts with "external_input", the value being rebuilt.
|
|
72
|
+
const rest = e.path[0] === "external_input" ? e.path.slice(1) : e.path;
|
|
88
73
|
if (rest.length === 0) {
|
|
89
74
|
input = value;
|
|
90
75
|
continue;
|
|
@@ -97,10 +82,8 @@ async function resolveObjects(job: QueueTask): Promise<unknown> {
|
|
|
97
82
|
}
|
|
98
83
|
|
|
99
84
|
async function call(path: string, body: unknown): Promise<{ ok: boolean; status: number; data: any }> {
|
|
100
|
-
// A network error is a REPLY
|
|
101
|
-
//
|
|
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.
|
|
85
|
+
// A network error is a REPLY (status 0, "never reached the server"), not a throw: a worker
|
|
86
|
+
// outlives restarts and deploys, and an unhandled rejection would kill it.
|
|
104
87
|
let res: Response;
|
|
105
88
|
try {
|
|
106
89
|
res = await fetch(SERVER + path, {
|
|
@@ -121,9 +104,8 @@ async function call(path: string, body: unknown): Promise<{ ok: boolean; status:
|
|
|
121
104
|
return { ok: res.ok, status: res.status, data };
|
|
122
105
|
}
|
|
123
106
|
|
|
124
|
-
/**
|
|
125
|
-
*
|
|
126
|
-
* as a compile_error — the nearest permanent kind, since no retry can fix the definition. */
|
|
107
|
+
/** A task input that is not an EvalRequest is the definition's fault, reported as compile_error:
|
|
108
|
+
* the nearest permanent kind, since no retry fixes the definition. */
|
|
127
109
|
function asEvalRequest(input: unknown): EvalRequest | string {
|
|
128
110
|
if (typeof input !== "object" || input === null) return "the task input is not an object";
|
|
129
111
|
const r = input as Record<string, unknown>;
|
|
@@ -135,18 +117,15 @@ function asEvalRequest(input: unknown): EvalRequest | string {
|
|
|
135
117
|
};
|
|
136
118
|
}
|
|
137
119
|
|
|
138
|
-
/**
|
|
139
|
-
*
|
|
140
|
-
* heartbeat and has to be delivered inward from there. */
|
|
120
|
+
/** genroc cannot call us, so a cancellation arrives on our own heartbeat and reaches the
|
|
121
|
+
* evaluation through the controller. */
|
|
141
122
|
type Running = { job: QueueTask; abort: AbortController };
|
|
142
123
|
|
|
143
124
|
const inFlight = new Map<string, Running>();
|
|
144
125
|
let running = true;
|
|
145
126
|
|
|
146
|
-
//
|
|
147
|
-
//
|
|
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.
|
|
127
|
+
// Announce reachability TRANSITIONS only: polling several times a second would otherwise emit
|
|
128
|
+
// thousands of lines during a restart.
|
|
150
129
|
let serverReachable = true;
|
|
151
130
|
|
|
152
131
|
async function claim(n: number): Promise<QueueTask[]> {
|
|
@@ -158,9 +137,8 @@ async function claim(n: number): Promise<QueueTask[]> {
|
|
|
158
137
|
...(TASK_FILTER ? { task: TASK_FILTER } : {}),
|
|
159
138
|
});
|
|
160
139
|
if (!ok) {
|
|
161
|
-
// A credential problem is not transient, and polling through it looks like a healthy
|
|
162
|
-
// worker
|
|
163
|
-
// instead, so a supervisor restarts it and the failure is visible where it happened.
|
|
140
|
+
// A credential problem is not transient, and polling through it looks like a healthy idle
|
|
141
|
+
// worker. Exit, so a supervisor restarts it visibly.
|
|
164
142
|
if (status === 401 || status === 403) {
|
|
165
143
|
console.error(
|
|
166
144
|
`claim rejected (${status}): ${JSON.stringify(data)}\n` +
|
|
@@ -169,9 +147,7 @@ async function claim(n: number): Promise<QueueTask[]> {
|
|
|
169
147
|
);
|
|
170
148
|
process.exit(1);
|
|
171
149
|
}
|
|
172
|
-
// status 0
|
|
173
|
-
// network blip. Not an error to act on — the next poll clears it — so it is reported once
|
|
174
|
-
// and then waited out.
|
|
150
|
+
// status 0 (see call): a restart or blip the next poll clears, so it is reported once.
|
|
175
151
|
if (status === 0) {
|
|
176
152
|
if (serverReachable) {
|
|
177
153
|
serverReachable = false;
|
|
@@ -197,10 +173,8 @@ async function release(token: string): Promise<void> {
|
|
|
197
173
|
if (!ok) console.error(`release failed: ${JSON.stringify(data)}`);
|
|
198
174
|
}
|
|
199
175
|
|
|
200
|
-
/**
|
|
201
|
-
*
|
|
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. */
|
|
176
|
+
/** A refused outcome is not retried with another: the worker does not satisfy the declared
|
|
177
|
+
* contract. Released, so an operator sees the task waiting rather than gone. */
|
|
204
178
|
async function answer(token: string, outcome: Record<string, unknown>): Promise<void> {
|
|
205
179
|
const { ok, data } = await call("/api/external-tasks/resolve", { token, ...outcome });
|
|
206
180
|
if (ok) return;
|
|
@@ -231,18 +205,15 @@ async function run(job: QueueTask, signal: AbortSignal): Promise<void> {
|
|
|
231
205
|
try {
|
|
232
206
|
result = await evaluate(req, signal);
|
|
233
207
|
} catch (err) {
|
|
234
|
-
// Cancelled is not a fault: the
|
|
235
|
-
//
|
|
236
|
-
// waiting out a lease nobody is serving.
|
|
208
|
+
// Cancelled is not a fault. Still released: the row is terminal so nothing re-claims it,
|
|
209
|
+
// but the release stops it waiting out a lease nobody serves.
|
|
237
210
|
if (err instanceof Cancelled) {
|
|
238
211
|
console.log(`cancelled: ${job.token}`);
|
|
239
212
|
await release(job.token);
|
|
240
213
|
return;
|
|
241
214
|
}
|
|
242
|
-
// The RUNNER faulted,
|
|
243
|
-
//
|
|
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.
|
|
215
|
+
// The RUNNER faulted, the one retryable class. Releasing is how a queue spells "retryable",
|
|
216
|
+
// and it reaches another worker without spending the definition's on_error budget.
|
|
246
217
|
console.error(`evaluator fault on ${job.token}: ${err instanceof Error ? err.message : String(err)}`);
|
|
247
218
|
await release(job.token);
|
|
248
219
|
return;
|
|
@@ -278,17 +249,13 @@ async function renewLoop(): Promise<void> {
|
|
|
278
249
|
});
|
|
279
250
|
if (!ok) continue;
|
|
280
251
|
|
|
281
|
-
//
|
|
282
|
-
//
|
|
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.
|
|
252
|
+
// Abort first rather than let a stopped script burn a core; the release rides run()'s
|
|
253
|
+
// catch, so nothing is released twice.
|
|
285
254
|
for (const token of (data?.cancelled ?? []) as string[]) {
|
|
286
255
|
inFlight.get(token)?.abort.abort();
|
|
287
256
|
}
|
|
288
|
-
// Lost:
|
|
289
|
-
//
|
|
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.
|
|
257
|
+
// Lost: another worker holds it now and our answer will be refused; logged as the sign that
|
|
258
|
+
// LEASE_MS is too short. NOT released: that would bump the epoch out from under the holder.
|
|
292
259
|
const lost = (data?.lost ?? []) as string[];
|
|
293
260
|
if (lost.length) {
|
|
294
261
|
console.error(`lost ${lost.length}/${tokens.length} claims; a lease lapsed under load`);
|