import { spawn, execFileSync } from "node:child_process"; import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { homedir } from "node:os"; import { startHttpServer, DEFAULT_HTTP_PORT, DEFAULT_AIPRO_HTTP_PORT, DEFAULT_HTTP_HOST, } from "../http/server.js"; import { VERSION } from "../version.js"; import type { CliRuntime } from "./types.js"; export type ServiceTargetName = "hose-use" | "hose-aipro"; export const SERVICE_STATE_DIR = process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use"); export type ServiceConfig = { serviceName?: ServiceTargetName; serviceTitle?: string; appRoot: string; entryFile: string; stateDir: string; version?: string; launcher?: { command: string; args?: string[]; }; port?: number; host?: string; pidFileName?: string; logFileName?: string; }; export function getHoseUseServiceConfig( runtime?: Partial, options?: { port?: number; host?: string } ): ServiceConfig { const appRoot = runtime?.appRoot || process.cwd(); return { serviceName: "hose-use", serviceTitle: "hose-use 常驻服务管理 (Service)", appRoot, entryFile: runtime?.entryFile || join(appRoot, "src", "cli.ts"), stateDir: SERVICE_STATE_DIR, version: VERSION, launcher: runtime?.launcher, port: options?.port, host: options?.host, pidFileName: "service.pid", logFileName: "service.log", }; } export function getAiProServiceConfig( runtime?: Partial, options?: { port?: number; host?: string } ): ServiceConfig { const appRoot = runtime?.appRoot || process.cwd(); return { serviceName: "hose-aipro", serviceTitle: "hose-aipro 审批网关常驻服务 (Service)", appRoot, entryFile: join(appRoot, "src", "aipro-cli.ts"), stateDir: SERVICE_STATE_DIR, version: VERSION, launcher: runtime?.launcher, port: options?.port, host: options?.host, pidFileName: "aipro-service.pid", logFileName: "aipro-service.log", }; } export async function runServiceCommand( action: string | undefined, config: ServiceConfig, options: { quiet?: boolean } = {} ) { const targetLabel = config.serviceName || "hose-use"; 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(`用法: ${targetLabel} service `); } } export function serviceStatus(config: ServiceConfig) { const pidFile = getPidFile(config); const pid = readServicePid(pidFile); const running = pid ? isHoseServiceProcess(pid, config.appRoot, config.serviceName) : false; if (pid && !running) { rmSync(pidFile, { force: true }); } const isAiPro = config.serviceName === "hose-aipro"; const defaultPort = isAiPro ? DEFAULT_AIPRO_HTTP_PORT : DEFAULT_HTTP_PORT; const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : defaultPort); const host = config.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST); return { running, serviceName: config.serviceName || "hose-use", serviceTitle: config.serviceTitle || (isAiPro ? "hose-aipro 审批网关常驻服务 (Service)" : "hose-use 常驻服务管理 (Service)"), 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 isAiPro = config.serviceName === "hose-aipro"; const defaultPort = isAiPro ? DEFAULT_AIPRO_HTTP_PORT : DEFAULT_HTTP_PORT; const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : defaultPort); const host = config.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST); appendLog(logFile, `${config.serviceName || "hose-use"} service starting on http://${host}:${port} pid=${process.pid}`); let server: Awaited> | null = null; try { server = await startHttpServer({ port, host, silent: true, app: isAiPro ? "hose-aipro" : "hose-use", }); appendLog(logFile, `${config.serviceName || "hose-use"} service listening pid=${process.pid}`); } catch (err: unknown) { appendLog(logFile, `${config.serviceName || "hose-use"} 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, `${config.serviceName || "hose-use"} 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), `${config.serviceName || "hose-use"} 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, config.serviceName)) { 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), `${config.serviceName || "hose-use"} 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, targetName?: ServiceTargetName ): boolean { if (!isProcessRunning(pid)) return false; try { const command = execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" }); const isRun = command.includes("service") && command.includes("run"); if (!isRun) return false; if (targetName === "hose-aipro") { return command.includes("hose-aipro") || command.includes("aipro-cli"); } if (targetName === "hose-use") { return ( (command.includes("hose-use") || command.includes("src/cli.ts") || command.includes(appRoot)) && !command.includes("hose-aipro") && !command.includes("aipro-cli") ); } return ( command.includes(appRoot) || command.includes("hose-use") || command.includes("src/cli.ts") || command.includes("hose-aipro") ); } catch { return false; } } function isProcessRunning(pid: number): boolean { try { process.kill(pid, 0); return true; } catch { return false; } } export function getPidFile(config: ServiceConfig): string { const fileName = config.pidFileName || (config.serviceName === "hose-aipro" ? "aipro-service.pid" : "service.pid"); return join(config.stateDir, fileName); } export function getLogFile(config: ServiceConfig): string { const fileName = config.logFileName || (config.serviceName === "hose-aipro" ? "aipro-service.log" : "service.log"); return join(config.stateDir, fileName); } 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 }); }