Files
FreeCADWasmDev/web/teaching/server.mjs
wangdequan 3a3077c089 teaching: run carrier builds from the toolkit page
Extract the console runner into web/teaching/console-runner.js (classic
script, file:// safe) and mount it on carrier-toolkit.html: per-part 运行本件,
per-group 运行本组, 运行全部 and 运行装配, all fed by lessons.mjs ids at build
time. Fix runButton() emitting a duplicate class attribute that dropped
run-group/run-assembly. Server banner now prints the carrier page URL; new
check:carrier-live gate drives the dry lesson end-to-end.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 21:45:08 +08:00

316 lines
12 KiB
JavaScript

#!/usr/bin/env node
// Teaching console server: serves the manual pages, the generated case data,
// the real evidence files and a POST /api/run endpoint that executes one case
// in a HEADED Chrome window (run-case.mjs) so a beginner can watch it happen.
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
import crypto from "node:crypto";
import { spawn } from "node:child_process";
import { fileURLToPath } from "node:url";
import { JobError, createRunner } from "./suite-runner.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(here, "../..");
const port = Number(process.env.TEACHING_PORT || "5190");
// TEACHING_PORT=0 binds an ephemeral port; the Origin check must use the real one.
let boundPort = port;
const appOrigin = process.env.FREECAD_APP_ORIGIN || "http://127.0.0.1:5180";
// Random per-process token guards the endpoints that spawn processes. The page
// receives it in the console URL; EventSource passes it back as ?token=.
const token = process.env.TEACHING_TOKEN || crypto.randomBytes(16).toString("hex");
const runner = createRunner();
const types = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".mjs": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".svg": "image/svg+xml",
".txt": "text/plain; charset=utf-8",
".md": "text/plain; charset=utf-8",
".mp4": "video/mp4",
".webm": "video/webm",
".vtt": "text/vtt; charset=utf-8",
".srt": "application/x-subrip; charset=utf-8",
".m4a": "audio/mp4",
};
function sendFile(request, response, filePath) {
if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) {
response.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
response.end("not found");
return;
}
const stat = fs.statSync(filePath);
const extension = path.extname(filePath).toLowerCase();
const media = [".mp4", ".webm", ".m4a", ".vtt", ".srt"].includes(extension);
const headers = {
"content-type": types[extension] ?? "application/octet-stream",
// Video must be cacheable and range-readable for seeking; HTML/data stay fresh.
"cache-control": media ? "public, max-age=3600" : "no-store",
"access-control-allow-origin": "*",
"access-control-expose-headers": "content-length, content-range, accept-ranges",
"accept-ranges": "bytes",
};
const range = request.headers.range;
if (range) {
const match = /^bytes=(\d*)-(\d*)$/.exec(String(range).trim());
if (!match || (match[1] === "" && match[2] === "")) {
response.writeHead(416, { ...headers, "content-range": `bytes */${stat.size}` });
response.end();
return;
}
let start;
let end;
if (match[1] === "") {
const suffix = Number(match[2]);
if (!Number.isFinite(suffix) || suffix <= 0) {
response.writeHead(416, { ...headers, "content-range": `bytes */${stat.size}` });
response.end();
return;
}
start = Math.max(stat.size - suffix, 0);
end = stat.size - 1;
} else {
start = Number(match[1]);
end = match[2] === "" ? stat.size - 1 : Number(match[2]);
if (!Number.isFinite(start) || !Number.isFinite(end) || start > end || start >= stat.size) {
response.writeHead(416, { ...headers, "content-range": `bytes */${stat.size}` });
response.end();
return;
}
end = Math.min(end, stat.size - 1);
}
response.writeHead(206, {
...headers,
"content-range": `bytes ${start}-${end}/${stat.size}`,
"content-length": String(end - start + 1),
});
if (request.method === "HEAD") { response.end(); return; }
fs.createReadStream(filePath, { start, end }).pipe(response);
return;
}
response.writeHead(200, { ...headers, "content-length": String(stat.size) });
if (request.method === "HEAD") { response.end(); return; }
fs.createReadStream(filePath).pipe(response);
}
function within(root, target) {
const resolved = path.resolve(target);
return resolved === root || resolved.startsWith(`${root}${path.sep}`);
}
const running = new Map();
/* ------------------------------------------------------ console API helpers */
function sendJson(response, status, payload) {
response.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
response.end(JSON.stringify(payload));
}
async function readBody(request, limit = 8192) {
let size = 0;
const chunks = [];
for await (const chunk of request) {
size += chunk.length;
if (size > limit) throw new JobError("E_BODY", "请求体过大");
chunks.push(chunk);
}
try {
return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
} catch {
throw new JobError("E_BODY", "请求体不是 JSON");
}
}
function tokenOk(request, url) {
const header = request.headers["x-teaching-token"];
const provided = typeof header === "string" ? header : (url.searchParams.get("token") ?? "");
if (provided.length !== token.length) return false;
return crypto.timingSafeEqual(Buffer.from(provided), Buffer.from(token));
}
function originOk(request) {
const origin = request.headers.origin;
if (!origin) return true;
return origin === `http://127.0.0.1:${boundPort}` || origin === `http://localhost:${boundPort}`;
}
const JOB_STATUS = { E_LESSON: 404, E_PARAM: 400, E_BUSY: 409, E_PREFLIGHT: 409, E_NO_JOB: 404, E_NOT_RUNNING: 409, E_BODY: 400 };
function handleConsoleApi(request, response, url, pathname) {
const sub = pathname.slice("/api/console/".length);
const method = request.method ?? "GET";
const route = async () => {
if (sub === "health" && method === "GET") {
sendJson(response, 200, { schema: "freecad-web-teaching-console/v1", origin: `http://127.0.0.1:${port}`, preflight: runner.preflight().ok });
return;
}
if (sub === "lessons" && method === "GET") { sendJson(response, 200, runner.catalog().lessons); return; }
if (sub === "preflight" && method === "GET") { sendJson(response, 200, runner.preflight()); return; }
if ((sub === "run" || sub === "cancel") && method === "POST") {
if (!originOk(request)) { sendJson(response, 403, { code: "E_ORIGIN", error: "来源不在白名单" }); return; }
if (!tokenOk(request, url)) { sendJson(response, 401, { code: "E_TOKEN", error: "缺少或错误的 token" }); return; }
const body = await readBody(request);
if (sub === "run") {
sendJson(response, 202, runner.start({ lessonId: String(body.lessonId ?? ""), params: body.params ?? {} }));
} else {
sendJson(response, 200, runner.cancel(String(body.jobId ?? "")));
}
return;
}
if (sub === "events" && method === "GET") {
const jobId = url.searchParams.get("jobId") ?? "";
try {
runner.get(jobId);
} catch (error) {
sendJson(response, 404, { code: "E_NO_JOB", error: "找不到该任务" });
return;
}
response.writeHead(200, {
"content-type": "text/event-stream; charset=utf-8",
"cache-control": "no-store",
connection: "keep-alive",
"x-accel-buffering": "no",
});
const send = (event, data) => response.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
const unsubscribe = runner.subscribe(jobId, send);
const ping = setInterval(() => response.write(": ping\n\n"), 15000);
request.on("close", () => { clearInterval(ping); unsubscribe(); });
return;
}
const jobMatch = /^job\/([^/]+)$/.exec(sub);
if (jobMatch && method === "GET") { sendJson(response, 200, runner.get(jobMatch[1])); return; }
const artifactMatch = /^artifacts\/([^/]+)\/(.+)$/.exec(sub);
if (artifactMatch && method === "GET") {
sendFile(request, response, runner.artifact(artifactMatch[1], decodeURIComponent(artifactMatch[2])));
return;
}
sendJson(response, 404, { code: "E_ROUTE", error: "未知接口" });
};
route().catch((error) => {
if (error instanceof JobError) {
sendJson(response, JOB_STATUS[error.code] ?? 500, { code: error.code, error: error.message, detail: error.detail ?? null });
} else {
sendJson(response, 500, { code: "E_INTERNAL", error: error instanceof Error ? error.message : String(error) });
}
});
}
function runCase(body) {
return new Promise((resolve, reject) => {
const { moduleName, command, caseId, payload } = body;
if (!moduleName || !command) { reject(new Error("moduleName and command are required")); return; }
const args = [
path.join(here, "run-case.mjs"),
"--module", String(moduleName),
"--command", String(command),
"--case", String(caseId || `${moduleName}-${command}`),
"--origin", appOrigin,
"--artifacts", path.join(repoRoot, "docs", "current", "teaching-runs"),
];
if (payload) args.push("--payload", String(payload));
const child = spawn(process.execPath, args, { cwd: repoRoot, env: { ...process.env, HEADLESS: process.env.HEADLESS ?? "0" } });
let stdout = "";
let stderr = "";
child.stdout.on("data", chunk => { stdout += chunk; });
child.stderr.on("data", chunk => { stderr += chunk; });
child.on("error", reject);
child.on("close", code => {
const line = stdout.trim().split("\n").filter(Boolean).at(-1) ?? "{}";
let parsed;
try { parsed = JSON.parse(line); } catch { parsed = { ok: false, error: line.slice(0, 400) }; }
parsed.exitCode = code;
parsed.stderrTail = stderr.slice(-1200);
resolve(parsed);
});
});
}
const server = http.createServer(async (request, response) => {
const url = new URL(request.url ?? "/", `http://127.0.0.1:${port}`);
const pathname = decodeURIComponent(url.pathname);
if (request.method === "OPTIONS") {
response.writeHead(204, { "access-control-allow-origin": "*", "access-control-allow-headers": "content-type", "access-control-allow-methods": "GET,POST" });
response.end();
return;
}
if (pathname.startsWith("/api/console/")) {
handleConsoleApi(request, response, url, pathname);
return;
}
if (pathname === "/api/health") {
response.writeHead(200, { "content-type": "application/json; charset=utf-8" });
response.end(JSON.stringify({ ok: true, appOrigin, cases: path.join(here, "data/cases.json") }));
return;
}
if (pathname === "/api/run" && request.method === "POST") {
let raw = "";
for await (const chunk of request) raw += chunk;
try {
const body = JSON.parse(raw || "{}");
const key = `${body.caseId}`;
if (running.has(key)) {
response.writeHead(409, { "content-type": "application/json; charset=utf-8" });
response.end(JSON.stringify({ ok: false, error: "该案例正在执行中" }));
return;
}
running.set(key, true);
const result = await runCase(body);
running.delete(key);
response.writeHead(200, { "content-type": "application/json; charset=utf-8", "access-control-allow-origin": "*" });
response.end(JSON.stringify(result));
} catch (error) {
response.writeHead(500, { "content-type": "application/json; charset=utf-8" });
response.end(JSON.stringify({ ok: false, error: error instanceof Error ? error.message : String(error) }));
}
return;
}
if (pathname.startsWith("/evidence/")) {
const target = path.join(repoRoot, "docs", pathname.slice("/evidence/".length));
if (!within(path.join(repoRoot, "docs"), target)) { response.writeHead(403); response.end("forbidden"); return; }
sendFile(request, response, target);
return;
}
const relative = pathname === "/" ? "index.html" : pathname.replace(/^\/+/, "");
const target = within(here, path.join(here, relative)) ? path.join(here, relative) : null;
if (!target) { response.writeHead(403); response.end("forbidden"); return; }
sendFile(request, response, target);
});
server.listen(port, "127.0.0.1", () => {
const actualPort = server.address()?.port ?? port;
boundPort = actualPort;
const origin = `http://127.0.0.1:${actualPort}`;
console.log(JSON.stringify({
schema: "freecad-web-teaching-server/v1",
origin,
appOrigin,
token,
console: `${origin}/console.html?token=${token}`,
// The carrier toolkit page mounts the same runner (console-runner.js), so it
// is a first-class entry point, not a link out to the console.
carrier: `${origin}/carrier-toolkit.html?token=${token}`,
}));
});
for (const signal of ["SIGINT", "SIGTERM"]) {
process.on(signal, () => {
runner.close();
server.close(() => process.exit(0));
setTimeout(() => process.exit(0), 2000).unref();
});
}