Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion graphify-out/graph.json

Large diffs are not rendered by default.

13 changes: 9 additions & 4 deletions lib/hosts/update-fixture.test-helper.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,12 @@ export function nodeBinary() {
throw new Error("node is required on PATH for the host update tests");
}

function hostScript(kind) {
function hostScript(kind, pidFile) {
// The detached daemon the worker launches is only known by pid once it writes health.json: record it from its first line.
const record = pidFile ? `require("node:fs").appendFileSync(${JSON.stringify(pidFile)},process.pid+"\\n");\n` : "";
return record + hostBody(kind);
}
function hostBody(kind) {
if (kind === "exit") return "process.exit(4);\n";
if (kind === "wrong-version") {
// A daemon that acknowledges a version other than the one being installed.
Expand All @@ -54,15 +59,15 @@ require(${JSON.stringify(jitiPath)}).createJiti(__filename).import(path.join(__d
}

/** `kind`: "ack" (production health acknowledgement), "exit" (dies at launch), "wrong-version" (acknowledges 0.0.1),
* "forged-ack" (another live process acknowledges for it, then it dies). */
export function writeRelease(dir, version, kind = "ack", { binary = false } = {}) {
* "forged-ack" (another live process acknowledges for it, then it dies). `pidFile`: each launched host appends its pid to it. */
export function writeRelease(dir, version, kind = "ack", { binary = false, pidFile } = {}) {
mkdirSync(join(dir, "bin"), { recursive: true });
for (const file of RELEASE_MODULES) {
mkdirSync(dirname(join(dir, file)), { recursive: true });
cpSync(join(repo, file), join(dir, file));
}
writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "@kahme247/ompweb", version }));
writeFileSync(join(dir, "bin", "omp-web-host.js"), hostScript(kind));
writeFileSync(join(dir, "bin", "omp-web-host.js"), hostScript(kind, pidFile));
writeFileSync(join(dir, "bin", "idle-web.js"), "setInterval(()=>{},1000);\n");
if (!binary) return;
// The compiled release: an executable that answers --version and otherwise runs this release's host.
Expand Down
36 changes: 20 additions & 16 deletions lib/hosts/update-worker.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ const stateRoot = join(base, "agent", "omp-web", "host-update");
const windows = process.platform === "win32";
const posixOnly = windows ? "The disposable binary release is a POSIX shell script; archive, digest and state validation still run on Windows" : false;
let worker;
const healthFiles = [];
const hostPids = join(base, "host-pids"); // every fake host the worker launches appends its own pid here, health.json or not
const pidFiles = [hostPids]; // plus the web a fake manager starts
const children = [];

before(async () => {
Expand All @@ -26,16 +27,18 @@ before(async () => {
worker = await import("./update-worker.ts");
});
after(async () => {
for (const child of children) { try { child.kill(); } catch {} }
const relaunched = healthFiles.flatMap((file) => { try { return [JSON.parse(readFileSync(file)).pid]; } catch { return []; } });
for (const pid of relaunched) { try { process.kill(pid, "SIGTERM"); } catch {} }
// A relaunched host runs with its cwd inside `base`; Windows keeps that directory locked (EBUSY) until the
// process has exited, and a kill returns before it has.
const pids = [...children.map((child) => child.pid), ...relaunched];
for (let i = 0; i < 100 && pids.some(alive); i++) await wait(50);
// Everything that may still hold `base` (its cwd or an open file): the stand-ins, every launched host and the fake manager's web.
const pids = new Set(children.filter((child) => child.exitCode === null && child.signalCode === null).map((child) => child.pid));
for (const file of pidFiles) { try { for (const pid of readFileSync(file, "utf8").split("\n")) pids.add(Number(pid)); } catch {} }
const running = [...pids].filter((pid) => Number.isSafeInteger(pid) && pid > 1 && pid !== process.pid && alive(pid));
for (const pid of running) { try { process.kill(pid, "SIGTERM"); } catch {} }
// A kill is asynchronous and on Windows the process keeps its cwd and handles until it is gone: wait, or rmSync hits EBUSY.
for (const stop = Date.now() + 10000; running.some(alive) && Date.now() < stop;) await wait(50);
process.env = saved;
// A handle a process releases just after its exit (antivirus, the search indexer) still gets retried.
rmSync(base, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });
// Bun ignores maxRetries/retryDelay (EBUSY comes back at once), so retry here as well.
for (let tries = 0; ; tries++) {
try { return rmSync(base, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 }); } catch (error) { if (tries === 50) throw error; await wait(100); }
}
});

const read = (path) => JSON.parse(readFileSync(path, "utf8"));
Expand All @@ -49,26 +52,27 @@ async function fixture(id, { candidate = "ack", method = "npm", from = "1.0.0",
mkdirSync(stateRoot, { recursive: true, mode: 0o700 });
const attempt = join(stateRoot, id);
mkdirSync(attempt, { mode: 0o700 });
healthFiles.push(join(attempt, "health.json"));
const work = join(base, id);
const webPidFile = join(work, "web.pid");
pidFiles.push(webPidFile);
const install = binary ? join(work, "renamed-release") : join(work, "node_modules", "@kahme247", "ompweb");
writeRelease(install, restartOnly ? to : from, "ack", { binary });
writeRelease(install, restartOnly ? to : from, "ack", { binary, pidFile: hostPids });
for (let dir = install; dir !== base; dir = dirname(dir)) chmodSync(dir, 0o755);
const release = join(work, "candidate");
writeRelease(release, to, candidate, { binary });
const manager = binary ? undefined : writeManager(work, { method, version: to, releaseDir: release, dependenciesDir: join(work, "candidate-modules"), webDuringInstall: webDuringInstall && { script: join(install, "bin", "idle-web.js"), pidFile: join(work, "web.pid") } });
writeRelease(release, to, candidate, { binary, pidFile: hostPids });
const manager = binary ? undefined : writeManager(work, { method, version: to, releaseDir: release, dependenciesDir: join(work, "candidate-modules"), webDuringInstall: webDuringInstall && { script: join(install, "bin", "idle-web.js"), pidFile: webPidFile } });
const daemon = spawn(nodeBinary(), ["-e", "setInterval(()=>{},1000)"], { stdio: "ignore" });
children.push(daemon);
const operation = { id, target: "ompweb", version: to, state: "running" };
writeFileSync(join(stateRoot, "status.json"), JSON.stringify({ operation, daemonPid: daemon.pid, workerPid: process.pid, startedAt: Date.now() }), { mode: 0o600 });
const descriptor = {
id, target: "ompweb", version: to, fromVersion: from, installMethod: binary ? "binary" : method, installDir: install, runtime: nodeBinary(),
hostArgs: ["--allow-http"], cwd: work, daemonPid: daemon.pid, daemonIdentity: identity ?? await worker.processStartIdentity(daemon.pid),
hostArgs: ["--allow-http"], cwd: tmpdir(), daemonPid: daemon.pid, daemonIdentity: identity ?? await worker.processStartIdentity(daemon.pid), // the daemons run in cwd: not inside `base`, which a live process blocks removing
managerPath: manager, restartOnly: restartOnly || undefined, systemd: null,
};
const descriptorPath = join(attempt, "descriptor.json");
writeFileSync(descriptorPath, JSON.stringify(descriptor), { mode: 0o600 });
return { descriptorPath, install, daemon, attempt, work, backup: join(dirname(install), `.ompweb-backup-${id}`), failed: join(dirname(install), `.ompweb-failed-${id}`), webPidFile: join(work, "web.pid") };
return { descriptorPath, install, daemon, attempt, work, backup: join(dirname(install), `.ompweb-backup-${id}`), failed: join(dirname(install), `.ompweb-failed-${id}`), webPidFile };
}
const outcome = (f) => `${JSON.stringify(status().operation)} ${f.descriptorPath}`;
async function idleWebOn(install) {
Expand Down
Loading