fix(updater): recover interrupted swaps reliably across deployments

- Ship one POSIX launcher that repairs an interrupted code swap before Node
  starts, install it atomically before the swap, and keep it out of
  CODE_ENTRIES so it always survives at the install root.
- Restore from the in-progress task backup (state.json task.id ->
  backups/<id>) first, then the newest complete backup, so a leftover older
  backup never resurrects an obsolete build.
- Add exact-window SIGKILL recovery tests, including the stale-backup case.
- Gate Linux arm64 apply behind a capability check; add five-language copy
  and i18n labels for arm64, lock and unavailable errors.
- Harden the L2 runner handshake and recheck runner health before exit.
This commit is contained in:
OddTurtleHead committed 2026-11-24 03:13:32 +08:00
1 parent 699e606da5
commit 82b58dbd61
16 files changed
+699 -24

No files matched your search

+9
View File
@@ -73,6 +73,15 @@ async function main() {
updateService,
restartAfterUpdate: () => {
void (async () => {
if (!updateService.runnerStillHealthy()) {
// 202 already promised a restart, but the helper died before this
// process left. Stay up and reconcile instead of reporting success
// and silently abandoning the update.
logger.warn("The restart runner is no longer healthy; keeping this process and reconciling the update state");
try { updateService.initialize(); }
catch (error) { logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Update state could not be reconciled"); }
return;
}
logger.info("Stopping for scheduled update");
try { await webServer?.stop(); }
catch (error) { logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Web server did not stop cleanly for update"); }
+25 -1
View File
@@ -17,7 +17,10 @@ export const CODE_ENTRIES = [
"README.md",
"LICENSE",
"config.example.json",
"start-webspeak.sh",
// start-webspeak.sh is deliberately absent: the launcher must stay at the
// install root for the whole swap so an interrupted update can still be
// recovered by running ./start-webspeak.sh. It is installed atomically by
// the updater before the runner swaps any code.
"start-webspeak.cmd",
] as const;
@@ -114,6 +117,26 @@ export function setCodeSwapCopyForTests(copy: CopyEntry | null): void {
copyEntry = copy ?? defaultCopyEntry;
}
/**
* Test-only fault-injection seam. When the named directory exists, the swap
* pauses in the exact window between "old code moved aside" and "new code
* moved in" so a test can SIGKILL the runner. Production never sets this
* variable; it is a local barrier directory, not a URL or network switch.
*/
const SWAP_BARRIER_ENV = "WEBSPEAK_TEST_SWAP_BARRIER_DIR";
function swapWindowBarrier(): void {
const directory = process.env[SWAP_BARRIER_ENV];
if (!directory || !existsSync(directory)) return;
writeFileSync(path.join(directory, "swap-window-reached"), String(process.pid));
const resume = path.join(directory, "resume");
const deadline = Date.now() + 30_000;
const waiter = new Int32Array(new SharedArrayBuffer(4));
while (!existsSync(resume) && Date.now() < deadline) {
Atomics.wait(waiter, 0, 0, 20);
}
}
function moveIfPresent(from: string, to: string): void {
if (!existsSync(from)) return;
mkdirSync(path.dirname(to), { recursive: true });
@@ -183,6 +206,7 @@ export function swapCode(rootDir: string, stagedRoot: string, backupDir: string)
movedToBackup.push(entry);
writeSwapManifest(backupDir, movedToBackup);
}
swapWindowBarrier();
for (const entry of CODE_ENTRIES) {
if (!existsSync(path.join(stagedRoot, entry))) continue;
moveIfPresent(path.join(stagedRoot, entry), path.join(rootDir, entry));
+16 -1
View File
@@ -77,7 +77,8 @@ test("a complete packaged tree is detected as a release package", t => {
const info = detectDeployment({ rootDir: root, env: {}, isDocker: false, platform: "linux", architecture: "arm64" });
assert.equal(info.mode, "release-package");
assert.equal(info.assetKind, "linux-arm64");
assert.equal(info.applyAllowed, true);
assert.equal(info.applyAllowed, false);
assert.equal(info.reasonCode, "LINUX_ARM64_APPLY_UNVERIFIED");
assert.equal(detectDeployment({ rootDir: root, env: { WEBSPEAK_DEPLOYMENT_MODE: "docker" }, isDocker: false, platform: "linux" }).mode, "docker");
});
@@ -129,6 +130,20 @@ test("windows release packages are visible but apply stays disabled", t => {
assert.equal(linux.reasonCode, null);
});
test("linux arm64 release packages are checkable but apply is gated off", t => {
const root = releasePackageRoot(t);
const arm64 = detectDeployment({ rootDir: root, env: {}, isDocker: false, platform: "linux", architecture: "arm64" });
assert.equal(arm64.mode, "release-package");
assert.equal(arm64.assetKind, "linux-arm64");
assert.equal(arm64.applyAllowed, false);
assert.equal(arm64.reasonCode, "LINUX_ARM64_APPLY_UNVERIFIED");
assert.equal(arm64.upgradePath, "release-package");
const x64 = detectDeployment({ rootDir: root, env: {}, isDocker: false, platform: "linux", architecture: "x64" });
assert.equal(x64.applyAllowed, true);
assert.equal(x64.reasonCode, null);
});
test("unsupported platforms are visible but cannot apply", t => {
const root = releasePackageRoot(t);
const info = detectDeployment({ rootDir: root, env: {}, isDocker: false, platform: "linux", architecture: "s390x" });
+6
View File
@@ -45,6 +45,12 @@ export function detectDeployment(options: DeploymentDetectionOptions): Deploymen
// real Windows release package. Report versions, but never fake an apply.
applyAllowed = false;
reasonCode = "WINDOWS_APPLY_UNVERIFIED";
} else if (platform === "linux" && architecture === "arm64") {
// arm64 packages are built and can be checked, but the in-place swap has
// only been exercised on x64. Gate on the detected capability itself so
// "unverified" is never rendered as "can apply" in the UI.
applyAllowed = false;
reasonCode = "LINUX_ARM64_APPLY_UNVERIFIED";
}
return {
mode,
+328
View File
@@ -0,0 +1,328 @@
import assert from "node:assert/strict";
import { spawn, type ChildProcess } from "node:child_process";
import { createServer } from "node:net";
import test, { type TestContext } from "node:test";
import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { UpdateService } from "./update-service.js";
const SOURCE_DIR = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(SOURCE_DIR, "..", "..");
const LAUNCHER_SOURCE = path.join(REPO_ROOT, "scripts", "start-webspeak.sh");
const RUNNER_SOURCE = path.join(SOURCE_DIR, "restart-runner.ts");
const TASK_ID = "upd_sigkill_window";
const logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } };
const sleep = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
async function availablePort(): Promise<number> {
const server = createServer();
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
assert.ok(address && typeof address !== "string");
await new Promise<void>((resolve) => server.close(() => resolve()));
return address.port;
}
async function waitFor(check: () => boolean | Promise<boolean>, message: string, timeoutMs = 15_000): Promise<void> {
const deadline = Date.now() + timeoutMs;
while (!(await check())) {
if (Date.now() > deadline) throw new Error(message);
await sleep(25);
}
}
async function healthVersion(port: number): Promise<string | null> {
try {
const response = await fetch(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(1_000) });
if (!response.ok) return null;
const body = await response.json() as { status?: string; version?: string };
return body.status === "ok" ? body.version ?? null : null;
} catch {
return null;
}
}
function processAlive(pid: number | undefined): boolean {
if (!pid || pid <= 0) return false;
try { process.kill(pid, 0); return true; }
catch (error) { return (error as NodeJS.ErrnoException).code === "EPERM"; }
}
function stop(child: ChildProcess | undefined): void {
if (!child || !processAlive(child.pid)) return;
try { child.kill("SIGKILL"); } catch { /* Already gone. */ }
}
/** The stub reports the version from package.json, as the real app does. */
function appScript(): string {
return `const http = require("node:http");
const fs = require("node:fs");
const path = require("node:path");
const config = JSON.parse(fs.readFileSync(path.join(process.cwd(), "config.json"), "utf8"));
const version = JSON.parse(fs.readFileSync(path.join(process.cwd(), "package.json"), "utf8")).version;
http.createServer((request, response) => {
if (request.url === "/api/health") {
response.setHeader("content-type", "application/json");
response.end(JSON.stringify({ status: "ok", version }));
return;
}
response.statusCode = 404;
response.end();
}).listen(config.port, "127.0.0.1", () => fs.writeFileSync(config.startedFile, version));
`;
}
interface Fixture {
directory: string;
rootDir: string;
dataDir: string;
stagedRoot: string;
backupDir: string;
barrierDir: string;
port: number;
markerFiles: Record<string, string>;
}
function buildFixture(t: TestContext, port: number, withStaleBackup = false): Fixture {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-swap-recovery-"));
t.after(() => rmSync(directory, { recursive: true, force: true }));
const rootDir = path.join(directory, "app");
const dataDir = path.join(rootDir, "data");
const updatesDir = path.join(dataDir, "updates");
const stagedRoot = path.join(updatesDir, "tasks", TASK_ID, "staged");
const backupDir = path.join(updatesDir, "backups", TASK_ID);
const barrierDir = path.join(directory, "barrier");
for (const relative of ["dist", "web/dist", "node_modules", "runtime"]) {
mkdirSync(path.join(rootDir, relative), { recursive: true });
}
writeFileSync(path.join(rootDir, "package.json"), JSON.stringify({ name: "webspeak-webclient", version: "0.3.2" }));
writeFileSync(path.join(rootDir, "package-lock.json"), "{}");
writeFileSync(path.join(rootDir, "README.md"), "old readme");
writeFileSync(path.join(rootDir, "LICENSE"), "old license");
writeFileSync(path.join(rootDir, "config.example.json"), "{}");
writeFileSync(path.join(rootDir, "web", "dist", "index.html"), "<!doctype html>\n");
writeFileSync(path.join(rootDir, "node_modules", ".keep"), "");
writeFileSync(path.join(rootDir, "dist", "index.js"), appScript());
copyFileSync(process.execPath, path.join(rootDir, "runtime", "node"));
chmodSync(path.join(rootDir, "runtime", "node"), 0o755);
// This is the same file CI ships and applyUpdate installs before the swap.
copyFileSync(LAUNCHER_SOURCE, path.join(rootDir, "start-webspeak.sh"));
chmodSync(path.join(rootDir, "start-webspeak.sh"), 0o755);
const markerFiles: Record<string, string> = {
config: path.join(rootDir, "config.json"),
database: path.join(dataDir, "webspeak.db"),
identity: path.join(dataDir, "identity.key"),
cert: path.join(rootDir, "certs", "cert.pem"),
skin: path.join(dataDir, "skins", "skin.json"),
plugin: path.join(dataDir, "plugins", "plugin.json"),
};
mkdirSync(path.dirname(markerFiles.database), { recursive: true });
mkdirSync(path.dirname(markerFiles.identity), { recursive: true });
mkdirSync(path.dirname(markerFiles.cert), { recursive: true });
mkdirSync(path.dirname(markerFiles.skin), { recursive: true });
mkdirSync(path.dirname(markerFiles.plugin), { recursive: true });
writeFileSync(markerFiles.config, JSON.stringify({ port, startedFile: path.join(directory, "started.txt") }));
for (const [key, value] of Object.entries(markerFiles)) {
if (key !== "config") writeFileSync(value, `${key} preserved`);
}
mkdirSync(updatesDir, { recursive: true });
mkdirSync(stagedRoot, { recursive: true });
mkdirSync(path.join(stagedRoot, "dist"), { recursive: true });
mkdirSync(path.join(stagedRoot, "web", "dist"), { recursive: true });
mkdirSync(path.join(stagedRoot, "node_modules"), { recursive: true });
mkdirSync(path.join(stagedRoot, "runtime"), { recursive: true });
writeFileSync(path.join(stagedRoot, "package.json"), JSON.stringify({ name: "webspeak-webclient", version: "0.4.0" }));
writeFileSync(path.join(stagedRoot, "package-lock.json"), "{}");
writeFileSync(path.join(stagedRoot, "README.md"), "new readme");
writeFileSync(path.join(stagedRoot, "LICENSE"), "new license");
writeFileSync(path.join(stagedRoot, "config.example.json"), "{}");
writeFileSync(path.join(stagedRoot, "dist", "index.js"), "// new code marker\n");
writeFileSync(path.join(stagedRoot, "web", "dist", "index.html"), "<!doctype html>\n");
writeFileSync(path.join(stagedRoot, "node_modules", ".keep"), "");
writeFileSync(path.join(stagedRoot, "runtime", "node"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
copyFileSync(LAUNCHER_SOURCE, path.join(stagedRoot, "start-webspeak.sh"));
writeFileSync(path.join(updatesDir, "state.json"), JSON.stringify({
schemaVersion: 1,
task: {
id: TASK_ID, status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
},
}));
writeFileSync(path.join(updatesDir, "update.lock"), JSON.stringify({ pid: 0, taskId: TASK_ID, createdAt: "2026-01-01T00:00:00.000Z" }));
writeFileSync(path.join(updatesDir, "plan.json"), JSON.stringify({
schemaVersion: 1,
taskId: TASK_ID,
rootDir,
statePath: path.join(updatesDir, "state.json"),
lockPath: path.join(updatesDir, "update.lock"),
stagedRoot,
backupDir,
fromVersion: "0.3.2",
targetVersion: "0.4.0",
nodePath: process.execPath,
appEntry: path.join(rootDir, "dist", "index.js"),
health: { protocol: "http", port, path: "/api/health" },
waitForPid: null,
parentTimeoutMs: 2_000,
healthTimeoutMs: 300,
pollIntervalMs: 50,
appLogPath: path.join(updatesDir, "app.log"),
}, null, 2));
if (withStaleBackup) {
// A complete backup from an earlier, already successful update. Its name
// sorts before the in-progress task's id, so the old "first complete
// backup wins" launcher logic would wrongly restore this older build.
const staleDir = path.join(updatesDir, "backups", "aaa_stale_backup");
for (const relative of ["dist", "web/dist", "node_modules", "runtime"]) {
mkdirSync(path.join(staleDir, relative), { recursive: true });
}
writeFileSync(path.join(staleDir, "dist", "index.js"), appScript());
writeFileSync(path.join(staleDir, "web", "dist", "index.html"), "<!doctype html>\n");
writeFileSync(path.join(staleDir, "node_modules", ".keep"), "");
writeFileSync(path.join(staleDir, "package.json"), JSON.stringify({ name: "webspeak-webclient", version: "0.1.0" }));
writeFileSync(path.join(staleDir, "package-lock.json"), "{}");
writeFileSync(path.join(staleDir, "README.md"), "stale readme");
writeFileSync(path.join(staleDir, "LICENSE"), "stale license");
writeFileSync(path.join(staleDir, "config.example.json"), "{}");
copyFileSync(process.execPath, path.join(staleDir, "runtime", "node"));
chmodSync(path.join(staleDir, "runtime", "node"), 0o755);
writeFileSync(path.join(staleDir, ".webspeak-swap.json"), JSON.stringify({
schemaVersion: 1,
entries: ["dist", "web/dist", "node_modules", "runtime", "package.json", "package-lock.json", "README.md", "LICENSE", "config.example.json"],
}, null, 2));
}
mkdirSync(barrierDir, { recursive: true });
return { directory, rootDir, dataDir, stagedRoot, backupDir, barrierDir, port, markerFiles };
}
test(
"SIGKILL in the exact swap window is recovered by the official launcher with data intact",
{ timeout: 40_000 },
async t => {
const port = await availablePort();
const fixture = buildFixture(t, port);
let runner: ChildProcess | undefined;
let app: ChildProcess | undefined;
t.after(() => { stop(app); stop(runner); });
let runnerOutput = "";
runner = spawn(process.execPath, ["--import", "tsx", RUNNER_SOURCE, path.join(fixture.dataDir, "updates", "plan.json")], {
cwd: REPO_ROOT,
env: { ...process.env, WEBSPEAK_TEST_SWAP_BARRIER_DIR: fixture.barrierDir },
stdio: ["ignore", "pipe", "pipe"],
});
runner.stdout?.on("data", (chunk: Buffer) => { runnerOutput += chunk.toString(); });
runner.stderr?.on("data", (chunk: Buffer) => { runnerOutput += chunk.toString(); });
await waitFor(
() => existsSync(path.join(fixture.barrierDir, "swap-window-reached")),
`runner never reached the exact swap window: ${runnerOutput}`,
);
// Precisely the failure state: old dist moved aside, new dist not yet in.
assert.equal(existsSync(path.join(fixture.rootDir, "dist", "index.js")), false);
assert.equal(existsSync(path.join(fixture.backupDir, "dist", "index.js")), true);
assert.equal(existsSync(path.join(fixture.rootDir, "start-webspeak.sh")), true, "official launcher survived the swap");
stop(runner);
await waitFor(() => !processAlive(runner?.pid), "runner did not die after SIGKILL", 5_000);
// Restart through the shipped launcher itself, not a harness wrapper.
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
cwd: fixture.rootDir,
env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir },
stdio: "ignore",
});
await waitFor(() => healthVersion(port).then(version => version === "0.3.2"), "official launcher did not restore a healthy install");
assert.equal(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), appScript());
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.3.2");
assert.deepEqual(JSON.parse(readFileSync(fixture.markerFiles.config, "utf8")), { port, startedFile: path.join(fixture.directory, "started.txt") });
for (const [key, file] of Object.entries(fixture.markerFiles)) {
if (key !== "config") assert.equal(readFileSync(file, "utf8"), `${key} preserved`, `${key} survived recovery`);
}
assert.equal(existsSync(path.join(fixture.backupDir, "rejected", "dist")), false, "no partial new code in the install root");
// Once Node is up, the existing initialize() path records the real failure.
stop(app);
await waitFor(() => !processAlive(app?.pid), "app did not stop", 5_000);
const service = new UpdateService({
rootDir: fixture.rootDir,
dataDir: fixture.dataDir,
currentVersion: "0.3.2",
logger,
platform: "linux",
architecture: "x64",
env: {},
isDocker: false,
});
service.initialize();
const status = service.getStatus();
assert.equal(status.task?.status, "failed");
assert.equal(status.task?.errorCode, "UPDATE_INTERRUPTED");
assert.equal(status.task?.rolledBack, true);
},
);
test(
"recovery prefers the in-progress task backup over an older lexicographically-first backup",
{ timeout: 40_000 },
async t => {
const port = await availablePort();
const fixture = buildFixture(t, port, true);
const staleDir = path.join(fixture.dataDir, "updates", "backups", "aaa_stale_backup");
let runner: ChildProcess | undefined;
let app: ChildProcess | undefined;
t.after(() => { stop(app); stop(runner); });
let runnerOutput = "";
runner = spawn(process.execPath, ["--import", "tsx", RUNNER_SOURCE, path.join(fixture.dataDir, "updates", "plan.json")], {
cwd: REPO_ROOT,
env: { ...process.env, WEBSPEAK_TEST_SWAP_BARRIER_DIR: fixture.barrierDir },
stdio: ["ignore", "pipe", "pipe"],
});
runner.stdout?.on("data", (chunk: Buffer) => { runnerOutput += chunk.toString(); });
runner.stderr?.on("data", (chunk: Buffer) => { runnerOutput += chunk.toString(); });
await waitFor(
() => existsSync(path.join(fixture.barrierDir, "swap-window-reached")),
`runner never reached the exact swap window: ${runnerOutput}`,
);
// Old code is only in the current task's backup; the stale backup is
// untouched and still sitting under a lexicographically earlier name.
assert.equal(existsSync(path.join(fixture.rootDir, "dist", "index.js")), false);
assert.equal(existsSync(path.join(fixture.backupDir, "dist", "index.js")), true);
assert.equal(existsSync(path.join(staleDir, "dist", "index.js")), true);
stop(runner);
await waitFor(() => !processAlive(runner?.pid), "runner did not die after SIGKILL", 5_000);
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
cwd: fixture.rootDir,
env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir },
stdio: "ignore",
});
await waitFor(() => healthVersion(port).then(version => version === "0.3.2"), "launcher did not restore the current task's 0.3.2 build");
// The current task's version, not the stale 0.1.0 build, is back in place.
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.3.2");
assert.equal(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), appScript());
assert.equal(JSON.parse(readFileSync(path.join(staleDir, "package.json"), "utf8")).version, "0.1.0", "stale backup was not consumed");
assert.equal(existsSync(path.join(staleDir, "dist", "index.js")), true, "stale backup is still intact");
assert.deepEqual(JSON.parse(readFileSync(fixture.markerFiles.config, "utf8")), { port, startedFile: path.join(fixture.directory, "started.txt") });
for (const [key, file] of Object.entries(fixture.markerFiles)) {
if (key !== "config") assert.equal(readFileSync(file, "utf8"), `${key} preserved`, `${key} survived recovery`);
}
},
);
+89
View File
@@ -573,3 +573,92 @@ test("the real restart runner starts with every runtime module and survives the
const log = readFileSync(path.join(updatesDir, "runner.log"), "utf8");
assert.ok(!log.includes("ERR_MODULE_NOT_FOUND"), `runner log has no missing module: ${log}`);
});
test("the runner handshake requires lock takeover and a later death is caught before exit", async t => {
const directory = workspace(t);
const compiled = path.join(directory, "compiled");
await compileRunnerSources(compiled);
const rootDir = path.join(directory, "app");
createPackageFiles(rootDir, "0.3.2");
const dataDir = path.join(directory, "data");
const updatesDir = path.join(dataDir, "updates");
mkdirSync(updatesDir, { recursive: true });
const taskId = "upd_handshake";
const statePath = path.join(updatesDir, "state.json");
const lockPath = path.join(updatesDir, "update.lock");
const planPath = path.join(updatesDir, "plan.json");
const makeTask = () => ({
id: taskId, status: "restarting" as const, fromVersion: "0.3.2", targetVersion: "0.4.0",
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
});
const writePlan = () => writeFileSync(planPath, JSON.stringify({
schemaVersion: 1, taskId, rootDir, statePath, lockPath,
stagedRoot: path.join(updatesDir, "staged"),
backupDir: path.join(updatesDir, "backups", taskId),
fromVersion: "0.3.2", targetVersion: "0.4.0", nodePath: process.execPath,
appEntry: path.join(rootDir, "dist", "index.js"),
health: { protocol: "http", port: 39998, path: "/api/health" },
waitForPid: process.pid, parentTimeoutMs: 60_000, healthTimeoutMs: 100, pollIntervalMs: 50,
appLogPath: path.join(updatesDir, "app.log"),
}, null, 2));
writeUpdateState(statePath, { schemaVersion: 1, task: makeTask() });
writeFileSync(lockPath, JSON.stringify({ pid: process.pid, taskId, createdAt: "2026-01-01T00:00:00.000Z" }));
writePlan();
const service = new UpdateService({
rootDir, dataDir, currentVersion: "0.3.2", logger, platform: "linux", architecture: "x64", env: {}, isDocker: false,
fetch: fakeFetch([], new Map()), runnerSourceDir: compiled, runnerStartupTimeoutMs: 1_500,
});
const pid = await service.launchRunner(planPath, path.join(updatesDir, "runner"));
t.after(() => stopProcess(pid));
assert.equal(service.runnerStillHealthy(), true, "runner owns the lock right after the handshake");
await stopProcess(pid);
assert.equal(service.runnerStillHealthy(), false, "a runner that died after 202 is caught before process.exit");
});
test("a runner that cannot take over the lock never passes the handshake", async t => {
const directory = workspace(t);
const compiled = path.join(directory, "compiled");
await compileRunnerSources(compiled);
const rootDir = path.join(directory, "app");
createPackageFiles(rootDir, "0.3.2");
const dataDir = path.join(directory, "data");
const updatesDir = path.join(dataDir, "updates");
mkdirSync(updatesDir, { recursive: true });
const taskId = "upd_bad_lock";
const statePath = path.join(updatesDir, "state.json");
const lockPath = path.join(updatesDir, "update.lock");
const planPath = path.join(updatesDir, "plan.json");
writeUpdateState(statePath, {
schemaVersion: 1,
task: {
id: taskId, status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
},
});
// A different task owns the lock: the runner must refuse to steal it.
writeFileSync(lockPath, JSON.stringify({ pid: process.pid, taskId: "upd_other", createdAt: "2026-01-01T00:00:00.000Z" }));
writeFileSync(planPath, JSON.stringify({
schemaVersion: 1, taskId, rootDir, statePath, lockPath,
stagedRoot: path.join(updatesDir, "staged"),
backupDir: path.join(updatesDir, "backups", taskId),
fromVersion: "0.3.2", targetVersion: "0.4.0", nodePath: process.execPath,
appEntry: path.join(rootDir, "dist", "index.js"),
health: { protocol: "http", port: 39997, path: "/api/health" },
waitForPid: process.pid, parentTimeoutMs: 60_000, healthTimeoutMs: 100, pollIntervalMs: 50,
appLogPath: path.join(updatesDir, "app.log"),
}, null, 2));
const service = new UpdateService({
rootDir, dataDir, currentVersion: "0.3.2", logger, platform: "linux", architecture: "x64", env: {}, isDocker: false,
fetch: fakeFetch([], new Map()), runnerSourceDir: compiled, runnerStartupTimeoutMs: 1_500,
});
await assert.rejects(
service.launchRunner(planPath, path.join(updatesDir, "runner")),
updateErrorCode("UPDATE_RUNNER_FAILED"),
);
assert.equal(service.runnerStillHealthy(), true, "no runner was recorded, so the guard is a no-op");
});
+76 -12
View File
@@ -1,7 +1,7 @@
import { createHash, randomBytes } from "node:crypto";
import { spawn, type ChildProcess } from "node:child_process";
import {
closeSync, copyFileSync, createWriteStream, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync,
chmodSync, closeSync, copyFileSync, createWriteStream, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync,
} from "node:fs";
import { rename, rm } from "node:fs/promises";
import path from "node:path";
@@ -82,6 +82,29 @@ export interface UpdateServiceOptions {
const CHECKSUM_LIMIT = 1024 * 1024;
const DOWNLOAD_LIMIT = 512 * 1024 * 1024;
/**
* Install the recovery-capable launcher before the runner tears down dist/
* and runtime/. The staged package ships the canonical script (same file CI
* generates), so even the first upgrade from the old four-line launcher has
* a self-healing ./start-webspeak.sh on the official path at all times.
*/
function installRecoveryLauncher(rootDir: string, stagedRoot: string): void {
const source = path.join(stagedRoot, "start-webspeak.sh");
// Source installs and hand-built test packages have no launcher; real
// release packages always do.
if (!existsSync(source)) return;
const target = path.join(rootDir, "start-webspeak.sh");
const temporary = `${target}.${process.pid}.tmp`;
try {
copyFileSync(source, temporary);
chmodSync(temporary, 0o755);
renameSync(temporary, target);
} catch (error) {
try { rmSync(temporary, { force: true }); } catch { /* Preserve the original error. */ }
throw error;
}
}
/**
* Every local module the restart runner imports at runtime. The runner is
* copied into an isolated directory under data/updates, so any omission here
@@ -107,6 +130,7 @@ export class UpdateService {
private state: PersistedUpdateState = emptyUpdateState();
private applying = false;
private releaseLock: (() => void) | null = null;
private runnerPid: number | null = null;
constructor(private readonly options: UpdateServiceOptions) {
this.deployment = detectDeployment({
@@ -253,6 +277,7 @@ export class UpdateService {
throw new UpdateError("UPDATE_IN_PROGRESS", "Another update task is already running.", 409);
}
this.applying = true;
this.runnerPid = null;
const taskId = `upd_${Date.now().toString(36)}_${randomBytes(6).toString("hex")}`;
const startedAt = this.now().toISOString();
const task: UpdateTaskView = {
@@ -317,6 +342,7 @@ export class UpdateService {
throw error;
}
this.finishStep(task, "stage", "succeeded");
installRecoveryLauncher(this.options.rootDir, stagedRoot);
const planPath = path.join(taskDirectory, "plan.json");
const runnerDirectory = path.join(taskDirectory, "runner");
const plan = {
@@ -375,6 +401,7 @@ export class UpdateService {
try { rmSync(taskDirectory, { recursive: true, force: true }); } catch { /* Best effort. */ }
this.releaseLock?.();
this.releaseLock = null;
this.runnerPid = null;
// A runner that died after taking over leaves its own pid in the lock.
// Only a provably dead owner is removed; a live lock is left alone.
clearStaleUpdateLock(this.lockPath);
@@ -479,10 +506,11 @@ export class UpdateService {
/**
* Copy the runner and all of its runtime imports into an isolated directory,
* start it detached, and wait briefly to prove it did not die on startup.
* start it detached, and wait until it has taken over the update lock.
* A successful spawn alone is not enough: Node resolves the whole ESM module
* graph before executing the helper, so a missing file only shows up as an
* early exit. Returning here means the helper is actually running.
* early exit. Ownership of the lock also proves the runner is alive after
* its startup window and really controls this task before we promise 202.
*/
async launchRunner(planPath: string, runnerDirectory: string): Promise<number> {
const sourceDirectory = this.options.runnerSourceDir ?? path.dirname(fileURLToPath(import.meta.url));
@@ -507,7 +535,7 @@ export class UpdateService {
nodePath = process.execPath;
}
const log = path.join(path.dirname(planPath), "runner.log");
const graceMs = this.options.runnerStartupTimeoutMs ?? 750;
const graceMs = this.options.runnerStartupTimeoutMs ?? 1_500;
return new Promise<number>((resolve, reject) => {
let child: ChildProcess;
let fd: number | null = null;
@@ -527,11 +555,11 @@ export class UpdateService {
if (fd !== null) closeSync(fd);
}
let settled = false;
let timer: NodeJS.Timeout | undefined;
let poll: NodeJS.Timeout | undefined;
const fail = (message: string) => {
if (settled) return;
settled = true;
if (timer) clearTimeout(timer);
if (poll) clearInterval(poll);
reject(new UpdateError("UPDATE_RUNNER_FAILED", message, 500));
};
child.once("error", (error) => fail(error.message));
@@ -540,18 +568,54 @@ export class UpdateService {
});
child.once("spawn", () => {
child.unref();
timer = setTimeout(() => {
const deadline = Date.now() + graceMs;
poll = setInterval(() => {
if (settled) return;
settled = true;
if (!child.pid) {
reject(new UpdateError("UPDATE_RUNNER_FAILED", "The restart runner did not report a process id.", 500));
const pid = child.pid;
if (!pid) {
fail("The restart runner did not report a process id.");
return;
}
resolve(child.pid);
}, graceMs);
if (Date.now() > deadline) {
fail("The restart runner did not take over the update lock in time.");
return;
}
if (!pidIsAlive(pid) || !lockOwnedBy(this.lockPath, pid)) return;
settled = true;
if (poll) clearInterval(poll);
this.runnerPid = pid;
resolve(pid);
}, 25);
});
});
}
/**
* Last chance guard for the promise made with 202. The parent still exists
* for a short window after the handshake, so re-check that the runner is
* alive and still owns the lock before the caller exits the process.
*/
runnerStillHealthy(): boolean {
const pid = this.runnerPid;
// No runner was launched through this instance (source install, mocked
// route test): there is nothing extra to verify.
if (pid === null) return true;
return pidIsAlive(pid) && lockOwnedBy(this.lockPath, pid);
}
}
function pidIsAlive(pid: number): boolean {
try { process.kill(pid, 0); return true; }
catch (error) { return (error as NodeJS.ErrnoException).code === "EPERM"; }
}
function lockOwnedBy(lockPath: string, pid: number): boolean {
try {
const record = JSON.parse(readFileSync(lockPath, "utf8")) as { pid?: unknown };
return record?.pid === pid;
} catch {
return false;
}
}
function repositoryParts(repository: string | undefined): [string, string] {