fix(updater): preserve recovery consistency across interrupted updates

Keep health checks, rollback reporting, launcher recovery, and download failure handling consistent so verified updates cannot report false success or crash during recoverable I/O failures.
This commit is contained in:
OddTurtleHead committed 2026-11-25 23:51:16 +08:00
1 parent 6273185afa
commit cf1cc9fb94
9 files changed
+325 -46

No files matched your search

+34 -23
View File
@@ -28,8 +28,8 @@ code_missing() {
return 1
}
# A backup can only repair an install if it recorded a swap and still holds
# every entry needed to boot. Partial/legacy backups must be skipped.
# A backup can only repair a missing-code install if it is complete. Partial
# backups are still resumable when they belong to the active task.
backup_is_complete() {
[ -f "$1/.webspeak-swap.json" ] || return 1
for entry in $required_entries; do
@@ -52,6 +52,30 @@ task_backup_can_repair() {
return 0
}
state_file="$data_dir/updates/state.json"
task_id=""
task_status=""
if [ -f "$state_file" ]; then
task_id=$(sed -n 's/.*"id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$state_file" | head -n 1)
task_status=$(sed -n 's/.*"status"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$state_file" | head -n 1)
fi
case "$task_id" in
""|*[!A-Za-z0-9_-]*) task_id="" ;;
esac
recovery_needed() {
if code_missing; then
return 0
fi
case "$task_status" in
downloading|verifying|extracting|staging|restarting)
[ -n "$task_id" ] && [ -d "$backups/$task_id" ] && [ -f "$backups/$task_id/.webspeak-swap.json" ]
return $?
;;
esac
return 1
}
restore_from_backup() {
backup="$1"
# Move whatever partial new code the interrupted swap left in the install
@@ -80,33 +104,20 @@ restore_from_backup() {
done
}
if code_missing; then
if recovery_needed; then
restore_backup=""
# The interrupted task is the source of truth: backups/<task.id> holds the
# exact version that was running before the swap. A successful earlier
# update leaves its backup behind (M1 does not clean it up), so picking the
# first or alphabetically smallest backup can resurrect a much older build.
state_file="$data_dir/updates/state.json"
task_id=""
if [ -f "$state_file" ]; then
task_id=$(sed -n 's/.*"id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$state_file" | head -n 1)
fi
# Task ids are generated as upd_<base36>_<hex>. Reject anything else so a
# tampered state.json cannot become a path traversal or a glob pattern.
case "$task_id" in
""|*[!A-Za-z0-9_-]*) task_id="" ;;
esac
if [ -n "$task_id" ]; then
# The interrupted task is the source of truth. Its backup may be partial
# while the old tree is being saved or while a previous recovery is still
# consuming it, but it must never be replaced by an older complete backup.
if [ -n "$task_id" ] && [ -d "$backups/$task_id" ]; then
candidate="$backups/$task_id"
if task_backup_can_repair "$candidate"; then
restore_backup="$candidate"
fi
fi
# No usable task backup (e.g. state.json was lost): use the most recently
# modified complete backup rather than whichever name happens to sort first.
if [ -z "$restore_backup" ]; then
else
# No current task backup (e.g. state.json was lost): use the most recently
# modified complete backup rather than whichever name happens to sort first.
for manifest in "$backups"/*/.webspeak-swap.json; do
[ -f "$manifest" ] || continue
backup="${manifest%/.webspeak-swap.json}"
+5
View File
@@ -37,6 +37,11 @@ test("staged packages must be complete, regular files and version-matched", t =>
rmSync(path.join(missing, "runtime", "node"));
assert.throws(() => validateStagedPackage(missing, { version: "0.4.0", platform: "linux" }), packageInvalid);
const missingLauncher = workspace(t);
createPackageFiles(missingLauncher, "0.4.0");
rmSync(path.join(missingLauncher, "start-webspeak.sh"));
assert.throws(() => validateStagedPackage(missingLauncher, { version: "0.4.0", platform: "linux" }), packageInvalid);
const linked = workspace(t);
createPackageFiles(linked, "0.4.0");
rmSync(path.join(linked, "runtime", "node"));
+13 -7
View File
@@ -56,6 +56,7 @@ export function validateStagedPackage(root: string, options: StagedPackageOption
requireEntry(root, "node_modules", "directory");
requireEntry(root, "package.json", "file");
requireEntry(root, options.platform === "win32" ? "runtime/node.exe" : "runtime/node", "file");
requireEntry(root, options.platform === "win32" ? "start-webspeak.cmd" : "start-webspeak.sh", "file");
let manifest: unknown;
try { manifest = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")); }
catch { throw new CodeSwapError("UPDATE_PACKAGE_INVALID", "Release package manifest is not valid JSON."); }
@@ -145,10 +146,10 @@ function moveIfPresent(from: string, to: string): void {
}
/**
* Backups written by this version contain only atomically moved entries.
* The manifest records which entries were moved completely, so a backup that
* was partially written by an older implementation (or tampered with) can be
* rejected instead of overwriting an intact install tree.
* Backups written by this version journal each entry before moving it. The
* journal may therefore contain an entry whose move never started, but it can
* never omit an entry that reached the backup. Recovery acts only on entries
* that actually exist in the backup, so a kill between journal and move is safe.
*/
const SWAP_MANIFEST = ".webspeak-swap.json";
@@ -203,10 +204,10 @@ export function swapCode(rootDir: string, stagedRoot: string, backupDir: string)
writeSwapManifest(backupDir, []);
for (const entry of CODE_ENTRIES) {
if (!existsSync(path.join(rootDir, entry))) continue;
moveIfPresent(path.join(rootDir, entry), path.join(backupDir, entry));
movedToBackup.push(entry);
swapWindowBarrier(entry);
writeSwapManifest(backupDir, movedToBackup);
moveIfPresent(path.join(rootDir, entry), path.join(backupDir, entry));
swapWindowBarrier(entry);
}
swapWindowBarrier();
for (const entry of CODE_ENTRIES) {
@@ -216,7 +217,12 @@ export function swapCode(rootDir: string, stagedRoot: string, backupDir: string)
}
} catch (error) {
try { restoreMovedEntries(rootDir, backupDir, movedToBackup, movedToRoot); }
catch { /* Report the original swap error; rollback failure is handled by the caller. */ }
catch (rollbackError) {
throw new CodeSwapError(
"UPDATE_ROLLBACK_FAILED",
`${error instanceof Error ? error.message : "Release package swap failed."} Code rollback also failed: ${rollbackError instanceof Error ? rollbackError.message : "unknown error"}`,
);
}
if (error instanceof CodeSwapError) throw error;
throw new CodeSwapError("UPDATE_SWAP_FAILED", error instanceof Error ? error.message : "Release package swap failed.");
}
+58 -4
View File
@@ -2,9 +2,12 @@ import assert from "node:assert/strict";
import test, { type TestContext } from "node:test";
import { spawn, type ChildProcess } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import fs from "node:fs";
import { syncBuiltinESMExports } from "node:module";
import { createServer } from "node:net";
import { tmpdir } from "node:os";
import path from "node:path";
import { setCodeSwapCopyForTests } from "./code-swap.js";
import { runRestartPlan } from "./restart-runner.js";
const sleep = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
@@ -27,13 +30,13 @@ async function waitFor(check: () => boolean, timeoutMs = 5_000): Promise<void> {
}
}
function appScript(version: string, port: number, pidFile: string): string {
function appScript(version: string, port: number, pidFile: string, status = "ok"): string {
return `const http = require("node:http");
const { writeFileSync } = require("node:fs");
const server = http.createServer((request, response) => {
if (request.url === "/api/health") {
response.setHeader("content-type", "application/json");
response.end(JSON.stringify({ status: "ok", version: ${JSON.stringify(version)} }));
response.end(JSON.stringify({ status: ${JSON.stringify(status)}, version: ${JSON.stringify(version)} }));
return;
}
response.statusCode = 404;
@@ -85,10 +88,10 @@ function runnerFixture(t: TestContext): RunnerFixture {
};
}
function writePlan(fixture: RunnerFixture, port: number, pidFile: string, options: { targetVersion: string; reportedVersion: string; healthTimeoutMs?: number }) {
function writePlan(fixture: RunnerFixture, port: number, pidFile: string, options: { targetVersion: string; reportedVersion: string; reportedStatus?: string; healthTimeoutMs?: number }) {
mkdirSync(path.dirname(fixture.statePath), { recursive: true });
writeFileSync(fixture.lockPath, JSON.stringify({ pid: process.pid, taskId: fixture.taskId, createdAt: new Date().toISOString() }));
writeFileSync(path.join(fixture.stagedRoot, "dist", "index.js"), appScript(options.reportedVersion, port, pidFile));
writeFileSync(path.join(fixture.stagedRoot, "dist", "index.js"), appScript(options.reportedVersion, port, pidFile, options.reportedStatus));
writeFileSync(fixture.planPath, JSON.stringify({
schemaVersion: 1,
taskId: fixture.taskId,
@@ -148,6 +151,57 @@ test("a healthy target version completes the swap and leaves persistent state al
await waitFor(() => existsSync(fixture.pidFile));
});
test("a failed in-process rollback is persisted as a rollback failure", { timeout: 20_000 }, async t => {
const fixture = runnerFixture(t);
const port = await availablePort();
writePlan(fixture, port, fixture.pidFile, { targetVersion: "2.0.0", reportedVersion: "2.0.0" });
const originalRename = fs.renameSync;
t.after(() => {
fs.renameSync = originalRename;
syncBuiltinESMExports();
setCodeSwapCopyForTests(null);
});
const exdev = () => Object.assign(new Error("cross-device link"), { code: "EXDEV" });
fs.renameSync = ((from, to) => {
if (from === path.join(fixture.rootDir, "dist") && to === path.join(fixture.backupDir, "dist")) throw exdev();
if (from === path.join(fixture.stagedRoot, "dist") && to === path.join(fixture.rootDir, "dist")) throw new Error("simulated staging failure");
if (from === path.join(fixture.backupDir, "dist") && to === path.join(fixture.rootDir, "dist")) throw exdev();
return originalRename(from, to);
}) as typeof fs.renameSync;
syncBuiltinESMExports();
let copies = 0;
setCodeSwapCopyForTests((from, to) => {
copies += 1;
if (copies === 2) throw new Error("simulated rollback copy failure");
fs.cpSync(from, to, { recursive: true });
});
assert.equal(await runRestartPlan(fixture.planPath), 1);
const state = JSON.parse(readFileSync(fixture.statePath, "utf8"));
assert.equal(state.task.status, "failed");
assert.equal(state.task.rolledBack, false);
assert.equal(state.task.errorCode, "UPDATE_ROLLBACK_FAILED");
assert.equal(existsSync(path.join(fixture.rootDir, "dist", "index.js")), false);
assert.equal(existsSync(path.join(fixture.backupDir, "dist", "index.js")), true);
});
test("a target reporting the expected version with an error status is not accepted as healthy", { timeout: 20_000 }, async t => {
const fixture = runnerFixture(t);
const port = await availablePort();
writePlan(fixture, port, fixture.pidFile, {
targetVersion: "2.0.0", reportedVersion: "2.0.0", reportedStatus: "error", healthTimeoutMs: 500,
});
writeFileSync(path.join(fixture.rootDir, "dist", "index.js"), appScript("1.0.0", port, fixture.pidFile));
t.after(() => stopPidFile(fixture.pidFile));
assert.equal(await runRestartPlan(fixture.planPath), 1);
const state = JSON.parse(readFileSync(fixture.statePath, "utf8"));
assert.equal(state.task.status, "failed");
assert.equal(state.task.rolledBack, true);
assert.equal(state.task.errorCode, "UPDATE_HEALTH_CHECK_FAILED");
assert.match(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), /version: "1\.0\.0"/);
});
test("a failed health check rolls back to the previous code and reports the failure", { timeout: 20_000 }, async t => {
const fixture = runnerFixture(t);
const port = await availablePort();
+7 -1
View File
@@ -217,7 +217,7 @@ async function waitForVersion(plan: RestartPlan, version: string, timeoutMs: num
if (last?.status === "ok" && last.version === version) return last;
await sleep(plan.pollIntervalMs);
}
return last?.version === version ? last : null;
return null;
}
function startApp(plan: RestartPlan): ChildProcess {
@@ -309,6 +309,12 @@ export async function runRestartPlan(planPath: string): Promise<number> {
: "UPDATE_RESTART_FAILED";
const message = error instanceof Error ? error.message : "The update could not be completed.";
state.step("restart", "failed", message);
if (!swapped && code === "UPDATE_ROLLBACK_FAILED") {
state.rolledBack(false);
state.status("failed", { code, message });
releaseLock?.();
return 1;
}
let rolledBack = !swapped;
if (swapped) {
state.step("rollback", "running");
+84 -2
View File
@@ -2,12 +2,12 @@ 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 { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, 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";
import { CODE_ENTRIES } from "./code-swap.js";
import { CODE_ENTRIES, swapCode } from "./code-swap.js";
const SOURCE_DIR = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(SOURCE_DIR, "..", "..");
@@ -81,6 +81,11 @@ async function healthVersion(port: number): Promise<string | null> {
}
}
function startedVersion(fixture: Fixture): string | null {
const { startedFile } = JSON.parse(readFileSync(fixture.markerFiles.config, "utf8")) as { startedFile: string };
return existsSync(startedFile) ? readFileSync(startedFile, "utf8") : null;
}
function processAlive(pid: number | undefined): boolean {
if (!pid || pid <= 0) return false;
try { process.kill(pid, 0); return true; }
@@ -309,6 +314,83 @@ test(
},
);
test(
"launcher resumes a partial current backup instead of installing a stale complete backup",
{ timeout: 20_000 },
async t => {
const port = await availablePort();
const fixture = buildFixture(t, port, true);
const staleDir = path.join(fixture.dataDir, "updates", "backups", "aaa_stale_backup");
mkdirSync(fixture.backupDir, { recursive: true });
renameSync(path.join(fixture.rootDir, "dist"), path.join(fixture.backupDir, "dist"));
writeFileSync(path.join(fixture.backupDir, ".webspeak-swap.json"), JSON.stringify({ schemaVersion: 1, entries: ["dist"] }));
let app: ChildProcess | undefined;
t.after(() => stop(app));
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
cwd: fixture.rootDir,
env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir },
stdio: "ignore",
});
await waitFor(() => startedVersion(fixture) !== null, "launcher did not resume the partial current backup");
assert.equal(startedVersion(fixture), "0.3.2");
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.3.2");
assert.equal(JSON.parse(readFileSync(path.join(staleDir, "package.json"), "utf8")).version, "0.1.0");
assert.equal(existsSync(path.join(staleDir, "dist", "index.js")), true);
},
);
test(
"launcher resumes a rollback that already consumed part of the current backup",
{ timeout: 20_000 },
async t => {
const port = await availablePort();
const fixture = buildFixture(t, port);
swapCode(fixture.rootDir, fixture.stagedRoot, fixture.backupDir);
for (const entry of ["runtime", "package.json"]) {
rmSync(path.join(fixture.rootDir, entry), { recursive: true, force: true });
renameSync(path.join(fixture.backupDir, entry), path.join(fixture.rootDir, entry));
}
mkdirSync(path.join(fixture.backupDir, "rejected"), { recursive: true });
renameSync(path.join(fixture.rootDir, "dist"), path.join(fixture.backupDir, "rejected", "dist"));
let app: ChildProcess | undefined;
t.after(() => stop(app));
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
cwd: fixture.rootDir,
env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir },
stdio: "ignore",
});
await waitFor(() => startedVersion(fixture) !== null, "launcher did not resume the interrupted rollback");
assert.equal(startedVersion(fixture), "0.3.2");
assert.equal(existsSync(path.join(fixture.rootDir, "dist", "index.js")), true);
},
);
test(
"launcher rolls back an active fully swapped tree before starting the target",
{ timeout: 20_000 },
async t => {
const port = await availablePort();
const fixture = buildFixture(t, port);
writeFileSync(path.join(fixture.stagedRoot, "dist", "index.js"), appScript());
copyFileSync(process.execPath, path.join(fixture.stagedRoot, "runtime", "node"));
chmodSync(path.join(fixture.stagedRoot, "runtime", "node"), 0o755);
swapCode(fixture.rootDir, fixture.stagedRoot, fixture.backupDir);
let app: ChildProcess | undefined;
t.after(() => stop(app));
app = spawn(path.join(fixture.rootDir, "start-webspeak.sh"), [], {
cwd: fixture.rootDir,
env: { ...process.env, WEBSPEAK_DATA_DIR: fixture.dataDir },
stdio: "ignore",
});
await waitFor(() => startedVersion(fixture) !== null, "launcher did not resolve the active swapped tree");
assert.equal(startedVersion(fixture), "0.3.2");
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.3.2");
},
);
test(
"recovery prefers the in-progress task backup over an older lexicographically-first backup",
{ timeout: 40_000 },
+1
View File
@@ -143,6 +143,7 @@ export function createPackageFiles(root: string, version: string, extra: Record<
writeFileSync(path.join(root, "dist", "index.js"), "// package entry\n", "utf8");
writeFileSync(path.join(root, "web", "dist", "index.html"), "<!doctype html>\n", "utf8");
writeFileSync(path.join(root, "runtime", "node"), "#!/bin/sh\nexit 0\n", { encoding: "utf8", mode: 0o755 });
writeFileSync(path.join(root, "start-webspeak.sh"), "#!/bin/sh\nexit 0\n", { encoding: "utf8", mode: 0o755 });
for (const [relative, contents] of Object.entries(extra)) {
const target = path.join(root, relative);
mkdirSync(path.dirname(target), { recursive: true });
+97 -1
View File
@@ -1,6 +1,9 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { once } from "node:events";
import fs from "node:fs";
import { syncBuiltinESMExports } from "node:module";
import { Writable } from "node:stream";
import test, { type TestContext } from "node:test";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
@@ -8,6 +11,7 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import type { Logger } from "../logger.js";
import { CHECKSUM_ASSET_NAME, OFFICIAL_REPOSITORY } from "./releases.js";
import { swapCode } from "./code-swap.js";
import { UpdateError, UpdateService, type UpdateErrorCode, type UpdateServiceOptions } from "./update-service.js";
import { createPackageFiles, createTarGz, sha256Hex, type TarFixtureEntry } from "./test-support.js";
import { acquireUpdateLock, readUpdateState, writeUpdateState } from "./update-state.js";
@@ -67,6 +71,7 @@ function packageArchive(version: string, extra: TarFixtureEntry[] = []): Buffer
{ name: "webspeak/web/dist/index.html", data: "<!doctype html>\n" },
{ name: "webspeak/node_modules/.keep", data: "" },
{ name: "webspeak/runtime/node", data: "#!/bin/sh\nexit 0\n", mode: 0o755 },
{ name: "webspeak/start-webspeak.sh", data: "#!/bin/sh\nexit 0\n", mode: 0o755 },
...extra,
]);
}
@@ -269,6 +274,64 @@ test("unsafe archives are refused before any code is staged", async t => {
assert.equal(state.task?.errorCode, "UPDATE_ARCHIVE_UNSAFE");
});
test("an asynchronous download write failure rejects the update without crashing the process", async t => {
const archive = packageArchive("0.4.0");
const checksums = Buffer.from(checksumText(ASSET_NAME, archive));
const release = releaseJson({
version: "0.4.0",
assets: [
{ name: ASSET_NAME, data: archive },
{ name: CHECKSUM_ASSET_NAME, data: checksums },
],
});
const originalCreateWriteStream = fs.createWriteStream;
t.after(() => {
fs.createWriteStream = originalCreateWriteStream;
syncBuiltinESMExports();
});
fs.createWriteStream = (() => new Writable({
write(_chunk, _encoding, callback) {
setImmediate(() => callback(new Error("simulated ENOSPC")));
},
})) as unknown as typeof fs.createWriteStream;
syncBuiltinESMExports();
const stalledBody = () => new ReadableStream({
start(controller) { controller.enqueue(new Uint8Array([1, 2, 3])); },
pull() { return new Promise(() => {}); },
});
const fetch = (async (input: string | URL | Request) => {
if (String(input) === RELEASE_LIST_URL) return new Response(JSON.stringify([release]), { status: 200 });
return new Response(stalledBody(), { status: 200 });
}) as typeof globalThis.fetch;
const { service, launched } = createService(t, [], new Map(), { fetch });
await assert.rejects(service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_DOWNLOAD_FAILED"));
assert.equal(launched.length, 0);
});
test("a download redirected outside GitHub is refused before it is written", async t => {
const archive = packageArchive("0.4.0");
const checksums = Buffer.from(checksumText(ASSET_NAME, archive));
const release = releaseJson({
version: "0.4.0",
assets: [
{ name: ASSET_NAME, data: archive },
{ name: CHECKSUM_ASSET_NAME, data: checksums },
],
});
const fetch = (async (input: string | URL | Request) => {
const url = String(input);
if (url === RELEASE_LIST_URL) return new Response(JSON.stringify([release]), { status: 200 });
const response = new Response(url.endsWith(ASSET_NAME) ? new Uint8Array(archive) : new Uint8Array(checksums), { status: 200 });
if (url.endsWith(ASSET_NAME)) Object.defineProperty(response, "url", { value: "https://example.invalid/package.tar.gz" });
return response;
}) as typeof globalThis.fetch;
const { service, launched } = createService(t, [], new Map(), { fetch });
await assert.rejects(service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_RELEASE_UNAVAILABLE"));
assert.equal(launched.length, 0);
});
test("a verified package is staged, persisted and handed to the restart runner", async t => {
const archive = packageArchive("0.4.0");
const checksums = Buffer.from(checksumText(ASSET_NAME, archive));
@@ -400,7 +463,7 @@ test("initialization restores the previous code from an interrupted swap backup"
writeFileSync(lockPath, JSON.stringify({ pid: 0, taskId, createdAt: "2026-01-01T00:00:00.000Z" }));
const restarted = new UpdateService({
rootDir: fixture.rootDir, dataDir: fixture.dataDir, currentVersion: "0.4.0", logger,
rootDir: fixture.rootDir, dataDir: fixture.dataDir, currentVersion: "0.3.2", logger,
platform: "linux", architecture: "x64", env: {}, isDocker: false, fetch: fakeFetch([], new Map()),
now: () => new Date("2026-01-01T00:10:00.000Z"),
});
@@ -415,6 +478,39 @@ test("initialization restores the previous code from an interrupted swap backup"
assert.equal(existsSync(lockPath), false);
});
test("initialization keeps a complete target tree consistent with the running target version", t => {
const fixture = createService(t, [], new Map());
const taskId = "upd_complete_target";
const statePath = path.join(fixture.dataDir, "updates", "state.json");
const lockPath = path.join(fixture.dataDir, "updates", "update.lock");
const backupDir = path.join(fixture.dataDir, "updates", "backups", taskId);
const stagedRoot = path.join(fixture.dataDir, "updates", "tasks", taskId, "staged");
createPackageFiles(stagedRoot, "0.4.0", { "dist/index.js": "// complete target code\n" });
swapCode(fixture.rootDir, stagedRoot, backupDir);
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: [],
},
});
writeFileSync(lockPath, JSON.stringify({ pid: 0, taskId, createdAt: "2026-01-01T00:00:00.000Z" }));
const restarted = new UpdateService({
rootDir: fixture.rootDir, dataDir: fixture.dataDir, currentVersion: "0.4.0", logger,
platform: "linux", architecture: "x64", env: {}, isDocker: false, fetch: fakeFetch([], new Map()),
now: () => new Date("2026-01-01T00:10:00.000Z"),
});
restarted.initialize();
assert.equal(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), "// complete target code\n");
assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.4.0");
assert.equal(restarted.getStatus().task?.status, "succeeded");
assert.equal(restarted.getStatus().task?.rolledBack, false);
assert.equal(existsSync(lockPath), false);
});
test("initialization keeps a live task but reconciles it once its process is gone", async t => {
const fixture = createService(t, [], new Map());
const running = {
+26 -8
View File
@@ -9,7 +9,7 @@ import { fileURLToPath } from "node:url";
import type { Logger } from "../logger.js";
import type { UpdateCheckView, UpdateReleaseView, UpdateStatusView, UpdateTaskStatus, UpdateTaskView } from "../shared/update.js";
import { ArchiveError, extractReleaseArchive } from "./archive.js";
import { CodeSwapError, locatePackageRoot, restoreCode } from "./code-swap.js";
import { CodeSwapError, locatePackageRoot, restoreCode, validateStagedPackage } from "./code-swap.js";
import { detectDeployment, releaseAssetName, type DeploymentInfo } from "./deployment.js";
import {
assertOfficialDownloadUrl, CHECKSUM_ASSET_NAME, GitHubReleaseSource, ReleaseSourceError,
@@ -184,6 +184,15 @@ export class UpdateService {
private recoverInterruptedSwap(task: NonNullable<PersistedUpdateState["task"]>): boolean | null {
const backupDir = path.join(this.backupsDir, task.id);
if (!existsSync(backupDir)) return null;
if (this.options.currentVersion === task.targetVersion) {
try {
validateStagedPackage(this.options.rootDir, { version: task.targetVersion, platform: this.options.platform });
return null;
} catch {
// A process can read the target version before every target entry is in
// place. Fall through to recovery when the on-disk tree is incomplete.
}
}
const now = this.now().toISOString();
let restored = false;
try {
@@ -490,19 +499,28 @@ export class UpdateService {
const hash = createHash("sha256");
const stream = createWriteStream(temporary, { mode: 0o600, flags: "wx" });
let bytes = 0;
let failStream!: (error: Error) => void;
const streamFailure = new Promise<Error>((resolve) => { failStream = resolve; });
stream.on("error", failStream);
const finished = new Promise<void>((resolve) => { stream.once("finish", resolve); });
try {
for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {
const buffer = Buffer.from(chunk);
const iterator = (response.body as unknown as AsyncIterable<Uint8Array>)[Symbol.asyncIterator]();
while (true) {
const next = await Promise.race([iterator.next(), streamFailure]);
if (next instanceof Error) throw next;
if (next.done) break;
const buffer = Buffer.from(next.value);
bytes += buffer.length;
if (bytes > limit) throw new UpdateError("UPDATE_DOWNLOAD_TOO_LARGE", "The release asset exceeds the download limit.", 422);
hash.update(buffer);
if (!stream.write(buffer)) await new Promise<void>((resolve) => stream.once("drain", resolve));
if (!stream.write(buffer)) {
const drained = await Promise.race([streamFailure, new Promise<void>((resolve) => { stream.once("drain", resolve); })]);
if (drained instanceof Error) throw drained;
}
}
stream.end();
await new Promise<void>((resolve, reject) => {
stream.once("finish", resolve);
stream.once("error", reject);
});
const streamError = await Promise.race([finished.then(() => null), streamFailure]);
if (streamError) throw streamError;
await rename(temporary, destination);
} catch (error) {
stream.destroy();