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 } = {} ) { 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 "logs": case "log": return readServiceLogs(config); case "status": case undefined: return serviceStatus(config); default: throw new Error("用法: hose-use service "); } } export function serviceStatus(config: ServiceConfig) { const pidFile = getPidFile(config); const pid = readServicePid(pidFile); const running = pid ? isHoseServiceProcess(pid, config.appRoot) : false; if (pid && !running) { rmSync(pidFile, { force: true }); } 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); return { running, pid: running ? pid : undefined, version: config.version, port, host, url: running ? `http://${host}:${port}` : undefined, 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 }); 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); appendLog(logFile, `service starting on http://${host}:${port} pid=${process.pid}`); let server: Awaited> | 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 }); } throw err; } const cleanup = () => { if (server) { server.close(); server = null; } if (readServicePid(pidFile) === process.pid) { rmSync(pidFile, { force: true }); } appendLog(logFile, `service stopped pid=${process.pid}`); }; await new Promise((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=${config.port}`); if (config.host) serviceArgs.push(`--host=${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), `service 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 || !isHoseServiceProcess(pid, config.appRoot)) { rmSync(pidFile, { force: true }); return options.quiet ? undefined : { stopped: false, reason: "服务未处于运行状态" }; } try { process.kill(pid, "SIGTERM"); } catch { // ignore } rmSync(pidFile, { force: true }); appendLog(getLogFile(config), `service stop requested pid=${pid}`); return options.quiet ? undefined : { stopped: true, pid }; } function readServiceLogs(config: ServiceConfig, maxLines = 50) { const logFile = getLogFile(config); if (!existsSync(logFile)) { return { logFile, lines: [], content: "暂无服务运行日志" }; } const content = readFileSync(logFile, "utf-8"); const lines = content.trim().split("\n").filter(Boolean).slice(-maxLines); return { logFile, lines, content: lines.join("\n"), }; } export function isHoseServiceProcess(pid: number, appRoot: string): boolean { if (!isProcessRunning(pid)) return false; try { const command = execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" }); const matchesTarget = command.includes(appRoot) || command.includes("hose-use") || command.includes("src/cli.ts"); return matchesTarget && command.includes("service") && command.includes("run"); } catch { return false; } } function isProcessRunning(pid: number): boolean { try { process.kill(pid, 0); return true; } catch { return false; } } export function getPidFile(config: ServiceConfig): string { return join(config.stateDir, "service.pid"); } export function getLogFile(config: ServiceConfig): string { return join(config.stateDir, "service.log"); } export function readServicePid(path: string): number | undefined { if (!existsSync(path)) return undefined; const pid = Number(readFileSync(path, "utf-8").trim()); return Number.isInteger(pid) && pid > 0 ? pid : undefined; } function ensureStateDir(stateDir: string): void { mkdirSync(stateDir, { recursive: true, mode: 0o700 }); } function appendLog(path: string, message: string): void { writeFileSync(path, `${new Date().toISOString()} ${message}\n`, { flag: "a", mode: 0o600 }); }