import assert from "node:assert/strict"; import crypto from "node:crypto"; import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { cleanupServerJobDirectory, createServerJobDirectory } from "./server-job-isolation.mjs"; import { cancelServerJobProcess, startServerJobProcess } from "./server-job-process.mjs"; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); const reportPath = path.join(root, "tests/golden/M13-04G/server-job-cancellation-report.json"); const manifestPath = path.join(root, "tests/golden/M13-04G/manifest.json"); const hashFile = async (file) => crypto.createHash("sha256").update(await fs.readFile(file)).digest("hex"); const temporary = await fs.mkdtemp(path.join(os.tmpdir(), "m13-04g-check-")); let job; try { job = await createServerJobDirectory(temporary, "server:check-cancel"); const childScript = "const {spawn}=require('node:child_process'); spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{stdio:'ignore'}); setInterval(()=>{},1000);"; const handle = startServerJobProcess(process.execPath, ["-e", childScript], { cwd: root }); let cleanupCount = 0; const receipt = await cancelServerJobProcess(handle, async () => { cleanupCount += 1; await cleanupServerJobDirectory(job); }); assert.equal(receipt.state, "CANCELLED"); assert.equal(receipt.cleanupCount, 1); assert.equal(cleanupCount, 1); assert.equal(receipt.orphanCount, 0); assert.match(receipt.treeSignal, /GROUP|ALREADY_EXITED/); await assert.rejects(fs.stat(job.path), { code: "ENOENT" }); const report = { schemaVersion: 1, task: "M13-04G", operation: "SERVER_JOB_PROCESS_TREE_CANCELLATION", runtime: "NODE_REAL_PROCESS_GROUP", state: receipt.state, treeSignal: receipt.treeSignal, cleanupCount: receipt.cleanupCount, orphanCount: receipt.orphanCount, residualDirectory: false, repeatedCancelIdempotent: true, execution: "DISABLED", nextTask: "M13-04H" }; if (process.env.UPDATE_M13_04G_REPORT === "1") { await fs.mkdir(path.dirname(reportPath), { recursive: true }); await fs.writeFile(reportPath, `${JSON.stringify(report, null, 2)}\n`); } assert.deepEqual(JSON.parse(await fs.readFile(reportPath, "utf8")), report); const manifest = JSON.parse(await fs.readFile(manifestPath, "utf8")); assert.deepEqual({ schemaVersion: manifest.schemaVersion, task: manifest.task, parentTask: manifest.parentTask, nextTask: manifest.nextTask }, { schemaVersion: 1, task: "M13-04G", parentTask: "M13-04F", nextTask: "M13-04H" }); for (const artifact of Object.values(manifest.artifacts)) assert.equal(await hashFile(path.join(root, artifact.path)), artifact.sha256, `artifact hash mismatch ${artifact.path}`); process.stdout.write(`server-job-cancel-ok state=CANCELLED tree=${receipt.treeSignal} cleanup=1 orphan=0 residual=0 execution=DISABLED next=${manifest.nextTask}\n`); } finally { await fs.rm(temporary, { recursive: true, force: true }); }