Files
seal-use/src/cli/service.ts
T

176 lines
4.7 KiB
TypeScript

import { spawn, execFileSync } from "node:child_process";
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
export type ServiceConfig = {
appRoot: string;
entryFile: string;
stateDir: string;
version?: string;
launcher?: {
command: string;
args?: string[];
};
};
export async function runServiceCommand(
action: string | undefined,
config: ServiceConfig,
options: { quiet?: boolean } = {}
) {
switch (action) {
case "run":
await runService(config);
return undefined;
case "start":
return startService(config);
case "stop":
return stopService(config, options);
case "restart":
stopService(config, { quiet: true });
return startService(config);
case "status":
case undefined:
return serviceStatus(config);
default:
throw new Error("Usage: seal-use service <start|stop|restart|status>");
}
}
export function serviceStatus(config: ServiceConfig) {
const pidFile = getPidFile(config);
const pid = readServicePid(pidFile);
const running = pid ? isSealHomeProcess(pid, config.appRoot) : false;
if (pid && !running) {
rmSync(pidFile, { force: true });
}
return {
running,
pid: running ? pid : undefined,
version: config.version,
appRoot: config.appRoot,
stateDir: config.stateDir,
pidFile,
logFile: getLogFile(config)
};
}
async function runService(config: ServiceConfig) {
const pidFile = getPidFile(config);
const logFile = getLogFile(config);
ensureStateDir(config.stateDir);
writeFileSync(pidFile, `${process.pid}\n`, { mode: 0o600 });
appendLog(logFile, `running pid=${process.pid}`);
const cleanup = () => {
if (readServicePid(pidFile) === process.pid) {
rmSync(pidFile, { force: true });
}
appendLog(logFile, `stopped pid=${process.pid}`);
};
await new Promise<void>((resolve) => {
let stopped = false;
const heartbeat = setInterval(() => {}, 60_000);
const stop = () => {
if (stopped) return;
stopped = true;
cleanup();
clearInterval(heartbeat);
process.off("SIGTERM", stop);
process.off("SIGINT", stop);
resolve();
};
process.once("SIGTERM", stop);
process.once("SIGINT", stop);
});
}
function startService(config: ServiceConfig) {
ensureStateDir(config.stateDir);
const current = serviceStatus(config);
if (current.running) {
return current;
}
const launcher = config.launcher ?? { command: process.execPath, args: [config.entryFile] };
const child = spawn(launcher.command, [
...(launcher.args ?? []),
"service",
"run"
], {
cwd: config.appRoot,
detached: true,
stdio: ["ignore", "ignore", "ignore"],
env: process.env
});
child.unref();
const pidFile = getPidFile(config);
writeFileSync(pidFile, `${child.pid}\n`, { mode: 0o600 });
appendLog(getLogFile(config), `started pid=${child.pid}`);
return { started: true, ...serviceStatus(config) };
}
function stopService(config: ServiceConfig, options: { quiet?: boolean } = {}) {
const pidFile = getPidFile(config);
const pid = readServicePid(pidFile);
if (!pid || !isSealHomeProcess(pid, config.appRoot)) {
rmSync(pidFile, { force: true });
return options.quiet ? undefined : { stopped: false, reason: "not running" };
}
process.kill(pid, "SIGTERM");
rmSync(pidFile, { force: true });
appendLog(getLogFile(config), `stop requested pid=${pid}`);
return options.quiet ? undefined : { stopped: true, pid };
}
function isSealHomeProcess(pid: number, appRoot: string) {
if (!isProcessRunning(pid)) return false;
try {
const command = execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" });
const matchesTarget =
command.includes(appRoot) ||
command.includes("seal-use") ||
command.includes("src/cli.ts");
return matchesTarget && command.includes("service") && command.includes("run");
} catch {
return false;
}
}
function isProcessRunning(pid: number) {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
function getPidFile(config: ServiceConfig) {
return join(config.stateDir, "service.pid");
}
function getLogFile(config: ServiceConfig) {
return join(config.stateDir, "service.log");
}
function readServicePid(path: string): number | undefined {
if (!existsSync(path)) return undefined;
const pid = Number(readFileSync(path, "utf8").trim());
return Number.isInteger(pid) && pid > 0 ? pid : undefined;
}
function ensureStateDir(stateDir: string) {
mkdirSync(stateDir, { recursive: true, mode: 0o700 });
}
function appendLog(path: string, message: string) {
writeFileSync(path, `${new Date().toISOString()} ${message}\n`, { flag: "a", mode: 0o600 });
}