279 lines
8.1 KiB
TypeScript
279 lines
8.1 KiB
TypeScript
import { spawn, execFileSync } from "node:child_process";
|
|
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
import { startHttpServer, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST } from "../http/server.js";
|
|
|
|
export type ServiceConfig = {
|
|
appRoot: string;
|
|
entryFile: string;
|
|
stateDir: string;
|
|
version?: string;
|
|
launcher?: {
|
|
command: string;
|
|
args?: string[];
|
|
};
|
|
port?: number;
|
|
host?: string;
|
|
};
|
|
|
|
export async function runServiceCommand(
|
|
action: string | undefined,
|
|
config: ServiceConfig,
|
|
options: { quiet?: boolean; maxLines?: number } = {}
|
|
) {
|
|
switch (action) {
|
|
case "run":
|
|
await runService(config);
|
|
return undefined;
|
|
case "start":
|
|
return startService(config);
|
|
case "stop":
|
|
case "kill":
|
|
case "down":
|
|
case "shutdown":
|
|
return stopService(config, options);
|
|
case "restart":
|
|
stopService(config, { quiet: true });
|
|
return startService(config);
|
|
case "logs":
|
|
case "log":
|
|
return readServiceLogs(config, options.maxLines);
|
|
case "status":
|
|
case undefined:
|
|
return serviceStatus(config);
|
|
default:
|
|
throw new Error("Usage: seal-use service <start|stop|restart|status|logs>");
|
|
}
|
|
}
|
|
|
|
export function serviceStatus(config: ServiceConfig) {
|
|
const pidFile = getPidFile(config);
|
|
const metaFile = getMetaFile(config);
|
|
const pid = readServicePid(pidFile);
|
|
const running = pid ? isSealHomeProcess(pid, config.appRoot) : false;
|
|
|
|
if (!running) {
|
|
if (pid) rmSync(pidFile, { force: true });
|
|
if (existsSync(metaFile)) rmSync(metaFile, { force: true });
|
|
}
|
|
|
|
let storedMeta: { port?: number; host?: string; version?: string } | undefined;
|
|
if (running && existsSync(metaFile)) {
|
|
try {
|
|
storedMeta = JSON.parse(readFileSync(metaFile, "utf8"));
|
|
} catch {
|
|
// ignore
|
|
}
|
|
}
|
|
|
|
const port = config.port ?? storedMeta?.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
|
|
const host = config.host ?? storedMeta?.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
|
|
const version = config.version ?? storedMeta?.version;
|
|
|
|
return {
|
|
running,
|
|
pid: running ? pid : undefined,
|
|
version,
|
|
port,
|
|
host,
|
|
url: running ? `http://${host}:${port}` : undefined,
|
|
appRoot: config.appRoot,
|
|
stateDir: config.stateDir,
|
|
pidFile,
|
|
logFile: getLogFile(config)
|
|
};
|
|
}
|
|
|
|
export function readServiceLogs(config: ServiceConfig, maxLines = 50) {
|
|
const logFile = getLogFile(config);
|
|
if (!existsSync(logFile)) {
|
|
return {
|
|
logFile,
|
|
lines: [],
|
|
totalLines: 0
|
|
};
|
|
}
|
|
const content = readFileSync(logFile, "utf8");
|
|
const allLines = content.split("\n").filter(Boolean);
|
|
const lines = allLines.slice(-maxLines);
|
|
return {
|
|
logFile,
|
|
lines,
|
|
totalLines: allLines.length
|
|
};
|
|
}
|
|
|
|
async function runService(config: ServiceConfig) {
|
|
const pidFile = getPidFile(config);
|
|
const metaFile = getMetaFile(config);
|
|
const logFile = getLogFile(config);
|
|
ensureStateDir(config.stateDir);
|
|
|
|
const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
|
|
const host = config.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
|
|
|
|
writeFileSync(pidFile, `${process.pid}\n`, { mode: 0o600 });
|
|
writeFileSync(
|
|
metaFile,
|
|
JSON.stringify(
|
|
{
|
|
pid: process.pid,
|
|
port,
|
|
host,
|
|
version: config.version,
|
|
startedAt: new Date().toISOString()
|
|
},
|
|
null,
|
|
2
|
|
),
|
|
{ mode: 0o600 }
|
|
);
|
|
|
|
appendLog(logFile, `service starting on http://${host}:${port} pid=${process.pid}`);
|
|
|
|
let server: Awaited<ReturnType<typeof startHttpServer>> | null = null;
|
|
try {
|
|
server = await startHttpServer({ port, host, silent: true });
|
|
appendLog(logFile, `service listening pid=${process.pid}`);
|
|
} catch (err: unknown) {
|
|
appendLog(logFile, `service failed to bind port ${port}: ${err instanceof Error ? err.message : String(err)}`);
|
|
if (readServicePid(pidFile) === process.pid) {
|
|
rmSync(pidFile, { force: true });
|
|
rmSync(metaFile, { force: true });
|
|
}
|
|
throw err;
|
|
}
|
|
|
|
const cleanup = () => {
|
|
if (server) {
|
|
server.close();
|
|
server = null;
|
|
}
|
|
if (readServicePid(pidFile) === process.pid) {
|
|
rmSync(pidFile, { force: true });
|
|
rmSync(metaFile, { force: true });
|
|
}
|
|
appendLog(logFile, `stopped pid=${process.pid}`);
|
|
};
|
|
|
|
await new Promise<void>((resolve) => {
|
|
let stopped = false;
|
|
const stop = () => {
|
|
if (stopped) return;
|
|
stopped = true;
|
|
cleanup();
|
|
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 serviceArgs = [
|
|
...(launcher.args ?? []),
|
|
"service",
|
|
"run"
|
|
];
|
|
if (config.port) serviceArgs.push("--port", String(config.port));
|
|
if (config.host) serviceArgs.push("--host", String(config.host));
|
|
|
|
const child = spawn(launcher.command, serviceArgs, {
|
|
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 metaFile = getMetaFile(config);
|
|
const pid = readServicePid(pidFile);
|
|
if (!pid || !isSealHomeProcess(pid, config.appRoot)) {
|
|
rmSync(pidFile, { force: true });
|
|
rmSync(metaFile, { force: true });
|
|
return options.quiet ? undefined : { stopped: false, reason: "not running" };
|
|
}
|
|
|
|
process.kill(pid, "SIGTERM");
|
|
rmSync(pidFile, { force: true });
|
|
rmSync(metaFile, { force: true });
|
|
appendLog(getLogFile(config), `stop requested pid=${pid}`);
|
|
return options.quiet ? undefined : { stopped: true, pid };
|
|
}
|
|
|
|
/**
|
|
* A pid file only proves that *some* process holds that pid. Match the recorded identity as argv
|
|
* tokens — the exact `service run` subcommand pair plus a path to this app or a seal-use launcher
|
|
* — instead of as substrings anywhere in the command line, so a stale pid cannot make an
|
|
* unrelated process look like our daemon and get signalled by `service stop`.
|
|
*/
|
|
function isSealHomeProcess(pid: number, appRoot: string) {
|
|
if (!isProcessRunning(pid)) return false;
|
|
|
|
try {
|
|
const command = execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" });
|
|
const tokens = command.trim().split(/\s+/).filter(Boolean);
|
|
|
|
const serviceIndex = tokens.indexOf("service");
|
|
const runsService = serviceIndex !== -1 && tokens[serviceIndex + 1] === "run";
|
|
const isSealUse =
|
|
command.includes(appRoot) || tokens.some((token) => /(^|[\\/])(seal-use|seal-home)(\.exe)?$/.test(token));
|
|
|
|
return runsService && isSealUse;
|
|
} 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 getMetaFile(config: ServiceConfig) {
|
|
return join(config.stateDir, "service.json");
|
|
}
|
|
|
|
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 });
|
|
}
|