Files
FreeCADWasmDev/tools/run_p6_sketcher_get_sketch_method_gate.mjs
wangdequan 9a7c4f0335 Save FreeCAD Web workspace sources and user validation evidence
IFC native binding remains incomplete; preserve accurate test results.
2026-09-15 22:01:58 +08:00

109 lines
11 KiB
JavaScript

#!/usr/bin/env node
import crypto from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { Worker } from "node:worker_threads";
import { createRequire } from "node:module";
import { fileURLToPath, pathToFileURL } from "node:url";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const build = path.resolve(process.argv[2] ?? path.join(root, "freecad-source/build-web/configure/bin"));
const out = fs.mkdtempSync(path.join(os.tmpdir(), "freecad-p6-sketcher-get-sketch-"));
const hash = (value) => crypto.createHash("sha256").update(typeof value === "string" ? value : JSON.stringify(value)).digest("hex");
const fileHash = (file) => crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
const tsc = path.join(root, "web/node_modules/.bin/tsc");
const { execFileSync } = await import("node:child_process");
execFileSync(tsc, ["--target", "ES2022", "--module", "ESNext", "--moduleResolution", "Bundler", "--strict", "--skipLibCheck", "--outDir", out, "--declaration", "false", "--noEmit", "false", "web/src/facade-envelope.ts", "web/src/sketcher-python-method-facade.ts", "web/src/api-method-bridge.ts"], { cwd: root, stdio: "inherit" });
globalThis.__dirname = `${build}${path.sep}`;
globalThis.require = createRequire(import.meta.url);
const loader = await import(pathToFileURL(path.join(build, "FreeCADWebSketcherProbe.js")));
const kernel = await loader.default({ wasmBinary: fs.readFileSync(path.join(build, "FreeCADWebSketcherProbe.wasm")), locateFile: (file) => path.join(build, file), print: () => {}, printErr: () => {} });
const facade = await import(pathToFileURL(path.join(out, "sketcher-python-method-facade.js")));
const envelope = await import(pathToFileURL(path.join(out, "facade-envelope.js")));
const apiBridgeModule = await import(pathToFileURL(path.join(out, "api-method-bridge.js")));
const invoke = (request) => JSON.parse(String(kernel.ccall("fc_web_dispatch_json", "string", ["string"], [JSON.stringify(request)])));
const queue = new envelope.FacadeSerialQueue();
const request = facade.createSketcherGetSketchRequest("sketcher-get-sketch-success");
const success = await facade.dispatchSketcherPythonMethod(queue, request, kernel);
const repeated = await facade.dispatchSketcherPythonMethod(queue, facade.createSketcherGetSketchRequest("sketcher-get-sketch-repeat"), kernel);
const malformed = await facade.dispatchSketcherPythonMethod(queue, { ...request, requestId: "sketcher-get-sketch-malformed", payload: { ...request.payload, tier: "tier-1-readonly" } }, kernel);
const cancelRequest = facade.createSketcherGetSketchRequest("sketcher-get-sketch-cancel");
const cancelledPromise = facade.dispatchSketcherPythonMethod(queue, cancelRequest, new Promise((resolve) => setTimeout(() => resolve(kernel), 25)));
const cancelledAccepted = queue.cancel(envelope.createCancel("sketcher-get-sketch-cancel-control", cancelRequest.requestId, "sketcher-python-method"));
const cancelled = await cancelledPromise;
const directRequest = { cmd: "sketcher.pythonMethod", args: request.payload };
const direct = invoke(directRequest);
const directRepeat = invoke(directRequest);
const crossModule = invoke({ cmd: directRequest.cmd, args: { ...directRequest.args, module: "Part", apiId: "py:Part:function:getSketch" } });
const unsupported = invoke({ cmd: "sketcher.unknown", args: {} });
const runtimeIndex = JSON.parse(fs.readFileSync(path.join(root, "web/public/api/python-api-index.json"), "utf8"));
const bridgeRouter = { request: async (_module, _command, payload) => envelope.createSuccess("router-get-sketch", await facade.handleSketcherPythonMethod(payload, new AbortController().signal, kernel)) };
const apiBridge = new apiBridgeModule.ApiMethodBridge(bridgeRouter, runtimeIndex);
const bridgeSuccess = await apiBridge.call({ apiId: facade.SKETCHER_GET_SKETCH_API_ID });
const bridgeInvalid = await apiBridge.call({ apiId: facade.SKETCHER_GET_SKETCH_API_ID, args: [1] });
if (success.kind !== "result" || success.result.status !== "exposed" || success.result.result.hasSketch !== false || success.result.result.withoutDocument !== false || success.result.result.withDocument !== false || success.result.result.guiAvailable !== false || success.result.resourcesReleased !== true) throw new Error(`native Sketcher getSketch method failed: ${JSON.stringify(success)}`);
if (repeated.kind !== "result" || JSON.stringify(success.result) !== JSON.stringify(repeated.result)) throw new Error("Sketcher getSketch replay changed");
if (malformed.kind !== "error" || malformed.error.code !== "invalid_request") throw new Error(`invalid Sketcher getSketch envelope was accepted: ${JSON.stringify(malformed)}`);
if (!cancelledAccepted || cancelled.kind !== "error" || cancelled.error.code !== "cancelled") throw new Error(`Sketcher getSketch cancellation failed: ${JSON.stringify(cancelled)}`);
if (direct.ok !== true || direct.result.hasSketch !== false || direct.result.withDocument !== false || directRepeat.ok !== true || JSON.stringify(direct) !== JSON.stringify(directRepeat)) throw new Error(`direct Sketcher getSketch dispatch failed: ${JSON.stringify({ direct, directRepeat })}`);
if (crossModule.ok !== false || crossModule.code !== "unmatched_source_record" || unsupported.ok !== false || unsupported.code !== "unsupported_command") throw new Error(`Sketcher getSketch boundaries failed: ${JSON.stringify({ crossModule, unsupported })}`);
if (bridgeSuccess.kind !== "result" || bridgeSuccess.result.apiId !== facade.SKETCHER_GET_SKETCH_API_ID || bridgeSuccess.result.result.hasSketch !== false || bridgeInvalid.kind !== "error" || bridgeInvalid.error.code !== "invalid_arguments") throw new Error(`Sketcher getSketch API bridge failed: ${JSON.stringify({ bridgeSuccess, bridgeInvalid })}`);
const manifestPath = path.join(root, "docs/p6/python-api-manifest.json");
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
const row = manifest.records.find((record) => record.id === facade.SKETCHER_GET_SKETCH_API_ID);
if (!row) throw new Error("Sketcher getSketch is missing from python-api-manifest.json");
row.disposition = "exposed";
row.dispositionEvidence = ["docs/p6/sketcher-get-sketch-method-runtime.json"];
row.dispositionReason = "official Sketcher Profiles.getSketch source replay through fc_web_dispatch_json";
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
const trace = { success, repeated, malformed, cancelled, direct, directRepeat, crossModule, unsupported, bridgeSuccess, bridgeInvalid };
const report = {
schema: "freecad-web-p6-sketcher-get-sketch-method-runtime/v1",
taskId: "FW-P6-FPA-Y",
module: "Sketcher",
tier: "tier-2-pure",
apiId: facade.SKETCHER_GET_SKETCH_API_ID,
status: "pass",
route: { command: facade.SKETCHER_PYTHON_METHOD_COMMAND, worker: "web/src/sketcher-python.worker.ts", facade: "web/src/sketcher-python-method-facade.ts", apiBridge: "web/src/api-method-bridge.ts", native: "freecad-source/src/WebAssembly/FreeCADCoreProbe/SketcherProbe.cpp:fc_web_dispatch_json" },
source: { entry: "src/Mod/Sketcher/Profiles.py", line: 40, revision: success.result.sourceRevision, guiShim: "FreeCADGui.ActiveDocument.getInEdit returns None; official getSketch source remains unchanged" },
request,
requestSha256: hash(request),
trace,
traceSha256: hash(trace),
replay: { equal: true, resultSha256: hash(repeated.result) },
resources: { resourcesReleased: success.result.resourcesReleased, documentMutation: false, temporaryDocumentClosed: true },
artifacts: { wasm: { path: "web/public/kernel/FreeCADWebSketcherProbe.wasm", sha256: fileHash(path.join(root, "web/public/kernel/FreeCADWebSketcherProbe.wasm")) }, loader: { path: "web/public/kernel/FreeCADWebSketcherProbe.js", sha256: fileHash(path.join(root, "web/public/kernel/FreeCADWebSketcherProbe.js")) } },
boundaries: ["GUI-only edit selection remains unavailable in the headless Web kernel and is represented by hasSketch=false.", "The method has no arguments and does not mutate the Document.", "All result fields and statuses come from compiled FreeCAD through fc_web_dispatch_json."]
};
const worker = new Worker(path.join(root, "tools/sketcher-python-method-smoke-worker.mjs"), { workerData: { buildDirectory: build, facadePath: pathToFileURL(path.join(out, "sketcher-python-method-facade.js")).href, envelopePath: pathToFileURL(path.join(out, "facade-envelope.js")).href } });
const receive = () => new Promise((resolve, reject) => { const onMessage = (value) => { worker.off("error", onError); resolve(value); }; const onError = (error) => { worker.off("message", onMessage); reject(error); }; worker.once("message", onMessage); worker.once("error", onError); });
const ready = await receive();
worker.postMessage(request);
const workerSuccess = await receive();
worker.postMessage(request);
const workerDuplicate = await receive();
const workerCancel = facade.createSketcherGetSketchRequest("sketcher-get-sketch-worker-cancel");
const workerCancelledPromise = new Promise((resolve, reject) => { const onMessage = (value) => { if (value.requestId === workerCancel.requestId) { worker.off("error", reject); resolve(value); } }; worker.on("message", onMessage); worker.once("error", reject); });
worker.postMessage(workerCancel);
worker.postMessage(envelope.createCancel("sketcher-get-sketch-worker-cancel-control", workerCancel.requestId, "sketcher-python-method"));
const workerCancelled = await workerCancelledPromise;
worker.postMessage({ kind: "reset", requestId: "sketcher-get-sketch-worker-reset" });
const reset = await receive();
await worker.terminate();
if (ready.kind !== "ready" || workerSuccess.kind !== "result" || workerSuccess.result.result.hasSketch !== false || workerDuplicate.kind !== "error" || workerDuplicate.error.code !== "duplicate_request" || workerCancelled.kind !== "error" || workerCancelled.error.code !== "cancelled" || reset.requestId !== "sketcher-get-sketch-worker-reset") throw new Error(`Sketcher getSketch Worker sequencing failed: ${JSON.stringify({ ready, workerSuccess, workerDuplicate, workerCancelled, reset })}`);
report.worker = { trace: { ready, success: workerSuccess, duplicate: workerDuplicate, cancelled: workerCancelled, reset }, sequencing: { duplicate: true, cancelAccepted: true, resetAccepted: true, maxActive: 1 } };
report.worker.traceSha256 = hash(report.worker.trace);
report.resultSha256 = hash({ trace: report.trace, worker: report.worker, source: report.source, resources: report.resources });
fs.writeFileSync(path.join(root, "docs/p6/sketcher-get-sketch-method-runtime.json"), `${JSON.stringify(report, null, 2)}\n`);
fs.writeFileSync(path.join(root, "docs/freecad-p6-sketcher-get-sketch-method.log"), `${JSON.stringify({ status: report.status, apiId: report.apiId, hasSketch: direct.result.hasSketch, resourcesReleased: success.result.resourcesReleased, traceSha256: report.traceSha256, workerTraceSha256: report.worker.traceSha256, resultSha256: report.resultSha256 })}\n`);
console.log(JSON.stringify({ status: report.status, apiId: report.apiId, hasSketch: direct.result.hasSketch, workerCancel: workerCancelled.error.code, resultSha256: report.resultSha256 }));
// The pthread-enabled probe owns a worker pool; terminate after evidence is flushed.
process.exit(0);