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
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f

---

## [Unreleased]

### Fixes & Improvements

- **In-app updates work when ompweb runs as a systemd service.** The update worker ran inside the service's cgroup, so stopping the server killed the worker too: nothing was installed, the service could stay down (`Restart=on-failure` does not restart a clean SIGTERM exit), and every page load reopened the update dialog at "Stop ompweb-managed sessions". The worker now runs in its own transient scope (`systemd-run --scope`) and stops, updates and starts the unit through `systemctl`, starting it again if the install fails.
- **An update whose worker died is reported as failed.** A running update whose worker process is gone, or whose lease has expired, now becomes a failed attempt the dialog can show and clean up, instead of waiting forever.

---

## [v0.6.0] - 2026-10-26

### Added
Expand Down
2 changes: 1 addition & 1 deletion app/api/app-update/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ async function commitAppUpdate(attemptId: string): Promise<CommitResult> {
if (commitState === "ready") markSelfUpdateStopping(attemptId);
await armSelfUpdateLauncher(attemptId);
launcherArmed = true;
return commitSelfUpdate(attemptId);
return await commitSelfUpdate(attemptId);
} catch (error) {
if (!launcherArmed) {
const reason = error instanceof SelfUpdateError
Expand Down
2 changes: 1 addition & 1 deletion app/api/omp-update/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export async function POST(request: Request) {
const commitState = validateCommitSelfUpdate(body.attemptId, OMP_KIND);
if (commitState !== "replay") {
if (commitState === "ready") markSelfUpdateStopping(body.attemptId, OMP_KIND);
commitSelfUpdate(body.attemptId, OMP_KIND);
await commitSelfUpdate(body.attemptId, OMP_KIND);
}
return NextResponse.json({ accepted: true, attemptId: body.attemptId }, { status: 202 });
}
Expand Down
29 changes: 28 additions & 1 deletion bin/omp-web-update-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ const from = arg("--from");
const launcherPid = Number(arg("--launcher-pid"));
const serverPid = Number(arg("--server-pid"));
const kind = arg("--kind") || "app";
// Set when the server runs as this systemd unit; systemd stops and starts it.
const systemdUnit = arg("--systemd-unit");
const systemctlScope = arg("--systemd-user") === "1" ? ["--user"] : [];
let descriptor;
let managerPrefix;
try {
Expand Down Expand Up @@ -76,9 +79,20 @@ function isTrayActive() {
return Boolean(data && data.pid);
} catch { return false; }
}
function systemctl(action) {
const result = cp.spawnSync("systemctl", [...systemctlScope, action, systemdUnit], { encoding: "utf8", timeout: 120000 });
if (result.status !== 0) {
const detail = (result.stderr || result.stdout || (result.error && result.error.message) || "").trim().slice(0, 200);
throw new Error(`systemctl ${action} ${systemdUnit} failed${detail ? `: ${detail}` : ""}`);
}
}

async function stopOriginalProcesses() {
updateStatus({ stage: "stopping" });
if (systemdUnit) {
systemctl("stop");
return { systemd: true, launchd: false, tray: false };
}
// Detect services
const launchd = isLaunchdActive();
const tray = isTrayActive();
Expand Down Expand Up @@ -158,6 +172,15 @@ async function runManagerGate() {

async function restartServices(info) {
updateStatus({ stage: "restarting" });
if (info.systemd) {
systemctl("start");
// A Type=simple start returns once the process is forked; a release that
// crashes on startup shows up as not active a moment later.
// shortcut: one check after 3s, not a port probe; upgrade if slow-starting crashes slip through.
await sleep(3000);
systemctl("is-active");
return;
}
if (info.launchd) {
try {
const uid = typeof process.getuid === "function" ? process.getuid() : 501;
Expand Down Expand Up @@ -228,7 +251,11 @@ async function main() {
// write complete marker
try { atomicWrite(markerFile("complete.json"), { attemptId, completedAt: new Date().toISOString() }); } catch {}
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
let msg = e instanceof Error ? e.message : String(e);
// Never leave the service stopped after a failed install.
if (systemdUnit) {
try { systemctl("start"); } catch { msg = `${systemdUnit} is still stopped: ${msg}`; }
}
updateStatus({ state: "failed", error: msg.slice(0, 240), finishedAt: new Date().toISOString(), cleanupReady: true });
}
}
Expand Down
68 changes: 68 additions & 0 deletions bin/omp-web-update-worker.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { delimiter, join } from "node:path";
import { tmpdir } from "node:os";
import { fileURLToPath } from "node:url";
import test from "node:test";

const WORKER = fileURLToPath(new URL("./omp-web-update-worker.js", import.meta.url));
const ATTEMPT = "11111111-2222-3333-4444-555555555555";

// Runs the worker for a systemd unit with stub `systemctl` and `npm` on PATH.
function runWorker(t, { npmExit = 0, startExit = 0, activeExit = 0 } = {}) {
const dir = mkdtempSync(join(tmpdir(), "update-worker-test-"));
t.after(() => rmSync(dir, { recursive: true, force: true }));
const log = join(dir, "calls.log");
writeFileSync(join(dir, "systemctl"), `#!/bin/sh\necho "systemctl $*" >> "${log}"\n[ "$2" = start ] && exit ${startExit}\n[ "$2" = is-active ] && { echo failed; exit ${activeExit}; }\nexit 0\n`, { mode: 0o755 });
writeFileSync(join(dir, "npm"), `#!/bin/sh\necho "npm $*" >> "${log}"\nexit ${npmExit}\n`, { mode: 0o755 });
writeFileSync(join(dir, "status.json"), JSON.stringify({ attemptId: ATTEMPT, state: "running" }), { mode: 0o600 });
writeFileSync(join(dir, `${ATTEMPT}.go`), "{}", { mode: 0o600 });
const result = spawnSync(process.execPath, [
WORKER,
"--attempt", ATTEMPT,
"--root", dir,
"--package-dir", dir,
"--manager", "npm",
"--manager-path", "npm",
"--target", "0.6.0",
"--kind", "app",
"--systemd-unit", "ompweb.service",
"--systemd-user", "1",
], { env: { ...process.env, PATH: `${dir}${delimiter}${process.env.PATH}` }, timeout: 20000 });
assert.equal(result.status, 0, String(result.stderr));
return {
calls: readFileSync(log, "utf8").trim().split("\n"),
status: JSON.parse(readFileSync(join(dir, "status.json"), "utf8")),
};
}

test("a systemd update stops the unit, installs, starts it and checks it stayed up", { skip: process.platform === "win32" }, (t) => {
const { calls, status } = runWorker(t);
assert.deepEqual(calls, [
"systemctl --user stop ompweb.service",
"npm install -g @kahme247/ompweb@0.6.0",
"systemctl --user start ompweb.service",
"systemctl --user is-active ompweb.service",
]);
assert.equal(status.state, "succeeded");
});

test("a failed install starts the unit again", { skip: process.platform === "win32" }, (t) => {
const { calls, status } = runWorker(t, { npmExit: 1 });
assert.equal(calls.at(-1), "systemctl --user start ompweb.service");
assert.equal(status.state, "failed");
assert.match(status.error, /package install failed/);
});

test("a unit that will not start again is reported as stopped", { skip: process.platform === "win32" }, (t) => {
const { status } = runWorker(t, { startExit: 1 });
assert.equal(status.state, "failed");
assert.match(status.error, /^ompweb\.service is still stopped: /);
});

test("a new release that does not stay up fails the update", { skip: process.platform === "win32" }, (t) => {
const { status } = runWorker(t, { activeExit: 3 });
assert.equal(status.state, "failed");
assert.match(status.error, /systemctl is-active ompweb\.service failed: failed/);
});
116 changes: 116 additions & 0 deletions lib/self-update.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import test from "node:test";
import { createJiti } from "jiti";

const jiti = createJiti(import.meta.url, {
alias: {
"@/": new URL("../", import.meta.url).pathname,
},
});
const {
getSelfUpdateStatus,
markSelfUpdateStopping,
parseSystemdServiceCgroup,
resolveSelfUpdateTempRoot,
validateCommitSelfUpdate,
} = await jiti.import("./self-update.ts");

test("parseSystemdServiceCgroup finds system and user services, and nothing outside one", () => {
assert.deepEqual(parseSystemdServiceCgroup("0::/system.slice/ompweb-api.service\n"), { unit: "ompweb-api.service", user: false });
assert.deepEqual(
parseSystemdServiceCgroup("0::/user.slice/user-1000.slice/user@1000.service/app.slice/ompweb.service\n"),
{ unit: "ompweb.service", user: true },
);
assert.deepEqual(
parseSystemdServiceCgroup("12:pids:/system.slice/x.service\n1:name=systemd:/system.slice/ompweb.service\n"),
{ unit: "ompweb.service", user: false },
);
assert.deepEqual(
parseSystemdServiceCgroup("1:name=systemd:/system.slice/ompweb.service\n0::/\n"),
{ unit: "ompweb.service", user: false },
);
assert.equal(parseSystemdServiceCgroup("0::/user.slice/user-1000.slice/session-3.scope\n"), null);
assert.equal(parseSystemdServiceCgroup("0::/user.slice/user-1000.slice/user@1000.service/app.slice/tmux-spawn-1.scope\n"), null);
assert.equal(parseSystemdServiceCgroup(""), null);
});

function withUpdateState(t, { workerPid, leaseExpiresAt, state = "running" }) {
const temporary = mkdtempSync(join(tmpdir(), "self-update-test-"));
// os.tmpdir() reads TMPDIR on POSIX and TEMP/TMP on Windows.
const names = ["TMPDIR", "TEMP", "TMP"];
const previous = names.map((name) => process.env[name]);
for (const name of names) process.env[name] = temporary;
t.after(() => {
names.forEach((name, index) => {
if (previous[index] === undefined) delete process.env[name];
else process.env[name] = previous[index];
});
rmSync(temporary, { recursive: true, force: true });
});
const root = resolveSelfUpdateTempRoot("app");
mkdirSync(root, { mode: 0o700 });
const attemptId = "2e4c6460-5a8f-4ef7-8d81-42cb688a8bdc";
if (leaseExpiresAt !== null) {
writeFileSync(join(root, "lease.json"), JSON.stringify({ attemptId, kind: "app", expiresAt: leaseExpiresAt }), { mode: 0o600 });
}
writeFileSync(join(root, `${attemptId}.ready`), "{}", { mode: 0o600 });
writeFileSync(join(root, "status.json"), JSON.stringify({
attemptId,
state,
...(state === "running" ? { stage: "stopping" } : {}),
fromVersion: "0.5.2",
targetVersion: "0.6.0",
preparedAt: new Date().toISOString(),
workerPid,
}), { mode: 0o600 });
return { statusFile: join(root, "status.json"), leaseFile: join(root, "lease.json"), attemptId };
}

// A pid far above any pid_max, so it is never alive.
const DEAD_PID = 2 ** 30;

test("a running update whose worker died is reported, and stored, as failed", (t) => {
const { statusFile } = withUpdateState(t, { workerPid: DEAD_PID, leaseExpiresAt: Date.now() + 60_000 });
const status = getSelfUpdateStatus("app");
assert.equal(status.state, "failed");
assert.equal(status.cleanupReady, true);
assert.match(status.error, /worker stopped/);
assert.equal(JSON.parse(readFileSync(statusFile, "utf8")).state, "failed");
});

test("a running update past its lease is failed even when its pid is alive (reused)", (t) => {
withUpdateState(t, { workerPid: process.pid, leaseExpiresAt: Date.now() - 1 });
assert.equal(getSelfUpdateStatus("app").state, "failed");
});

test("a running update with a live worker inside its lease stays running", (t) => {
const { statusFile } = withUpdateState(t, { workerPid: process.pid, leaseExpiresAt: Date.now() + 60_000 });
assert.equal(getSelfUpdateStatus("app").state, "running");
assert.equal(JSON.parse(readFileSync(statusFile, "utf8")).state, "running");
});

test("a running update before its worker pid is recorded stays running", (t) => {
withUpdateState(t, { workerPid: undefined, leaseExpiresAt: Date.now() + 60_000 });
assert.equal(getSelfUpdateStatus("app").state, "running");
});

test("a running update without a lease is failed", (t) => {
withUpdateState(t, { workerPid: process.pid, leaseExpiresAt: null });
assert.equal(getSelfUpdateStatus("app").state, "failed");
});

test("a prepared update whose lease expired cannot be committed", (t) => {
const { attemptId } = withUpdateState(t, { state: "prepared", leaseExpiresAt: Date.now() - 1 });
assert.throws(() => validateCommitSelfUpdate(attemptId, "app"), { code: "lease_expired" });
});

test("starting a commit renews the lease, so a late commit is not reported as lost", (t) => {
const { attemptId, leaseFile } = withUpdateState(t, { state: "prepared", leaseExpiresAt: Date.now() + 1_000 });
assert.equal(validateCommitSelfUpdate(attemptId, "app"), "ready");
markSelfUpdateStopping(attemptId, "app");
assert.ok(JSON.parse(readFileSync(leaseFile, "utf8")).expiresAt > Date.now() + 10 * 60_000);
assert.equal(getSelfUpdateStatus("app").state, "running");
});
Loading
Loading