- tools/reducer:目录/前置/单件/批量/装配/自测,复用 cad-ui-rebuild 引擎 - 教学控制台新增「二级减速器」分组:23 件逐件课 + 装配课 + 环境课(job kind reducer-part / reducer-assembly) - web/teaching/reducer-toolkit.html 初学者配套页(生成物)+ Playwright 双视口门禁 - 首页补工具入口;工具手册随 npm 脚本变更重生成 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
562 lines
22 KiB
JavaScript
562 lines
22 KiB
JavaScript
/**
|
||
* Whitelisted job runner behind the teaching console.
|
||
*
|
||
* The browser may only ask for a *lesson id* (plus bounded parameters for the
|
||
* free-practice lesson). This module turns that into fixed argv arrays for:
|
||
* - tools/web-freecad-functional-suite.mjs (kind "suite")
|
||
* - tools/layout-probe.mjs (kind "probe")
|
||
* - tools/static-host.mjs (kind "host")
|
||
* - the preflight report itself (kind "preflight")
|
||
*
|
||
* Nothing here accepts a shell string: spawn() always receives an argv array,
|
||
* cwd is the repo root, the environment is a whitelist, and only one job may
|
||
* run at a time (headed Chrome + a 4 GB dist tolerate no more).
|
||
*
|
||
* Progress is read from the suite's own files — manifest.json (planned cases),
|
||
* checkpoint.json (current/completed, rewritten during the run) and
|
||
* results.json (counts + per-case records) — never parsed from stdout. stdout
|
||
* is forwarded only as log lines.
|
||
*/
|
||
import fs from "node:fs";
|
||
import path from "node:path";
|
||
import crypto from "node:crypto";
|
||
import { spawn } from "node:child_process";
|
||
import { createRequire } from "node:module";
|
||
import { fileURLToPath } from "node:url";
|
||
import { loadCatalog } from "../tools/teaching-console/catalog.mjs";
|
||
import { buildLessons } from "../tools/teaching-console/lessons.mjs";
|
||
import { findChrome } from "../../tools/static-host.mjs";
|
||
|
||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||
export const REPO_ROOT = path.resolve(HERE, "../..");
|
||
export const CONSOLE_ROOT = path.join(REPO_ROOT, "docs/current/teaching-console");
|
||
const SUITE_ENTRY = path.join(REPO_ROOT, "tools/web-freecad-functional-suite.mjs");
|
||
const PROBE_ENTRY = path.join(REPO_ROOT, "tools/layout-probe.mjs");
|
||
const HOST_ENTRY = path.join(REPO_ROOT, "tools/static-host.mjs");
|
||
const REDUCER_PART = path.join(REPO_ROOT, "tools/reducer/create-part.mjs");
|
||
const REDUCER_ASSEMBLY = path.join(REPO_ROOT, "tools/reducer/create-assembly.mjs");
|
||
|
||
const LINE_LIMIT = 2000;
|
||
const BYTE_LIMIT = 512 * 1024;
|
||
const POLL_MS = 750;
|
||
const PROBE_PAGES = new Set(["/", "/project.html", "/partdesign.html"]);
|
||
const TIMEOUTS = {
|
||
suite: 45 * 60_000,
|
||
probe: 10 * 60_000,
|
||
host: 2 * 60_000,
|
||
// A 26-step cover part takes ~10 min headed; leave room without hanging forever.
|
||
"reducer-part": 40 * 60_000,
|
||
"reducer-assembly": 45 * 60_000,
|
||
};
|
||
|
||
export class JobError extends Error {
|
||
constructor(code, message, detail) {
|
||
super(message);
|
||
this.code = code;
|
||
this.detail = detail;
|
||
}
|
||
}
|
||
|
||
const require = createRequire(path.join(REPO_ROOT, "web/package.json"));
|
||
|
||
/* ---------------------------------------------------------------- catalog */
|
||
|
||
let cached = null;
|
||
export function catalog() {
|
||
if (!cached) {
|
||
const cases = loadCatalog();
|
||
cached = { cases, lessons: buildLessons(cases), byId: new Map() };
|
||
for (const lesson of cached.lessons.lessons) cached.byId.set(lesson.id, lesson);
|
||
}
|
||
return cached;
|
||
}
|
||
|
||
/* -------------------------------------------------------------- preflight */
|
||
|
||
export function preflight() {
|
||
const checks = [];
|
||
const add = (id, ok, detail, fix, hard = true) => checks.push({ id, ok, detail, fix, hard });
|
||
|
||
const distIndex = path.join(REPO_ROOT, "web/dist/index.html");
|
||
add("dist", fs.existsSync(distIndex), fs.existsSync(distIndex) ? "web/dist/index.html 已就绪" : "web/dist/index.html 不存在",
|
||
"cd web && npx vite build");
|
||
|
||
const kernelDirs = ["web/dist/kernel", "web/public/kernel"].map((rel) => path.join(REPO_ROOT, rel));
|
||
const wasm = kernelDirs.flatMap((dir) => {
|
||
try {
|
||
return fs.readdirSync(dir).filter((name) => name.endsWith(".wasm")).map((name) => path.join(dir, name));
|
||
} catch {
|
||
return [];
|
||
}
|
||
});
|
||
add("kernel", wasm.length > 0, wasm.length ? `内核产物 ${wasm.length} 个 .wasm` : "未找到内核 .wasm 产物",
|
||
"cd web && node ../tools/sync-assets.mjs");
|
||
|
||
let chrome = null;
|
||
try {
|
||
chrome = findChrome();
|
||
} catch {
|
||
chrome = null;
|
||
}
|
||
add("chrome", Boolean(chrome), chrome || "未找到 Chrome/Chromium", "export FREECAD_CHROME=/usr/bin/google-chrome");
|
||
|
||
const display = process.env.DISPLAY || "";
|
||
const displayOk = Boolean(display) && (display.startsWith(":") ? fs.existsSync(`/tmp/.X11-unix/X${display.replace(/^:/, "").split(".")[0]}`) : true);
|
||
add("display", displayOk, display ? `DISPLAY=${display}${displayOk ? "" : "(找不到 X socket)"}` : "DISPLAY 未设置",
|
||
"DISPLAY=:1 node web/teaching/server.mjs");
|
||
|
||
let playwright = null;
|
||
try {
|
||
playwright = require.resolve("playwright");
|
||
} catch {
|
||
playwright = null;
|
||
}
|
||
add("playwright", Boolean(playwright), playwright ? "web/node_modules 可解析 playwright" : "web/node_modules 中找不到 playwright",
|
||
"cd web && npm install");
|
||
|
||
const entriesOk = [SUITE_ENTRY, PROBE_ENTRY, HOST_ENTRY].every((file) => fs.existsSync(file));
|
||
add("tools", entriesOk, entriesOk ? "套件、探针与静态服务入口存在" : "工具入口缺失", "git status tools/");
|
||
|
||
const hard = checks.filter((check) => check.hard);
|
||
return { ok: hard.every((check) => check.ok), checks, checkedAt: new Date().toISOString() };
|
||
}
|
||
|
||
/* ------------------------------------------------------------- validation */
|
||
|
||
const ID_PATTERN = /^[A-Za-z][A-Za-z0-9._-]{0,79}$/;
|
||
|
||
export function validateCaseIds(ids, catalogData, maxCases = 8) {
|
||
if (!Array.isArray(ids) || ids.length === 0) throw new JobError("E_PARAM", "至少选择一个用例");
|
||
if (ids.length > maxCases) throw new JobError("E_PARAM", `最多选择 ${maxCases} 个用例`);
|
||
const known = new Set(catalogData.ids);
|
||
const seen = new Set();
|
||
for (const id of ids) {
|
||
if (typeof id !== "string" || !ID_PATTERN.test(id)) throw new JobError("E_PARAM", `非法用例 id:${String(id).slice(0, 40)}`);
|
||
if (!known.has(id)) throw new JobError("E_PARAM", `用例不在目录内:${id}`);
|
||
if (seen.has(id)) throw new JobError("E_PARAM", `用例重复:${id}`);
|
||
seen.add(id);
|
||
}
|
||
return [...ids];
|
||
}
|
||
|
||
export function validateProbeUrl(url) {
|
||
if (typeof url !== "string" || !url.startsWith("/")) throw new JobError("E_PARAM", "页面地址必须以 / 开头");
|
||
if (PROBE_PAGES.has(url)) return url;
|
||
const match = /^\/workbench\.html\?module=([A-Za-z0-9]+)$/.exec(url);
|
||
if (match && catalog().cases.modules.includes(match[1])) return url;
|
||
throw new JobError("E_PARAM", `页面不在白名单内:${url.slice(0, 60)}`);
|
||
}
|
||
|
||
function boundedInt(value, min, max, fallback) {
|
||
if (value === undefined || value === null || value === "") return fallback;
|
||
const parsed = Number(value);
|
||
if (!Number.isInteger(parsed) || parsed < min || parsed > max) throw new JobError("E_PARAM", `数值超出范围(${min}..${max})`);
|
||
return parsed;
|
||
}
|
||
|
||
/**
|
||
* Turn a lesson + bounded parameters into the exact argv to spawn.
|
||
* Exported so self-test can assert the whitelist without starting a process.
|
||
*/
|
||
export function buildJobArgv(lesson, params = {}, { jobDir } = {}) {
|
||
const job = lesson.job;
|
||
if (job.kind === "preflight") return { argv: null, dir: jobDir };
|
||
if (job.kind === "suite") {
|
||
const catalogData = catalog().cases;
|
||
const only = job.selectable
|
||
? validateCaseIds(params.only, catalogData, job.maxCases ?? 8)
|
||
: validateCaseIds(job.only, catalogData, 40);
|
||
const slow = job.selectable ? boundedInt(params.slow, 0, 1500, 0) : boundedInt(job.slow, 0, 1500, 0);
|
||
const highlight = job.selectable ? params.highlight === true : job.highlight === true;
|
||
const screenshots = job.selectable
|
||
? (params.screenshots === "all" ? "all" : "fails")
|
||
: (job.screenshots === "all" ? "all" : "fails");
|
||
const argv = [process.execPath, SUITE_ENTRY, "--only", only.join(","), "--headed"];
|
||
if (slow > 0) argv.push("--slow", String(slow));
|
||
if (highlight) argv.push("--highlight");
|
||
argv.push("--screenshots", screenshots, "--out", path.join(jobDir, "suite"));
|
||
return { argv, dir: jobDir };
|
||
}
|
||
if (job.kind === "probe") {
|
||
const url = validateProbeUrl(job.selectable ? params.url : job.url);
|
||
return {
|
||
argv: [
|
||
process.execPath, PROBE_ENTRY,
|
||
"--root", path.join(REPO_ROOT, "web/dist"),
|
||
"--url", url,
|
||
"--viewport", "1440x1000",
|
||
"--headed",
|
||
"--json", path.join(jobDir, "layout.json"),
|
||
"--screenshot", path.join(jobDir, "layout-{page}.png"),
|
||
],
|
||
dir: jobDir,
|
||
};
|
||
}
|
||
if (job.kind === "host") {
|
||
return {
|
||
argv: [process.execPath, HOST_ENTRY, "--root", path.join(REPO_ROOT, "web/dist"), "--port", "0"],
|
||
dir: jobDir,
|
||
};
|
||
}
|
||
if (job.kind === "reducer-part") {
|
||
const partId = String(job.partId ?? "");
|
||
if (!/^P\d{2}$/.test(partId)) throw new JobError("E_PARAM", `非法零件编号:${partId.slice(0, 20)}`);
|
||
const argv = [process.execPath, REDUCER_PART, partId];
|
||
if (job.dry) argv.push("--dry");
|
||
argv.push("--out", jobDir, "--json");
|
||
return { argv, dir: jobDir };
|
||
}
|
||
if (job.kind === "reducer-assembly") {
|
||
return { argv: [process.execPath, REDUCER_ASSEMBLY, "--out", jobDir, "--json"], dir: jobDir };
|
||
}
|
||
throw new JobError("E_PARAM", `未知课程类型:${job.kind}`);
|
||
}
|
||
|
||
/** Copyable command text for the page (quoted because the repo path has a space). */
|
||
export function argvToCommand(argv) {
|
||
if (!argv) return "";
|
||
return argv.map((part) => (/[\s"'$`]/.test(part) && part !== process.execPath ? JSON.stringify(part) : part)).join(" ");
|
||
}
|
||
|
||
/* --------------------------------------------------------------- progress */
|
||
|
||
export function parseProgressLine(line) {
|
||
const match = /^([A-Za-z][\w-]*): (passed|failed|blocked|skipped)\b/.exec(line.trim());
|
||
return match ? { id: match[1], status: match[2] } : null;
|
||
}
|
||
|
||
function readJson(file) {
|
||
try {
|
||
return { value: JSON.parse(fs.readFileSync(file, "utf8")), stamp: fs.statSync(file).mtimeMs };
|
||
} catch {
|
||
return { value: null, stamp: 0 };
|
||
}
|
||
}
|
||
|
||
function findSuiteRunDir(suiteRoot) {
|
||
try {
|
||
const entries = fs.readdirSync(suiteRoot)
|
||
.filter((name) => name.startsWith("run-"))
|
||
.map((name) => path.join(suiteRoot, name));
|
||
if (!entries.length) return null;
|
||
return entries.sort().at(-1);
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
function summarizeSuite(runDir) {
|
||
const manifest = readJson(path.join(runDir, "manifest.json")).value;
|
||
const checkpoint = readJson(path.join(runDir, "checkpoint.json")).value;
|
||
const results = readJson(path.join(runDir, "results.json")).value;
|
||
const planned = manifest?.cases?.length ?? 0;
|
||
const completed = checkpoint?.completed?.length ?? results?.results?.filter((item) => item.status !== "running").length ?? 0;
|
||
return {
|
||
planned,
|
||
completed,
|
||
current: checkpoint?.current ?? results?.results?.find((item) => item.status === "running")?.id ?? null,
|
||
counts: results?.counts ?? null,
|
||
results: (results?.results ?? []).map((item) => ({
|
||
id: item.id, title: item.title, status: item.status, seconds: item.seconds, error: item.error ?? null,
|
||
})),
|
||
origin: results?.origin ?? manifest?.origin ?? null,
|
||
};
|
||
}
|
||
|
||
/* ----------------------------------------------------------------- runner */
|
||
|
||
export function createRunner({ root = CONSOLE_ROOT } = {}) {
|
||
const jobs = new Map();
|
||
const listeners = new Map();
|
||
let active = null;
|
||
|
||
function emit(job, event, data) {
|
||
const set = listeners.get(job.id);
|
||
if (!set) return;
|
||
for (const send of set) {
|
||
try {
|
||
send(event, data);
|
||
} catch {
|
||
/* listener gone; cleaned up by its close handler */
|
||
}
|
||
}
|
||
}
|
||
|
||
function snapshot(job) {
|
||
const base = {
|
||
jobId: job.id, lessonId: job.lessonId, kind: job.kind, state: job.state,
|
||
startedAt: job.startedAt, endedAt: job.endedAt, seconds: job.seconds,
|
||
exitCode: job.exitCode, runDir: job.runDir, verdict: job.verdict, error: job.error,
|
||
argv: job.command, logs: job.lines.length,
|
||
};
|
||
if (job.kind === "suite" && job.runDir) return { ...base, ...job.progress };
|
||
return { ...base, ...job.progress };
|
||
}
|
||
|
||
function setState(job, state, extra = {}) {
|
||
job.state = state;
|
||
Object.assign(job, extra);
|
||
emit(job, "snapshot", snapshot(job));
|
||
}
|
||
|
||
function appendLine(job, stream, line) {
|
||
job.lines.push({ stream, text: line, at: Date.now() });
|
||
job.bytes += Buffer.byteLength(line) + 1;
|
||
while (job.lines.length > LINE_LIMIT || (job.bytes > BYTE_LIMIT && job.lines.length > 200)) {
|
||
const removed = job.lines.shift();
|
||
job.bytes -= Buffer.byteLength(removed.text) + 1;
|
||
}
|
||
emit(job, "log", { stream, text: line });
|
||
}
|
||
|
||
function wireOutput(job, stream, chunk) {
|
||
job.partial[stream] += chunk.toString("utf8");
|
||
const pieces = job.partial[stream].split("\n");
|
||
job.partial[stream] = pieces.pop() ?? "";
|
||
for (const piece of pieces) onLine(job, stream, piece);
|
||
}
|
||
|
||
function onLine(job, stream, line) {
|
||
if (!line.trim()) return;
|
||
appendLine(job, stream, line);
|
||
if (/^ORIGIN=/.test(line)) job.progress.origin = line.slice("ORIGIN=".length).trim();
|
||
if (/^fatal:/.test(line)) job.fatal = line;
|
||
const parsed = parseProgressLine(line);
|
||
if (parsed && job.progress.results) {
|
||
const existing = job.progress.results.find((item) => item.id === parsed.id);
|
||
if (existing) existing.status = parsed.status;
|
||
if (parsed.status !== "skipped") job.progress.completed = Math.min((job.progress.completed ?? 0) + (existing ? 0 : 1), job.progress.planned || Number.MAX_SAFE_INTEGER);
|
||
if (parsed.status !== "skipped") emit(job, "snapshot", snapshot(job));
|
||
}
|
||
}
|
||
|
||
function pollSuite(job) {
|
||
const suiteRoot = path.join(job.dir, "suite");
|
||
const runDir = findSuiteRunDir(suiteRoot);
|
||
if (runDir) {
|
||
job.runDir = path.relative(REPO_ROOT, runDir).split(path.sep).join("/");
|
||
const summary = summarizeSuite(runDir);
|
||
const changed = JSON.stringify(summary) !== JSON.stringify(job.progress);
|
||
job.progress = summary;
|
||
if (changed) emit(job, "snapshot", snapshot(job));
|
||
}
|
||
}
|
||
|
||
function finish(job, code, signal) {
|
||
if (job.finished) return;
|
||
job.finished = true;
|
||
clearInterval(job.poll);
|
||
clearTimeout(job.timeout);
|
||
if (active === job) active = null;
|
||
job.endedAt = new Date().toISOString();
|
||
job.seconds = Math.round((Date.now() - Date.parse(job.startedAt)) / 1000);
|
||
job.exitCode = code;
|
||
|
||
if (job.kind === "suite") {
|
||
pollSuite(job);
|
||
const counts = job.progress.counts ?? { passed: 0, failed: 0, blocked: 0 };
|
||
if (job.cancelled) job.verdict = "cancelled";
|
||
else if (job.timedOut) job.verdict = "timeout";
|
||
else if (job.fatal) job.verdict = "run_fail";
|
||
else if ((counts.failed ?? 0) > 0) job.verdict = "product_fail";
|
||
else if ((counts.blocked ?? 0) > 0) job.verdict = "precondition_fail";
|
||
else if (code === 0) job.verdict = "pass";
|
||
else job.verdict = "run_fail";
|
||
} else if (job.kind === "probe") {
|
||
job.progress = { ...job.progress, report: readJson(path.join(job.dir, "layout.json")).value };
|
||
if (job.cancelled) job.verdict = "cancelled";
|
||
else if (job.timedOut) job.verdict = "timeout";
|
||
else if (code === 0) job.verdict = "pass";
|
||
else if (code === 2) job.verdict = "precondition_fail";
|
||
else job.verdict = "product_fail";
|
||
} else if (job.kind === "reducer-part" || job.kind === "reducer-assembly") {
|
||
const report = readJson(path.join(job.dir, "report.json")).value;
|
||
const label = job.kind === "reducer-part" ? (report?.part?.id ?? "part") : "assembly";
|
||
job.progress = {
|
||
...job.progress,
|
||
planned: 1,
|
||
completed: 1,
|
||
results: report ? [{
|
||
id: label,
|
||
title: report.part?.title ?? report.document ?? "装配",
|
||
status: report.verdict === "pass" ? "passed" : report.verdict === "product_fail" ? "failed" : "blocked",
|
||
seconds: report.seconds ?? null,
|
||
error: report.verdict === "product_fail" && report.volumeMatches === false
|
||
? `体积 ${report.volume} ≠ 记录 ${report.expectedVolume}` : (report.fatal ?? null),
|
||
}] : [],
|
||
};
|
||
if (job.cancelled) job.verdict = "cancelled";
|
||
else if (job.timedOut) job.verdict = "timeout";
|
||
else if (!report) job.verdict = code === 2 ? "precondition_fail" : "run_fail";
|
||
else job.verdict = report.verdict;
|
||
} else if (job.kind === "host") {
|
||
// The host lesson succeeds once ORIGIN is printed; an explicit user
|
||
// cancel still reads as cancelled even if that already happened.
|
||
if (job.cancelled) job.verdict = "cancelled";
|
||
else if (job.progress.origin) job.verdict = "pass";
|
||
else job.verdict = job.timedOut ? "timeout" : "run_fail";
|
||
} else {
|
||
job.verdict = code === 0 ? "pass" : "run_fail";
|
||
}
|
||
|
||
// Flush any trailing partial line before the terminal snapshot.
|
||
for (const stream of ["stdout", "stderr"]) {
|
||
if (job.partial[stream]) {
|
||
appendLine(job, stream, job.partial[stream]);
|
||
job.partial[stream] = "";
|
||
}
|
||
}
|
||
job.progress = { ...job.progress, signal: signal ?? null };
|
||
emit(job, "snapshot", snapshot(job));
|
||
emit(job, "done", snapshot(job));
|
||
}
|
||
|
||
function killTree(job, signal = "SIGTERM") {
|
||
if (!job.child?.pid) return;
|
||
try {
|
||
process.kill(-job.child.pid, signal);
|
||
} catch {
|
||
try {
|
||
job.child.kill(signal);
|
||
} catch {
|
||
/* already gone */
|
||
}
|
||
}
|
||
}
|
||
|
||
function start({ lessonId, params = {} }) {
|
||
const entry = catalog().byId.get(lessonId);
|
||
if (!entry) throw new JobError("E_LESSON", `未知课程:${String(lessonId).slice(0, 40)}`);
|
||
if (active) throw new JobError("E_BUSY", "已有一节课在运行", { activeJobId: active.id });
|
||
|
||
const report = preflight();
|
||
if (!report.ok && entry.job.kind !== "preflight") {
|
||
throw new JobError("E_PREFLIGHT", "前置条件未满足,未启动运行", { blockers: report.checks.filter((check) => check.hard && !check.ok) });
|
||
}
|
||
|
||
const id = `job-${new Date().toISOString().replace(/[:.]/g, "-")}-${crypto.randomBytes(3).toString("hex")}`;
|
||
const dir = path.join(root, "runs", id);
|
||
fs.mkdirSync(dir, { recursive: true });
|
||
const { argv } = buildJobArgv(entry, params, { jobDir: dir });
|
||
const job = {
|
||
id, lessonId, kind: entry.job.kind, dir, state: "starting",
|
||
startedAt: new Date().toISOString(), endedAt: null, seconds: null,
|
||
exitCode: null, runDir: null, verdict: null, error: null, fatal: null,
|
||
cancelRequested: false, cancelled: false, timedOut: false,
|
||
lines: [], bytes: 0, partial: { stdout: "", stderr: "" },
|
||
progress: {
|
||
planned: entry.job.kind === "reducer-part" || entry.job.kind === "reducer-assembly"
|
||
? 1
|
||
: entry.job.selectable ? (params.only?.length ?? 0) : (entry.job.only?.length ?? 0),
|
||
completed: 0, current: null, counts: null, results: [],
|
||
},
|
||
command: argv ? argvToCommand(argv) : "(无命令:仅检查前置条件)",
|
||
};
|
||
fs.writeFileSync(path.join(dir, "job.json"), JSON.stringify({
|
||
id, lessonId, kind: job.kind, command: job.command,
|
||
argv: argv ? argv.map((part) => path.relative(REPO_ROOT, part) || part) : null,
|
||
startedAt: job.startedAt,
|
||
}, null, 2));
|
||
|
||
jobs.set(id, job);
|
||
if (entry.job.kind === "preflight") {
|
||
job.progress = { ...job.progress, preflight: report };
|
||
setState(job, "running");
|
||
setImmediate(() => finish(job, 0, null));
|
||
return snapshot(job);
|
||
}
|
||
|
||
active = job;
|
||
setState(job, "running");
|
||
|
||
const env = {
|
||
PATH: process.env.PATH ?? "",
|
||
HOME: process.env.HOME ?? "",
|
||
LANG: process.env.LANG ?? "C.UTF-8",
|
||
LC_ALL: process.env.LC_ALL ?? "",
|
||
TMPDIR: process.env.TMPDIR ?? "",
|
||
DISPLAY: process.env.DISPLAY ?? "",
|
||
FREECAD_CHROME: process.env.FREECAD_CHROME ?? "",
|
||
};
|
||
|
||
let child;
|
||
try {
|
||
child = spawn(argv[0], argv.slice(1), { cwd: REPO_ROOT, env, detached: true, stdio: ["ignore", "pipe", "pipe"] });
|
||
} catch (error) {
|
||
job.error = error instanceof Error ? error.message : String(error);
|
||
finish(job, -1, null);
|
||
return snapshot(job);
|
||
}
|
||
job.child = child;
|
||
child.stdout.on("data", (chunk) => wireOutput(job, "stdout", chunk));
|
||
child.stderr.on("data", (chunk) => wireOutput(job, "stderr", chunk));
|
||
child.on("error", (error) => {
|
||
job.error = error instanceof Error ? error.message : String(error);
|
||
});
|
||
child.on("close", (code, signal) => finish(job, code, signal));
|
||
|
||
job.poll = setInterval(() => {
|
||
if (job.kind === "suite") pollSuite(job);
|
||
}, POLL_MS);
|
||
job.timeout = setTimeout(() => {
|
||
job.timedOut = true;
|
||
job.stoppedByTimeout = job.kind === "host";
|
||
killTree(job);
|
||
}, TIMEOUTS[job.kind] ?? TIMEOUTS.suite);
|
||
if (job.timeout.unref) job.timeout.unref();
|
||
|
||
return snapshot(job);
|
||
}
|
||
|
||
function cancel(jobId) {
|
||
const job = jobs.get(jobId);
|
||
if (!job) throw new JobError("E_NO_JOB", "找不到该任务");
|
||
if (job.finished) throw new JobError("E_NOT_RUNNING", "任务已结束");
|
||
job.cancelRequested = true;
|
||
job.cancelled = true;
|
||
killTree(job);
|
||
setTimeout(() => killTree(job, "SIGKILL"), 5000).unref?.();
|
||
setState(job, "cancelling");
|
||
return snapshot(job);
|
||
}
|
||
|
||
function get(jobId) {
|
||
const job = jobs.get(jobId);
|
||
if (!job) throw new JobError("E_NO_JOB", "找不到该任务");
|
||
return { snapshot: snapshot(job), lines: job.lines.slice(-300) };
|
||
}
|
||
|
||
function subscribe(jobId, send) {
|
||
if (!listeners.has(jobId)) listeners.set(jobId, new Set());
|
||
listeners.get(jobId).add(send);
|
||
const job = jobs.get(jobId);
|
||
if (job) {
|
||
send("snapshot", snapshot(job));
|
||
for (const line of job.lines.slice(-200)) send("log", { stream: line.stream, text: line.text });
|
||
}
|
||
return () => {
|
||
const set = listeners.get(jobId);
|
||
if (!set) return;
|
||
set.delete(send);
|
||
if (!set.size) listeners.delete(jobId);
|
||
};
|
||
}
|
||
|
||
function artifact(jobId, rel) {
|
||
const job = jobs.get(jobId);
|
||
if (!job) throw new JobError("E_NO_JOB", "找不到该任务");
|
||
const base = job.dir;
|
||
const target = path.resolve(base, rel);
|
||
if (target !== base && !target.startsWith(`${base}${path.sep}`)) throw new JobError("E_PARAM", "非法路径");
|
||
return target;
|
||
}
|
||
|
||
function close() {
|
||
for (const job of jobs.values()) {
|
||
if (!job.finished && job.child) killTree(job, "SIGKILL");
|
||
}
|
||
}
|
||
|
||
return { start, cancel, get, subscribe, artifact, preflight, catalog, close };
|
||
}
|