Add persistent HTTP server to background service daemon
This commit is contained in:
1 parent
13ed555bbb
commit
f183cc8294
7 files changed
+237
-50
No files matched your search
+103
-12
@@ -1,6 +1,7 @@
|
||||
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;
|
||||
@@ -11,12 +12,14 @@ export type ServiceConfig = {
|
||||
command: string;
|
||||
args?: string[];
|
||||
};
|
||||
port?: number;
|
||||
host?: string;
|
||||
};
|
||||
|
||||
export async function runServiceCommand(
|
||||
action: string | undefined,
|
||||
config: ServiceConfig,
|
||||
options: { quiet?: boolean } = {}
|
||||
options: { quiet?: boolean; maxLines?: number } = {}
|
||||
) {
|
||||
switch (action) {
|
||||
case "run":
|
||||
@@ -29,27 +32,48 @@ export async function runServiceCommand(
|
||||
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>");
|
||||
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 (pid && !running) {
|
||||
rmSync(pidFile, { force: true });
|
||||
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: config.version,
|
||||
version,
|
||||
port,
|
||||
host,
|
||||
url: running ? `http://${host}:${port}` : undefined,
|
||||
appRoot: config.appRoot,
|
||||
stateDir: config.stateDir,
|
||||
pidFile,
|
||||
@@ -57,28 +81,84 @@ export function serviceStatus(config: ServiceConfig) {
|
||||
};
|
||||
}
|
||||
|
||||
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);
|
||||
writeFileSync(pidFile, `${process.pid}\n`, { mode: 0o600 });
|
||||
appendLog(logFile, `running pid=${process.pid}`);
|
||||
|
||||
const cleanup = () => {
|
||||
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 heartbeat = setInterval(() => {}, 60_000);
|
||||
const stop = () => {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
cleanup();
|
||||
clearInterval(heartbeat);
|
||||
process.off("SIGTERM", stop);
|
||||
process.off("SIGINT", stop);
|
||||
resolve();
|
||||
@@ -96,11 +176,15 @@ function startService(config: ServiceConfig) {
|
||||
}
|
||||
|
||||
const launcher = config.launcher ?? { command: process.execPath, args: [config.entryFile] };
|
||||
const child = spawn(launcher.command, [
|
||||
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"],
|
||||
@@ -116,14 +200,17 @@ function startService(config: ServiceConfig) {
|
||||
|
||||
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 };
|
||||
}
|
||||
@@ -156,6 +243,10 @@ 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");
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user