mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-12-04 22:41:40 +09:00
* fix(proxy): bump pinned meta-proxy release 0.4.0 -> 0.7.3 `DEFAULT_PROXY_RELEASE` had not moved in six meta-proxy releases, so `ruflo proxy install` shipped a binary predating every fix since v0.4.0: - require explicit Cognitum Cloud routing consent (#60) first in v0.7.0 - handle --help before binding (#74/#76) first in v0.7.2 - --help/--version win from any argv position (#85) first in v0.7.3 - reload live daemon config on login/logout (#28) first in v0.4.1 - pin the Linux glibc floor to 2.28 (#66) first in v0.7.1 The consent one matters most: the install disclosure promises cloud routing is "never enabled by install alone", but the commit that separated authentication from routing consent landed in v0.7.0 — after the pinned build. The --version regression is directly observable on 0.4.0: the binary starts the daemon, writes the token file and binds 127.0.0.1:11435, where meta-proxy's own source documents --version as side-effect-free ("no server, no I/O"). Any probe silently leaves a listener running. Also stop hardcoding the version in proxy.ts's example text. That string was written as a literal rather than interpolating the constant, so the advertised version could — and did — drift from the installed one. Both tests now read the pin from the module for the same reason; asserting a literal means every bump needs hand-edited test expectations. Verified on Windows x64: `ruflo proxy install --release 0.7.3 --yes` installs with signature + checksum verification intact, and `--version` then prints and exits with no process left running and no port bound. Test: 9 proxy test files, 56 tests, all passing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(proxy): surface pin drift to already-installed users Bumping DEFAULT_PROXY_RELEASE only changed what a NEW install receives. Someone who had already run `proxy install` on 0.4.0 got no signal that anything moved: `proxy status` reported installation as a boolean, and `proxy update` required an explicit --release, so reaching a newer binary meant already knowing its version number. The fixes that motivated the bump therefore reached only the users who did not yet have the problem. ProxyStatus now carries `version`, read from the install manifest install.ts already writes. `proxy status` prints it, the console guidance names the gap and the command that closes it, and `proxy update` defaults to the pin the same way `install` does. Updating stays explicit and user-initiated. The version is read from the manifest, never by executing the binary: releases before v0.7.2 start the server and bind a port on ANY invocation, so a `--version` probe against an old build leaves a listener running -- precisely the state this check exists to detect. A missing or malformed manifest reports "unknown", never "up to date". Also corrects two stale claims this change makes load-bearing: - proxy/lifecycle.ts's header asserted as fact that the binary "takes no CLI flags -- no --version/--help, any invocation just starts the server" (confirmed 2026-07-16). v0.7.2 handles --help before binding and v0.7.3 makes --help/--version win from any argv position. Left as-is, the next reader concludes no version handshake is possible. - ADR-307 still described the pin as v0.4.0 -- a fourth copy of the literal this PR is de-duplicating, and the one a reviewer reads to decide what the pin should be. It now names no version at all and points at the constant, plus records the drift-surfacing behavior. Test: 9 proxy test files, 64 tests, all passing (was 56). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
302 lines
10 KiB
TypeScript
302 lines
10 KiB
TypeScript
/**
|
|
* meta-proxy process lifecycle (ADR-307) — start/stop/status/logs.
|
|
*
|
|
* Adapts daemon.ts's proven pattern (PID file, O_EXCL lockfile for atomic
|
|
* check-then-start, signal-0 liveness, SIGTERM->1000ms->SIGKILL) to a
|
|
* native binary instead of a forked Node process. `spawn()` here passes zero
|
|
* arguments, always — starting the server is the argument-free behavior and
|
|
* the only one this module wants.
|
|
*
|
|
* That is now a choice rather than a constraint. The 2026-07-16 note here
|
|
* ("the binary takes no CLI flags — no `--version`/`--help`, any invocation
|
|
* just starts the server") was true of the release pinned at the time, and
|
|
* stopped being true: meta-proxy v0.7.2 handles `--help` before binding, and
|
|
* v0.7.3 makes `--help`/`--version` win from any argv position. Do not read
|
|
* the old note as "the binary cannot be asked what it is" — it can. The
|
|
* installed version is still read from the install manifest rather than by
|
|
* executing the binary, because a filesystem read cannot start a listener
|
|
* and an exec of an old build can (a `--version` probe against 0.4.0 leaves
|
|
* a daemon bound to 127.0.0.1:11435).
|
|
*
|
|
* Foreground `start` (the ADR-307 default) uses `stdio: 'inherit'` and
|
|
* blocks directly — simplest and safest, no log-file redirection needed.
|
|
* `start --service` needs REAL file-descriptor redirection
|
|
* (`stdio: ['ignore', fd, fd]`) + `detached: true` + `unref()` via
|
|
* `child_process.spawn()` directly — `SafeExecutor.executeStreaming()`
|
|
* buffers output in-process, which is wrong for a process meant to outlive
|
|
* the `ruflo` invocation that started it.
|
|
*
|
|
* @module proxy/lifecycle
|
|
*/
|
|
|
|
import { spawn } from 'node:child_process';
|
|
import * as fs from 'node:fs';
|
|
import {
|
|
proxyBinaryPath,
|
|
proxyPidFilePath,
|
|
proxyLockFilePath,
|
|
proxyLogFilePath,
|
|
proxyInstallManifestPath,
|
|
type InstallManifest,
|
|
} from './paths.js';
|
|
|
|
export class ProxyNotInstalledError extends Error {
|
|
constructor() {
|
|
super('meta-proxy is not installed. Run: ruflo proxy install');
|
|
this.name = 'ProxyNotInstalledError';
|
|
}
|
|
}
|
|
|
|
export class ProxyAlreadyRunningError extends Error {
|
|
constructor(public readonly pid: number) {
|
|
super(`meta-proxy is already running (pid ${pid}). Stop it first with: ruflo proxy stop`);
|
|
this.name = 'ProxyAlreadyRunningError';
|
|
}
|
|
}
|
|
|
|
function requireBinary(): string {
|
|
const bin = proxyBinaryPath();
|
|
if (!fs.existsSync(bin)) throw new ProxyNotInstalledError();
|
|
return bin;
|
|
}
|
|
|
|
/** Signal-0 liveness probe — cross-platform in Node, throws if the process is dead. */
|
|
function isProcessRunning(pid: number): boolean {
|
|
try {
|
|
process.kill(pid, 0);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export interface ProxyStatus {
|
|
installed: boolean;
|
|
running: boolean;
|
|
pid: number | null;
|
|
stalePidFile: boolean;
|
|
/**
|
|
* The release recorded by the install that produced the binary on disk, or
|
|
* null when unknown — either nothing is installed, or the binary predates
|
|
* the manifest / the manifest was hand-removed. Callers must treat null as
|
|
* "cannot tell", never as "up to date".
|
|
*/
|
|
version: string | null;
|
|
}
|
|
|
|
/**
|
|
* The installed release, from `install.ts`'s manifest. Deliberately a
|
|
* filesystem read and not `meta-proxy --version`: exec'ing the binary to ask
|
|
* its version is exactly the probe that starts a listener on the older
|
|
* builds this is most needed to detect.
|
|
*
|
|
* Never throws — a missing, unreadable, or malformed manifest is a normal
|
|
* "unknown", not a reason to fail `proxy status`.
|
|
*/
|
|
function readInstalledVersion(): string | null {
|
|
try {
|
|
const raw = fs.readFileSync(proxyInstallManifestPath(), 'utf-8');
|
|
const manifest = JSON.parse(raw) as Partial<InstallManifest>;
|
|
return typeof manifest.version === 'string' && manifest.version ? manifest.version : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export function getProxyStatus(): ProxyStatus {
|
|
const installed = fs.existsSync(proxyBinaryPath());
|
|
const version = installed ? readInstalledVersion() : null;
|
|
const pidPath = proxyPidFilePath();
|
|
if (!fs.existsSync(pidPath)) {
|
|
return { installed, running: false, pid: null, stalePidFile: false, version };
|
|
}
|
|
const raw = fs.readFileSync(pidPath, 'utf-8').trim();
|
|
const pid = parseInt(raw, 10);
|
|
if (!Number.isFinite(pid)) {
|
|
return { installed, running: false, pid: null, stalePidFile: true, version };
|
|
}
|
|
const running = isProcessRunning(pid);
|
|
return { installed, running, pid: running ? pid : null, stalePidFile: !running, version };
|
|
}
|
|
|
|
function writePidFile(pid: number): void {
|
|
fs.writeFileSync(proxyPidFilePath(), String(pid), 'utf-8');
|
|
}
|
|
|
|
function clearStalePidFile(): void {
|
|
try {
|
|
fs.unlinkSync(proxyPidFilePath());
|
|
} catch {
|
|
// already absent
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Atomic check-then-start via an O_EXCL lockfile — the same fix daemon.ts
|
|
* applies for the identical race (#2407/#2484: without this, N concurrent
|
|
* `start` calls all see "not running" and all spawn their own process).
|
|
* Returns the lock fd to release once the PID file has been written (or on
|
|
* any early-return/throw), never before.
|
|
*/
|
|
function acquireStartLock(): number | null {
|
|
const lockFile = proxyLockFilePath();
|
|
try {
|
|
return fs.openSync(lockFile, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY);
|
|
} catch (e) {
|
|
if ((e as NodeJS.ErrnoException).code === 'EEXIST') return null; // another start is mid-spawn
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
function releaseStartLock(fd: number | null): void {
|
|
if (fd === null) return;
|
|
try {
|
|
fs.closeSync(fd);
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
try {
|
|
fs.unlinkSync(proxyLockFilePath());
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Foreground start (ADR-307 default) — blocks the caller until the process
|
|
* exits or is interrupted. `stdio: 'inherit'` passes the proxy's own output
|
|
* straight through to the terminal; signals (Ctrl+C) propagate naturally to
|
|
* the child, no manual forwarding needed.
|
|
*/
|
|
export async function startForeground(supervised = false): Promise<never> {
|
|
const bin = requireBinary();
|
|
const status = getProxyStatus();
|
|
// In service mode startBackground has already written this supervisor's
|
|
// PID. Treating it as a competing proxy makes the supervisor immediately
|
|
// exit before it can spawn meta-proxy.
|
|
if (!supervised && status.running && status.pid) throw new ProxyAlreadyRunningError(status.pid);
|
|
if (status.stalePidFile) clearStalePidFile();
|
|
|
|
const child = spawn(bin, [], { stdio: 'inherit', windowsHide: false });
|
|
if (!supervised && child.pid) writePidFile(child.pid);
|
|
|
|
const cleanup = () => clearStalePidFile();
|
|
process.on('exit', cleanup);
|
|
if (supervised) {
|
|
const forwardSignal = (signal: NodeJS.Signals) => {
|
|
if (!child.killed) child.kill(signal);
|
|
};
|
|
process.once('SIGTERM', () => forwardSignal('SIGTERM'));
|
|
process.once('SIGINT', () => forwardSignal('SIGINT'));
|
|
}
|
|
|
|
await new Promise<void>((resolve) => {
|
|
child.on('exit', () => {
|
|
cleanup();
|
|
resolve();
|
|
});
|
|
});
|
|
process.exit(0);
|
|
}
|
|
|
|
/**
|
|
* Background/`--service` start — detaches so the process outlives this
|
|
* `ruflo` invocation, redirecting stdout/stderr to a real log file (not
|
|
* buffered in-process). Returns once the child's PID is confirmed written,
|
|
* without waiting for the process to exit.
|
|
*/
|
|
export async function startBackground(): Promise<{ pid: number }> {
|
|
requireBinary();
|
|
const status = getProxyStatus();
|
|
if (status.running && status.pid) throw new ProxyAlreadyRunningError(status.pid);
|
|
|
|
const lockFd = acquireStartLock();
|
|
try {
|
|
// Re-check under the lock — the dedup above raced a concurrent starter.
|
|
const rechecked = getProxyStatus();
|
|
if (rechecked.running && rechecked.pid) throw new ProxyAlreadyRunningError(rechecked.pid);
|
|
if (rechecked.stalePidFile) clearStalePidFile();
|
|
|
|
const logFd = fs.openSync(proxyLogFilePath(), 'a');
|
|
const cliEntry = process.argv[1];
|
|
if (!cliEntry) throw new Error('cannot locate the ruflo CLI entrypoint for supervised service mode');
|
|
const child = spawn(process.execPath, [cliEntry, 'proxy', 'supervise'], {
|
|
stdio: ['ignore', logFd, logFd],
|
|
detached: true,
|
|
windowsHide: true,
|
|
});
|
|
fs.closeSync(logFd); // the child holds its own duplicated fd; safe to close ours
|
|
|
|
if (!child.pid) throw new Error('ruflo proxy supervisor failed to spawn — no PID returned');
|
|
writePidFile(child.pid);
|
|
child.unref();
|
|
return { pid: child.pid };
|
|
} finally {
|
|
releaseStartLock(lockFd);
|
|
}
|
|
}
|
|
|
|
export interface StopResult {
|
|
wasRunning: boolean;
|
|
pid: number | null;
|
|
}
|
|
|
|
/** SIGTERM -> 1000ms -> SIGKILL if still alive, mirroring daemon.ts's killBackgroundDaemon. */
|
|
export async function stopProxy(): Promise<StopResult> {
|
|
const status = getProxyStatus();
|
|
if (!status.running || !status.pid) {
|
|
if (status.stalePidFile) clearStalePidFile();
|
|
return { wasRunning: false, pid: null };
|
|
}
|
|
|
|
const pid = status.pid;
|
|
process.kill(pid, 'SIGTERM');
|
|
await new Promise((r) => setTimeout(r, 1000));
|
|
if (isProcessRunning(pid)) {
|
|
process.kill(pid, 'SIGKILL');
|
|
}
|
|
clearStalePidFile();
|
|
return { wasRunning: true, pid };
|
|
}
|
|
|
|
const TAIL_BYTES = 64 * 1024; // bounded read — a long-running proxy's log grows over weeks
|
|
|
|
export function readProxyLogTail(maxBytes: number = TAIL_BYTES): string {
|
|
const logPath = proxyLogFilePath();
|
|
if (!fs.existsSync(logPath)) return '';
|
|
const { size } = fs.statSync(logPath);
|
|
const start = Math.max(0, size - maxBytes);
|
|
const fd = fs.openSync(logPath, 'r');
|
|
try {
|
|
const buf = Buffer.alloc(size - start);
|
|
fs.readSync(fd, buf, 0, buf.length, start);
|
|
return buf.toString('utf-8');
|
|
} finally {
|
|
fs.closeSync(fd);
|
|
}
|
|
}
|
|
|
|
/** Streams new log lines as they're appended, starting from the current end of file. */
|
|
export function watchProxyLog(onLine: (line: string) => void): fs.FSWatcher {
|
|
const logPath = proxyLogFilePath();
|
|
if (!fs.existsSync(logPath)) {
|
|
throw new Error('no log file yet — meta-proxy has never been started in --service mode');
|
|
}
|
|
let offset = fs.statSync(logPath).size;
|
|
return fs.watch(logPath, () => {
|
|
const { size } = fs.statSync(logPath);
|
|
if (size <= offset) return;
|
|
const fd = fs.openSync(logPath, 'r');
|
|
try {
|
|
const buf = Buffer.alloc(size - offset);
|
|
fs.readSync(fd, buf, 0, buf.length, offset);
|
|
offset = size;
|
|
for (const line of buf.toString('utf-8').split('\n')) {
|
|
if (line.length > 0) onLine(line);
|
|
}
|
|
} finally {
|
|
fs.closeSync(fd);
|
|
}
|
|
});
|
|
}
|