From f183cc8294325b2a4eef22a90ada3e9a3bb76578 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Fri, 4 Sep 2026 17:53:40 +0800 Subject: [PATCH] Add persistent HTTP server to background service daemon --- src/cli/commands/service.ts | 33 ++++++++--- src/cli/parser.ts | 13 +++- src/cli/runner.ts | 16 ++++- src/cli/service.test.ts | 68 ++++++++++++++++++++- src/cli/service.ts | 115 ++++++++++++++++++++++++++++++++---- src/http/routes.ts | 35 ++++------- src/http/server.ts | 7 ++- 7 files changed, 237 insertions(+), 50 deletions(-) diff --git a/src/cli/commands/service.ts b/src/cli/commands/service.ts index 433453e..f44c54e 100644 --- a/src/cli/commands/service.ts +++ b/src/cli/commands/service.ts @@ -3,17 +3,32 @@ import { join } from "node:path"; import { VERSION } from "../../version.js"; import { runServiceCommand } from "../service.js"; import { printJson } from "../printer.js"; -import type { CliRuntime } from "../types.js"; +import { numberOption, stringOption } from "../parser.js"; +import type { CliRuntime, ParsedArgs } from "../types.js"; export const STATE_DIR = join(homedir(), ".config", "seal-use"); -export async function handleServiceCommand(action: string | undefined, runtime: CliRuntime) { - const result = await runServiceCommand(action, { - appRoot: runtime.appRoot, - entryFile: runtime.entryFile, - stateDir: STATE_DIR, - version: VERSION, - launcher: runtime.launcher - }); +export async function handleServiceCommand( + action: string | undefined, + runtime: CliRuntime, + args?: ParsedArgs +) { + const port = args ? numberOption(args.options.port) ?? numberOption(args.options.p) : undefined; + const host = args ? stringOption(args.options.host) ?? stringOption(args.options.h) : undefined; + const maxLines = args ? numberOption(args.options.lines) ?? numberOption(args.options.n) : undefined; + + const result = await runServiceCommand( + action, + { + appRoot: runtime.appRoot, + entryFile: runtime.entryFile, + stateDir: STATE_DIR, + version: VERSION, + launcher: runtime.launcher, + port, + host + }, + { maxLines } + ); if (result !== undefined) printJson(result); } diff --git a/src/cli/parser.ts b/src/cli/parser.ts index 97b41fe..e89a09c 100644 --- a/src/cli/parser.ts +++ b/src/cli/parser.ts @@ -19,12 +19,19 @@ export function parseArgs(argv: string[]): ParsedArgs { } if (arg.startsWith("-")) { - const key = arg.replace(/^-+/, ""); + const raw = arg.replace(/^-+/, ""); + if (raw.includes("=")) { + const eqIdx = raw.indexOf("="); + const key = raw.slice(0, eqIdx); + const val = raw.slice(eqIdx + 1); + options[key] = val; + continue; + } const next = argv[index + 1]; if (!next || next.startsWith("-")) { - options[key] = true; + options[raw] = true; } else { - options[key] = next; + options[raw] = next; index += 1; } continue; diff --git a/src/cli/runner.ts b/src/cli/runner.ts index d1fcce1..9056422 100755 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -78,9 +78,23 @@ const KNOWN_AREAS = new Set([ export type { CliResult, CliRunOptions } from "./types.js"; +const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]); + +function isStandingCommand(argv: string[]): boolean { + if (!argv.length) return false; + const first = argv[0]?.toLowerCase(); + const second = argv[1]?.toLowerCase(); + if (first && STANDING_COMMANDS.has(first)) return true; + if ((first === "service" || first === "daemon") && second === "run") return true; + return false; +} + let runQueue = Promise.resolve(); export function runCli(argv: string[], options: CliRunOptions = {}): Promise { + if (isStandingCommand(argv)) { + return runCliOnce(argv, options); + } const run = runQueue.then(() => runCliOnce(argv, options)); runQueue = run.then( () => undefined, @@ -194,7 +208,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) { } if (area === "service") { - await handleServiceCommand(action, runtime); + await handleServiceCommand(action, runtime, args); return; } diff --git a/src/cli/service.test.ts b/src/cli/service.test.ts index 285fa60..b1a523b 100644 --- a/src/cli/service.test.ts +++ b/src/cli/service.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test"; import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { serviceStatus } from "./service.js"; +import { serviceStatus, readServiceLogs, runServiceCommand } from "./service.js"; const tempDirs: string[] = []; @@ -27,5 +27,71 @@ describe("service lifecycle state", () => { expect(status.running).toBe(false); expect(status.pid).toBeUndefined(); + expect(status.port).toBe(8787); + expect(status.host).toBe("127.0.0.1"); + expect(status.url).toBeUndefined(); + }); + + test("respects custom port and host configuration", () => { + const stateDir = mkdtempSync(join(tmpdir(), "seal-use-service-")); + tempDirs.push(stateDir); + + const status = serviceStatus({ + appRoot: "/tmp/seal-use", + entryFile: "/tmp/seal-use/src/cli.ts", + stateDir, + version: "0.10.7", + port: 9090, + host: "0.0.0.0" + }); + + expect(status.port).toBe(9090); + expect(status.host).toBe("0.0.0.0"); + }); + + test("reads service log file lines safely", () => { + const stateDir = mkdtempSync(join(tmpdir(), "seal-use-service-")); + tempDirs.push(stateDir); + + const emptyLogs = readServiceLogs({ + appRoot: "/tmp/seal-use", + entryFile: "/tmp/seal-use/src/cli.ts", + stateDir + }); + expect(emptyLogs.lines).toEqual([]); + expect(emptyLogs.totalLines).toBe(0); + + const logFile = join(stateDir, "service.log"); + writeFileSync(logFile, "line 1\nline 2\nline 3\nline 4\nline 5\n"); + + const logs = readServiceLogs( + { + appRoot: "/tmp/seal-use", + entryFile: "/tmp/seal-use/src/cli.ts", + stateDir + }, + 3 + ); + expect(logs.totalLines).toBe(5); + expect(logs.lines).toEqual(["line 3", "line 4", "line 5"]); + }); + + test("runServiceCommand handles logs and status actions", async () => { + const stateDir = mkdtempSync(join(tmpdir(), "seal-use-service-")); + tempDirs.push(stateDir); + + const status = await runServiceCommand("status", { + appRoot: "/tmp/seal-use", + entryFile: "/tmp/seal-use/src/cli.ts", + stateDir + }); + expect(status).toHaveProperty("running"); + + const logs = await runServiceCommand("logs", { + appRoot: "/tmp/seal-use", + entryFile: "/tmp/seal-use/src/cli.ts", + stateDir + }); + expect(logs).toHaveProperty("lines"); }); }); diff --git a/src/cli/service.ts b/src/cli/service.ts index eb644ed..7f7eea4 100644 --- a/src/cli/service.ts +++ b/src/cli/service.ts @@ -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 "); + throw new Error("Usage: seal-use service "); } } 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> | 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((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"); } diff --git a/src/http/routes.ts b/src/http/routes.ts index a5e84f7..c1cdd08 100644 --- a/src/http/routes.ts +++ b/src/http/routes.ts @@ -393,28 +393,19 @@ export function extractCorpId( } export async function parseJsonBody(req: IncomingMessage): Promise> { - return new Promise((resolve, reject) => { - let raw = ""; - req.on("data", (chunk) => { - raw += chunk; - if (raw.length > 20 * 1024 * 1024) { - // 20MB limit - reject(new Error("Payload too large")); - } - }); - req.on("end", () => { - if (!raw.trim()) { - resolve({}); - return; - } - try { - resolve(JSON.parse(raw)); - } catch (err) { - reject(new Error(`Invalid JSON body: ${err instanceof Error ? err.message : String(err)}`)); - } - }); - req.on("error", reject); - }); + let raw = ""; + for await (const chunk of req) { + raw += chunk; + if (raw.length > 20 * 1024 * 1024) { + throw new Error("Payload too large"); + } + } + if (!raw.trim()) return {}; + try { + return JSON.parse(raw); + } catch (err) { + throw new Error(`Invalid JSON body: ${err instanceof Error ? err.message : String(err)}`); + } } export function sendJson(res: ServerResponse, statusCode: number, data: unknown) { diff --git a/src/http/server.ts b/src/http/server.ts index 00a009a..6efc218 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -8,9 +8,12 @@ export type HttpServerOptions = { silent?: boolean; }; +export const DEFAULT_HTTP_PORT = 8787; +export const DEFAULT_HTTP_HOST = "127.0.0.1"; + export async function startHttpServer(options: HttpServerOptions = {}): Promise { - const port = options.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : 8787); - const host = options.host ?? (process.env.HOST ? process.env.HOST : "127.0.0.1"); + const port = options.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT); + const host = options.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST); const server = createServer(async (req, res) => { try {