Skip to content

Commit f39b179

Browse files
fix(cli): an update never replaces the CLI's files while a hyperframes command is running (#4637)
* fix(cli): an update never replaces the CLI's files while a hyperframes command is running * fix(cli): a killed command's leftover pid file cannot hold updates back * fix(cli): judge a stale pid file by the installer's own clock, so sleep cannot drop a live command * fix(cli): after a sleep the installer watches every command's file afresh * docs(cli): shorten the installer script comment * docs(cli): keep the new files within their comment share * refactor(cli): split the upgrade eligibility check out of the installer scheduler * docs(cli): keep the scheduler's doc on the scheduler
1 parent 5969c68 commit f39b179

5 files changed

Lines changed: 376 additions & 41 deletions

File tree

‎packages/cli/src/cli.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,9 @@ import {
116116
registerRootExitRequester,
117117
type CommandResult,
118118
} from "./utils/commandResult.js";
119+
import { registerRunningCli } from "./utils/runningCli.js";
120+
121+
registerRunningCli();
119122

120123
const isHelp = process.argv.includes("--help") || process.argv.includes("-h");
121124

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
import { spawn, type ChildProcess } from "node:child_process";
2+
import {
3+
existsSync,
4+
mkdirSync,
5+
mkdtempSync,
6+
readFileSync,
7+
rmSync,
8+
utimesSync,
9+
writeFileSync,
10+
} from "node:fs";
11+
import { tmpdir } from "node:os";
12+
import { join } from "node:path";
13+
import { afterEach, expect, it } from "vitest";
14+
import { installerScript } from "./autoUpdate.js";
15+
16+
// Runs the real detached-installer script; the "install" only writes a marker file.
17+
const dirs: string[] = [];
18+
const children: ChildProcess[] = [];
19+
20+
afterEach(() => {
21+
for (const child of children.splice(0)) child.kill();
22+
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
23+
});
24+
25+
function setup(staleMs = 60_000) {
26+
const dir = mkdtempSync(join(tmpdir(), "hf-installer-"));
27+
dirs.push(dir);
28+
const runningDir = join(dir, "running");
29+
mkdirSync(runningDir);
30+
const marker = join(dir, "installed");
31+
const script = installerScript({
32+
configFile: join(dir, "config.json"),
33+
version: "9.9.9",
34+
bin: process.execPath,
35+
args: ["-e", `require("node:fs").writeFileSync(${JSON.stringify(marker)}, "")`],
36+
runningDir,
37+
pollMs: 50,
38+
maxWaitMs: 60_000,
39+
staleMs,
40+
});
41+
return { dir, runningDir, marker, script };
42+
}
43+
44+
function start(args: string[]): ChildProcess {
45+
const child = spawn(process.execPath, args, { stdio: "ignore" });
46+
children.push(child);
47+
return child;
48+
}
49+
50+
const exited = (child: ChildProcess) =>
51+
child.exitCode !== null || child.signalCode !== null
52+
? Promise.resolve()
53+
: new Promise<void>((resolve) => child.once("exit", () => resolve()));
54+
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
55+
56+
async function until(check: () => boolean): Promise<void> {
57+
while (!check()) await sleep(25);
58+
}
59+
60+
function backdate(file: string): void {
61+
const tenMinutesAgo = new Date(Date.now() - 10 * 60_000);
62+
utimesSync(file, tenMinutesAgo, tenMinutesAgo);
63+
}
64+
65+
async function expectInstalledAndRemoved(script: string, marker: string, file: string) {
66+
await exited(start(["-e", script]));
67+
expect(existsSync(marker)).toBe(true);
68+
expect(existsSync(file)).toBe(false);
69+
}
70+
71+
function registerCli(runningDir: string): ChildProcess {
72+
const cli = start(["-e", "setInterval(() => {}, 1000)"]);
73+
writeFileSync(join(runningDir, String(cli.pid)), "");
74+
return cli;
75+
}
76+
77+
it("never replaces package files while a CLI process is running, then installs once it exits", async () => {
78+
const { dir, runningDir, marker, script } = setup();
79+
const cli = registerCli(runningDir);
80+
const installer = start(["-e", script]);
81+
82+
await sleep(1000);
83+
expect(existsSync(marker)).toBe(false);
84+
85+
cli.kill();
86+
await exited(installer);
87+
expect(existsSync(marker)).toBe(true);
88+
expect(JSON.parse(readFileSync(join(dir, "config.json"), "utf-8")).completedUpdate).toMatchObject(
89+
{ version: "9.9.9", ok: true },
90+
);
91+
});
92+
93+
it("does not wait on a CLI process that died without cleaning up", async () => {
94+
const { runningDir, marker, script } = setup();
95+
const dead = start(["-e", ""]);
96+
await exited(dead);
97+
const staleFile = join(runningDir, String(dead.pid));
98+
writeFileSync(staleFile, "");
99+
100+
await expectInstalledAndRemoved(script, marker, staleFile);
101+
});
102+
103+
it("keeps waiting on a live command whose file looks old after the machine slept", async () => {
104+
const { runningDir, marker, script } = setup();
105+
const cli = registerCli(runningDir);
106+
const file = join(runningDir, String(cli.pid));
107+
backdate(file);
108+
const installer = start(["-e", script]);
109+
110+
await sleep(1000);
111+
expect(existsSync(marker)).toBe(false);
112+
expect(existsSync(file)).toBe(true);
113+
114+
cli.kill();
115+
await exited(installer);
116+
expect(existsSync(marker)).toBe(true);
117+
});
118+
119+
it("drops a pid file whose pid belongs to another process once it stops changing", async () => {
120+
const { runningDir, marker, script } = setup(300);
121+
const other = start(["-e", "setInterval(() => {}, 1000)"]);
122+
const staleFile = join(runningDir, String(other.pid));
123+
writeFileSync(staleFile, "");
124+
backdate(staleFile);
125+
126+
await expectInstalledAndRemoved(script, marker, staleFile);
127+
});
128+
129+
it("lets only one installer wait: a later launch exits and installs nothing", async () => {
130+
const { dir, runningDir, marker, script } = setup();
131+
const cli = registerCli(runningDir);
132+
const first = start(["-e", script]);
133+
await until(() => existsSync(join(dir, "config.json.install-lock")));
134+
135+
await exited(start(["-e", script]));
136+
expect(existsSync(marker)).toBe(false);
137+
138+
cli.kill();
139+
await exited(first);
140+
expect(existsSync(marker)).toBe(true);
141+
});
142+
143+
it("takes over an install lock whose pid belongs to another process once it stops changing", async () => {
144+
const { dir, marker, script } = setup(300);
145+
const other = start(["-e", "setInterval(() => {}, 1000)"]);
146+
const lock = join(dir, "config.json.install-lock");
147+
writeFileSync(lock, String(other.pid));
148+
backdate(lock);
149+
150+
await exited(start(["-e", script]));
151+
expect(existsSync(marker)).toBe(true);
152+
});

