diff --git a/CHANGELOG.md b/CHANGELOG.md index 940751e11..ce2699fb8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Fixes & Improvements +- **The OMP update check gets the time a cold start needs, and a wedged one leaves nothing behind.** The check now waits up to 30 seconds instead of 15, which a first `omp update --check` after boot regularly exceeded on Windows, so it no longer reports `update_failed` for a check that was merely slow. When the deadline does expire, the launcher and every process it started are terminated together through the absolute `System32\taskkill.exe` path, so a PATH without System32 cannot leave the check running; on POSIX the direct child is killed. - **Windows host updates allow more time for safety checks.** The process inventory gets up to 20 seconds to start and finish on a busy machine, instead of five. Shared installations and failed or unreadable inventories still block the update before the daemon is stopped. - **Copied uploads start retention at the send time on Windows too.** When a hard link cannot be used or its timestamp cannot be changed, the host writes a fresh exclusive copy instead of inheriting an old staging timestamp. Failed copies remain retryable without replacing unrelated files. - **Newly sent uploads survive an overlapping retention sweep.** The host refreshes the staged file's timestamp before making its hard link visible, for attachments and Files-panel uploads alike, so cleanup cannot mistake a just-sent file for an expired one. A Files-panel overwrite of an expired file can no longer be deleted by a sweep that inspected the file it replaced. diff --git a/lib/hosts/update-fixture.test-helper.mjs b/lib/hosts/update-fixture.test-helper.mjs index b3beed4d2..7a8b4dd63 100644 --- a/lib/hosts/update-fixture.test-helper.mjs +++ b/lib/hosts/update-fixture.test-helper.mjs @@ -20,6 +20,10 @@ const RELEASE_MODULES = [ "lib/project-command-env.ts", "lib/omp/updates.ts", "lib/omp/omp-cli.ts", + // lib/omp/updates.ts imports the absolute taskkill resolver from here, so a + // release without these two modules cannot load its own update path. + "lib/windows-service.ts", + "lib/omp/paths.ts", ]; export function nodeBinary() { diff --git a/lib/omp/updates.test.mjs b/lib/omp/updates.test.mjs index 3a2c3b184..c27b779fb 100644 --- a/lib/omp/updates.test.mjs +++ b/lib/omp/updates.test.mjs @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import test from "node:test"; @@ -191,3 +191,166 @@ test("real .cmd launcher through the real update path returns its stdout", { ski assert.equal(status.currentVersion, "18.2.7"); assert.equal(status.updateAvailable, false); }); + +// The deadline itself, exercised at the subprocess boundary: a real launcher +// that answers after the old 15 s bound must succeed, and one that outlives the +// new 30 s bound must be terminated. `scaleOmpUpdateCheckTimeoutForTests` runs +// both against the real default deadline in a fraction of the wall time, so +// these assertions fail if the default drops back to 15 s or grows past 30 s. +// 1/10, not 1/20: cmd.exe + a cold node boot alone can take ~600 ms on Windows, +// which a 500 ms gap between the delay and the deadline would not absorb. +const CHECK_SCALE = 1 / 10; // 30 s → 3 s, the old 15 s → 1.5 s +const NEW_DEADLINE_MS = 30_000 * CHECK_SCALE; +const OLD_DEADLINE_MS = 15_000 * CHECK_SCALE; + +/** + * A launcher that waits `delayMs` and then answers like `omp update --check`. + * + * It records its own pid before waiting, so a test can prove the process is + * really gone after the deadline instead of only that the promise rejected. + */ +function writeSlowLauncher(t, delayMs) { + const dir = mkdtempSync(join(tmpdir(), "omp-update-slow-")); + const script = join(dir, "slow-omp.cjs"); + const pidFile = join(dir, "slow-omp.pid"); + writeFileSync(script, [ + `require("node:fs").writeFileSync(${JSON.stringify(pidFile)}, String(process.pid));`, + `setTimeout(() => {`, + ` process.stdout.write("Current version: 18.2.7\\nOMP is up to date\\n");`, + `}, ${delayMs});`, + "", + ].join("\n")); + const bin = join(dir, "slow-omp"); + if (process.platform === "win32") { + writeFileSync(`${bin}.cmd`, `@"${process.execPath.replaceAll("%", "%%")}" "${script.replaceAll("%", "%%")}" %*\r\n`); + withOmpBin(t, `${bin}.cmd`); + } else { + writeFileSync(bin, `#!${process.execPath}\n${readFileSync(script, "utf8")}`, { mode: 0o755 }); + withOmpBin(t, bin); + } + return { bin, pidFile }; +} + +/** Wait until the launcher has written its pid, or give up after `timeoutMs`. */ +async function readLauncherPid(pidFile, timeoutMs = 5000) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + try { + const pid = Number(readFileSync(pidFile, "utf8")); + if (Number.isInteger(pid) && pid > 0) return pid; + } catch { + // Not written yet. + } + await new Promise((resolve) => setTimeout(resolve, 25)); + } + throw new Error(`the launcher never wrote its pid to ${pidFile}`); +} + +/** True while `pid` names a live process. */ +function isProcessAlive(pid) { + try { + process.kill(pid, 0); + return true; + } catch (error) { + // EPERM means it exists but belongs to someone else; anything else is gone. + return error?.code === "EPERM"; + } +} + +test("a cold check that answers after the old 15 s deadline still succeeds", { timeout: 20000 }, async (t) => { + writeSlowLauncher(t, OLD_DEADLINE_MS + 250); + const { runOmpUpdate, parseOmpUpdateStatus, scaleOmpUpdateCheckTimeoutForTests } = await import(`./updates.ts?fresh=${freshImport++}`); + scaleOmpUpdateCheckTimeoutForTests(CHECK_SCALE); + t.after(() => scaleOmpUpdateCheckTimeoutForTests(1)); + const started = Date.now(); + const output = await runOmpUpdate(["--check"]); + const elapsed = Date.now() - started; + assert.ok(elapsed > OLD_DEADLINE_MS, `the launcher answered after the old bound (${elapsed} ms)`); + assert.equal(parseOmpUpdateStatus(output).currentVersion, "18.2.7"); +}); + +test("a check that outlives the 30 s deadline is terminated, not left running", { timeout: 20000 }, async (t) => { + // The launcher must outlive the assertion window by a wide margin: if it + // exited on its own, "gone" would prove nothing about the tree kill. + const { pidFile } = writeSlowLauncher(t, 60_000); + const { runOmpUpdate, scaleOmpUpdateCheckTimeoutForTests } = await import(`./updates.ts?fresh=${freshImport++}`); + scaleOmpUpdateCheckTimeoutForTests(CHECK_SCALE); + t.after(() => scaleOmpUpdateCheckTimeoutForTests(1)); + const started = Date.now(); + const pending = runOmpUpdate(["--check"]); + // The launcher is a real process behind cmd.exe on Windows: record its pid + // so the assertion is about that process, not about the promise. + const pid = await readLauncherPid(pidFile); + assert.ok(isProcessAlive(pid), "the launcher must be running before the deadline"); + await assert.rejects(pending, /Command failed/); + const elapsed = Date.now() - started; + assert.ok(elapsed >= NEW_DEADLINE_MS, `it waited for the new deadline (${elapsed} ms)`); + assert.ok(elapsed < NEW_DEADLINE_MS + 1000, `it stopped the launcher instead of waiting it out (${elapsed} ms)`); + // The claim in the title: the slow child is not left running. Node's own + // `timeout` only kills cmd.exe, so this fails without the tree kill. + const gone = await waitUntilGone(pid); + assert.ok(gone, `the launcher (pid ${pid}) must exit when the check times out`); +}); + +// The reaper must not depend on PATH: an omp session's sanitized environment or +// a user PATH without System32 would make a bare `taskkill` unresolvable exactly +// when a wedged check needs reaping. The deadline path is driven here with a +// fake clock, so the assertion is about the executable the reaper spawns. Runs +// on every platform: `withPlatform` simulates win32, and the SystemRoot below is +// a real directory holding a real (empty) taskkill.exe, so `resolveTaskkillBin` +// takes its absolute-path branch on Linux CI as well — no fs mock, and no +// assertion that only holds where C:\Windows happens to exist. +test("the timeout tree kill reaps through the absolute System32 taskkill path", { timeout: 20000 }, async (t) => { + withPlatform(t, "win32"); + const dir = mkdtempSync(join(tmpdir(), "omp-update-reaper-")); + // A SystemRoot that exists on this host, whatever the platform: the resolver + // only needs System32/taskkill.exe to be there. + const sysRoot = join(dir, "fake-sysroot"); + mkdirSync(join(sysRoot, "System32"), { recursive: true }); + writeFileSync(join(sysRoot, "System32", "taskkill.exe"), ""); + const previousSysRoot = process.env.SystemRoot; + process.env.SystemRoot = sysRoot; + t.after(() => { + if (previousSysRoot === undefined) delete process.env.SystemRoot; + else process.env.SystemRoot = previousSysRoot; + }); + const bin = join(dir, "fake-omp.cmd"); + writeFileSync(bin, "stub\n"); + withOmpBin(t, bin); + const spawned = []; + let settleExec; + const execFile = (file, args, options, callback) => { + // Never answers on its own: the deadline is what ends this check. The + // reaper below settles it, the way a real kill makes execFile report. + settleExec = () => callback(new Error("killed"), "", ""); + return { pid: 4242, exitCode: null, signalCode: null, kill() {} }; + }; + const spawn = (command, args) => { + spawned.push({ command, args }); + setTimeout(() => settleExec?.(), 0); + return { once() {}, unref() {} }; + }; + await mockBuiltin(t, "node:child_process", { execFile, spawn }); + const { runOmpUpdate } = await import(`./updates.ts?fresh=${freshImport++}`); + // A 0 ms deadline fires on the next timers phase; the check never answers. + await assert.rejects(runOmpUpdate(["--check"], 0), /timed out/); + const reaper = spawned.find((entry) => entry.args.includes("/t")); + assert.ok(reaper, "the deadline spawned a tree reaper"); + assert.equal(reaper.command, join(sysRoot, "System32", "taskkill.exe"), "the reaper is addressed absolutely, not through PATH"); + assert.deepEqual(reaper.args, ["/pid", "4242", "/t", "/f"]); +}); + +/** Poll for `pid` to disappear; the tree kill is asynchronous on Windows. */ +async function waitUntilGone(pid, timeoutMs = 5000) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (!isProcessAlive(pid)) return true; + await new Promise((resolve) => setTimeout(resolve, 25)); + } + try { + process.kill(pid, "SIGKILL"); + } catch { + // Already gone. + } + return false; +} diff --git a/lib/omp/updates.ts b/lib/omp/updates.ts index 992082a2f..3c46fe3e7 100644 --- a/lib/omp/updates.ts +++ b/lib/omp/updates.ts @@ -1,7 +1,8 @@ -import { execFile } from "child_process"; +import { execFile, spawn } from "child_process"; import { resolveOmpBin, wrapWindowsScript } from "./omp-cli"; import { createChildProcessEnvironment } from "../project-command-env"; import { isUpdateDisabled } from "../update-policy"; +import { resolveTaskkillBin } from "../windows-service"; export interface OmpUpdateStatus { currentVersion: string | null; @@ -11,28 +12,114 @@ export interface OmpUpdateStatus { updatesDisabled?: boolean; } -export const OMP_UPDATE_CHECK_TIMEOUT_MS = 15_000; +// A cold `omp update --check` on Windows regularly needs ~20 s (Node CLI startup +// plus network); 15 s made the very first check after boot fail with update_failed. +export const OMP_UPDATE_CHECK_TIMEOUT_MS = 30_000; export const OMP_UPDATE_CHECK_TTL_MS = 60 * 60 * 1000; +// Scales the check deadline so a test can run the real subprocess boundary: a +// launcher that answers past the old 15 s bound and one that outlives the new +// 30 s bound, both in a fraction of the real time. Production never sets it. +let checkTimeoutScale = 1; + +/** Test-only: scale the default check deadline (1 restores the real one). */ +export function scaleOmpUpdateCheckTimeoutForTests(scale: number): void { + checkTimeoutScale = scale; +} + /** Run a raw `omp update [args]` subcommand. Install durability * (lease/status/retry) lives in lib/self-update.ts. */ export function runOmpUpdate(args: string[], timeoutMs = OMP_UPDATE_CHECK_TIMEOUT_MS): Promise { const bin = resolveOmpBin(); if (!bin) return Promise.reject(new Error("omp binary not found. Install oh-my-pi or set OMP_WEB_OMP_BIN.")); + // The test-only scale is applied here, not in the default parameter: a + // default expression is evaluated per call, but keeping production's + // deadline out of the test hook's reach makes the hook's scope obvious. + const deadlineMs = timeoutMs * checkTimeoutScale; const { promise, resolve, reject } = Promise.withResolvers(); const target = wrapWindowsScript(bin, ["update", ...args]); - execFile(target.file, target.args, { - timeout: timeoutMs, + // The deadline is handled here rather than by `execFile`'s `timeout`: that + // option kills the direct child only, and on Windows the direct child is + // cmd.exe — the launcher it started keeps running. By the time the callback + // fires the parent is gone, so `taskkill /t` can no longer find the tree. + // Killing the tree while the parent is still alive is the only reliable way + // to leave no process behind. + let timedOut = false; + const child = execFile(target.file, target.args, { maxBuffer: 1024 * 1024, env: createChildProcessEnvironment({ FORCE_COLOR: "0", NO_COLOR: "1" }), windowsHide: true, }, (error, stdout, stderr) => { - if (error) reject(new Error((stderr || stdout || error.message).trim().slice(-1000))); - else resolve(`${stdout}\n${stderr}`.trim()); + clearTimeout(deadline); + if (error) { + if (timedOut) { + reject(new Error(`Command failed: ${target.file} ${target.args.join(" ")} (timed out after ${deadlineMs} ms)`)); + return; + } + reject(new Error((stderr || stdout || error.message).trim().slice(-1000))); + } else resolve(`${stdout}\n${stderr}`.trim()); }); + // Not unref'd: a running check is real work, and the timer must not be + // dropped just because nothing else holds the loop open. + const deadline = setTimeout(() => { + timedOut = true; + // Kill the tree while the parent is still alive: `taskkill /t` walks the + // parent's children, so it cannot work afterwards. + killProcessTree(child.pid); + // A launcher that ignores the kill still must not keep the check pending. + setTimeout(() => { + if (child.exitCode === null && child.signalCode === null) { + try { + child.kill("SIGKILL"); + } catch { + // Already gone. + } + } + }, 1000).unref(); + }, deadlineMs); return promise; } +/** + * Terminate a child and everything it started. + * + * Windows has no portable negative-pid equivalent, so `taskkill /t /f` walks + * the tree. It must run while the parent is still alive — once the parent has + * exited, its children are no longer reachable through it. POSIX uses the + * direct kill: this child is not detached, so it heads no process group of its + * own, and the launcher is the process that holds the deadline. + */ +function killProcessTree(pid: number | undefined): void { + if (!pid) return; + if (process.platform !== "win32") { + try { + process.kill(pid, "SIGKILL"); + } catch { + // Already gone. + } + return; + } + try { + // Absolute path: a bare `taskkill` resolves through PATH, which an omp + // session's sanitized environment or a user PATH without System32 can + // break — exactly when a wedged check needs reaping. + const reaper = spawn(resolveTaskkillBin(), ["/pid", String(pid), "/t", "/f"], { windowsHide: true, stdio: "ignore" }); + reaper.once("error", () => { + try { + process.kill(pid, "SIGKILL"); + } catch { + // Already gone. + } + }); + } catch { + try { + process.kill(pid, "SIGKILL"); + } catch { + // Already gone. + } + } +} + export function parseOmpUpdateStatus(output: string): OmpUpdateStatus { const currentVersion = output.match(/^Current version:\s*(\S+)/mi)?.[1] ?? null; const availableVersion = output.match(/^New version available:\s*(\S+)/mi)?.[1] ?? null;