‎packages/cli/src/utils/autoUpdate.ts‎

Lines changed: 144 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import { compareVersions } from "compare-versions";
3131
import { withFileLock } from "../media-use/lib/config-lock.mjs";
3232
import { readConfig, writeConfig } from "../telemetry/config.js";
3333
import { updateCheckDisabled } from "./updateCheck.js";
34+
import { RUNNING_DIR, RUNNING_STALE_MS } from "./runningCli.js";
3435
import {
3536
detectInstaller,
3637
installInvocation,
@@ -41,6 +42,9 @@ const CONFIG_DIR = join(homedir(), ".hyperframes");
4142
const LOG_FILE = join(CONFIG_DIR, "auto-update.log");
4243
/** An install that hasn't finished after this many ms is considered stuck. */
4344
const PENDING_TIMEOUT_MS = 10 * 60 * 1000;
45+
/** A waiting installer gives up after this long; the next run schedules it again. */
46+
const INSTALL_MAX_WAIT_MS = 60 * 60 * 1000;
47+
const INSTALL_POLL_MS = 2_000;
4448

4549
function isAutoInstallDisabled(): boolean {
4650
return updateCheckDisabled() || process.env["HYPERFRAMES_NO_AUTO_INSTALL"] === "1";
@@ -65,6 +69,125 @@ function log(line: string): void {
6569
}
6670
}
6771

72+
export interface InstallerScriptOptions {
73+
configFile: string;
74+
version: string;
75+
bin: string;
76+
args: readonly string[];
77+
runningDir: string;
78+
pollMs: number;
79+
maxWaitMs: number;
80+
/** A pid or install-lock file not touched for this long belongs to a dead process. */
81+
staleMs: number;
82+
}
83+
84+
/** The detached installer, run via `node -e`: waits until no CLI in `runningDir` is alive, then
85+
* installs with execFile (no shell) and records completedUpdate under the settings lock. */
86+
export function installerScript(o: InstallerScriptOptions): string {
87+
return `
88+
const { execFile } = require("node:child_process");
89+
const fs = require("node:fs");
90+
const { join } = require("node:path");
91+
const { readFileSync, renameSync, writeFileSync } = fs;
92+
const CFG = ${JSON.stringify(o.configFile)};
93+
const TMP = \`\${CFG}.tmp\`;
94+
const INSTALL_LOCK = \`\${CFG}.install-lock\`;
95+
const RUNNING = ${JSON.stringify(o.runningDir)};
96+
const VERSION = ${JSON.stringify(o.version)};
97+
const BIN = ${JSON.stringify(o.bin)};
98+
const ARGS = ${JSON.stringify(o.args)};
99+
const withFileLock = ${withFileLock.toString()};
100+
const withLock = (task) => { try { withFileLock(\`\${CFG}.lock\`, fs, task); } catch (e) {} };
101+
const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === "EPERM"; } };
102+
// Stale = no heartbeat for staleMs on this process's own clock, which stops while the machine sleeps.
103+
const seen = new Map();
104+
const mono = () => Number(process.hrtime.bigint() / 1000000n);
105+
const observe = (file) => {
106+
let mtime;
107+
try { mtime = fs.statSync(file).mtimeMs; } catch (e) { return "stale"; }
108+
const prev = seen.get(file);
109+
if (prev && prev.mtime === mtime) return mono() - prev.at >= ${o.staleMs} ? "stale" : "quiet";
110+
seen.set(file, { mtime, at: mono() });
111+
return prev ? "beating" : "quiet";
112+
};
113+
const touch = (file) => { try { const now = new Date(); fs.utimesSync(file, now, now); } catch (e) {} };
114+
const running = () => {
115+
let names = [];
116+
try { names = fs.readdirSync(RUNNING); } catch (e) {}
117+
return names.filter((name) => {
118+
const pid = Number(name);
119+
const file = join(RUNNING, name);
120+
if (Number.isInteger(pid) && pid > 0 && alive(pid) && observe(file) !== "stale") return true;
121+
try { fs.unlinkSync(file); } catch (e) {}
122+
return false;
123+
});
124+
};
125+
let lockBeat;
126+
const ownsLock = () => { try { return Number(readFileSync(INSTALL_LOCK, "utf-8")) === process.pid; } catch (e) { return false; } };
127+
// Under the settings lock, so two installers launched together cannot both take it over.
128+
const tryLock = () => {
129+
let result = "stuck";
130+
withLock(() => {
131+
let owner = NaN;
132+
try { owner = Number(readFileSync(INSTALL_LOCK, "utf-8")); } catch (e) {}
133+
const state = Number.isInteger(owner) && owner > 0 && alive(owner) ? observe(INSTALL_LOCK) : "stale";
134+
if (state !== "stale") { result = state; return; }
135+
writeFileSync(INSTALL_LOCK, String(process.pid));
136+
result = "taken";
137+
});
138+
return result;
139+
};
140+
const releaseInstallLock = () => {
141+
clearInterval(lockBeat);
142+
if (ownsLock()) { try { fs.unlinkSync(INSTALL_LOCK); } catch (e) {} }
143+
};
144+
const install = () => execFile(BIN, ARGS, { windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (err, _stdout, stderr) => {
145+
withLock(() => {
146+
let cfg = {};
147+
try { cfg = JSON.parse(readFileSync(CFG, "utf-8")); } catch (e) { if (e.code !== "ENOENT") return; }
148+
cfg.completedUpdate = {
149+
version: VERSION,
150+
ok: !err,
151+
finishedAt: new Date().toISOString(),
152+
...(err ? { error: String(stderr || err.message || "install failed").slice(-400) } : {}),
153+
};
154+
delete cfg.pendingUpdate;
155+
try {
156+
writeFileSync(TMP, JSON.stringify(cfg, null, 2) + "\\n", { mode: 0o600 });
157+
renameSync(TMP, CFG);
158+
} catch (e) {}
159+
});
160+
releaseInstallLock();
161+
});
162+
const started = Date.now();
163+
let lastPoll = Date.now();
164+
const waitThenInstall = () => {
165+
if (!ownsLock()) return releaseInstallLock();
166+
// A long gap between polls means the machine slept: watch every file afresh.
167+
if (Date.now() - lastPoll > ${o.pollMs} * 5) seen.clear();
168+
lastPoll = Date.now();
169+
if (running().length === 0) return install();
170+
if (Date.now() - started > ${o.maxWaitMs}) {
171+
console.log(\`[wait] gave up on \${VERSION}: a hyperframes process is still running\`);
172+
return releaseInstallLock();
173+
}
174+
setTimeout(waitThenInstall, ${o.pollMs});
175+
};
176+
const acquire = () => {
177+
const result = tryLock();
178+
if (result === "taken") {
179+
lockBeat = setInterval(() => ownsLock() && touch(INSTALL_LOCK), ${o.pollMs});
180+
return waitThenInstall();
181+
}
182+
if (result === "quiet") return setTimeout(acquire, ${o.pollMs});
183+
console.log(result === "beating"
184+
? \`[wait] another installer is already waiting; leaving \${VERSION} to it\`
185+
: \`[wait] settings lock busy; \${VERSION} left for the next run\`);
186+
};
187+
acquire();
188+
`;
189+
}
190+
68191
/**
69192
* Spawn a detached child to run the install command. Stdout/stderr land in
70193
* the log file; the child is `unref()`d so the parent exits immediately
@@ -83,41 +206,16 @@ function launchDetachedInstall(
83206
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
84207
const configFile = join(CONFIG_DIR, "config.json");
85208

86-
// The child script:
87-
// 1. Runs the install via execFile (bin + argv, NO shell) so a version
88-
// string can never be re-interpreted as shell syntax — structural
89-
// symmetry with the interactive `runDetectedInstall` path.
90-
// 2. Under the shared settings lock (withFileLock, embedded as source), rewrites the config with
91-
// completedUpdate and clears pendingUpdate; skips on lock timeout or an unreadable file.
92-
// We run it through `node -e` so we don't need to ship a separate file. Bin
93-
// and args are embedded as JSON literals (data, not code).
94-
const nodeScript = `
95-
const { execFile } = require("node:child_process");
96-
const fs = require("node:fs");
97-
const { readFileSync, renameSync, writeFileSync } = fs;
98-
const CFG = ${JSON.stringify(configFile)};
99-
const TMP = \`\${CFG}.tmp\`;
100-
const VERSION = ${JSON.stringify(version)};
101-
const BIN = ${JSON.stringify(invocation.bin)};
102-
const ARGS = ${JSON.stringify(invocation.args)};
103-
const withFileLock = ${withFileLock.toString()};
104-
const withLock = (task) => { try { withFileLock(\`\${CFG}.lock\`, fs, task); } catch (e) {} };
105-
execFile(BIN, ARGS, { windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (err, _stdout, stderr) => withLock(() => {
106-
let cfg = {};
107-
try { cfg = JSON.parse(readFileSync(CFG, "utf-8")); } catch (e) { if (e.code !== "ENOENT") return; }
108-
cfg.completedUpdate = {
109-
version: VERSION,
110-
ok: !err,
111-
finishedAt: new Date().toISOString(),
112-
...(err ? { error: String(stderr || err.message || "install failed").slice(-400) } : {}),
113-
};
114-
delete cfg.pendingUpdate;
115-
try {
116-
writeFileSync(TMP, JSON.stringify(cfg, null, 2) + "\\n", { mode: 0o600 });
117-
renameSync(TMP, CFG);
118-
} catch (e) {}
119-
}));
120-
`;
209+
const nodeScript = installerScript({
210+
configFile,
211+
version,
212+
bin: invocation.bin,
213+
args: invocation.args,
214+
runningDir: RUNNING_DIR,
215+
pollMs: INSTALL_POLL_MS,
216+
maxWaitMs: INSTALL_MAX_WAIT_MS,
217+
staleMs: RUNNING_STALE_MS,
218+
});
121219

122220
const out = openSync(LOG_FILE, "a", 0o600);
123221
const child = spawn(process.execPath, ["-e", nodeScript], {
@@ -130,12 +228,7 @@ function launchDetachedInstall(
130228
log(`[launch] pid=${child.pid ?? "?"} cmd=${displayCommand} version=${version}`);
131229
}
132230

133-
/**
134-
* If a new version is available and policy allows, kick off a detached
135-
* installer. Returns whether an install was spawned (for tests).
136-
*/
137-
export function scheduleBackgroundInstall(latestVersion: string, currentVersion: string): boolean {
138-
if (isAutoInstallDisabled()) return false;
231+
function isSilentUpgrade(latestVersion: string, currentVersion: string): boolean {
139232
if (!latestVersion || !currentVersion) return false;
140233

141234
let cmp: number;
@@ -155,6 +248,16 @@ export function scheduleBackgroundInstall(latestVersion: string, currentVersion:
155248
log(`[skip] major-bump ${currentVersion} -> ${latestVersion}`);
156249
return false;
157250
}
251+
return true;
252+
}
253+
254+
/**
255+
* If a new version is available and policy allows, kick off a detached
256+
* installer. Returns whether an install was spawned (for tests).
257+
*/
258+
export function scheduleBackgroundInstall(latestVersion: string, currentVersion: string): boolean {
259+
if (isAutoInstallDisabled()) return false;
260+
if (!isSilentUpgrade(latestVersion, currentVersion)) return false;
158261

159262
const installer = detectInstaller();
160263
if (installer.kind === "skip") {

0 commit comments

Comments
 (0)