@mingxy/cerebro 1.19.2 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,245 @@
1
+ /**
2
+ * web-server-child.ts — Cerebro Web Server Child Process
3
+ *
4
+ * 独立 fork 入口。实际 HTTP server 运行在此进程中。
5
+ * 通过 IPC 从父进程接收配置,启动后通知父进程 ready。
6
+ * 通过心跳文件 mtime 探测 plugin 进程存活状态。
7
+ */
8
+ import * as http from "node:http";
9
+ import * as fs from "node:fs";
10
+ import * as path from "node:path";
11
+ import * as os from "node:os";
12
+
13
+ // ── Types ────────────────────────────────────────────────────────────────
14
+
15
+ interface ChildConfig {
16
+ port: number;
17
+ webDir: string;
18
+ apiUrl: string;
19
+ }
20
+
21
+ // ── MIME map ─────────────────────────────────────────────────────────────
22
+
23
+ const MIME_TYPES: Record<string, string> = {
24
+ ".html": "text/html; charset=utf-8",
25
+ ".js": "application/javascript; charset=utf-8",
26
+ ".mjs": "application/javascript; charset=utf-8",
27
+ ".css": "text/css; charset=utf-8",
28
+ ".json": "application/json; charset=utf-8",
29
+ ".svg": "image/svg+xml",
30
+ ".png": "image/png",
31
+ ".jpg": "image/jpeg",
32
+ ".jpeg": "image/jpeg",
33
+ ".gif": "image/gif",
34
+ ".ico": "image/x-icon",
35
+ ".woff": "font/woff",
36
+ ".woff2": "font/woff2",
37
+ ".ttf": "font/ttf",
38
+ ".eot": "application/vnd.ms-fontobject",
39
+ ".webp": "image/webp",
40
+ ".webmanifest": "application/manifest+json",
41
+ ".map": "application/json",
42
+ ".txt": "text/plain; charset=utf-8",
43
+ };
44
+
45
+ function getMimeType(ext: string): string {
46
+ return MIME_TYPES[ext] || "application/octet-stream";
47
+ }
48
+
49
+ // ── Safe path resolver (prevent traversal) ───────────────────────────────
50
+
51
+ function resolveSafe(baseDir: string, pathname: string): string | null {
52
+ const relative = pathname.startsWith("/") ? pathname.slice(1) : pathname;
53
+ const resolved = path.resolve(baseDir, relative || ".");
54
+ if (!resolved.startsWith(baseDir + path.sep) && resolved !== baseDir) {
55
+ return null;
56
+ }
57
+ return resolved;
58
+ }
59
+
60
+ // ── File serving ─────────────────────────────────────────────────────────
61
+
62
+ function serveFile(
63
+ res: http.ServerResponse,
64
+ filePath: string,
65
+ apiUrl: string,
66
+ ): void {
67
+ const ext = path.extname(filePath).toLowerCase();
68
+ const contentType = getMimeType(ext);
69
+
70
+ fs.readFile(filePath, (err, data) => {
71
+ if (err) {
72
+ res.writeHead(500, { "Content-Type": "text/plain" });
73
+ res.end("Internal Server Error");
74
+ return;
75
+ }
76
+
77
+ let body: Buffer | string = data;
78
+
79
+ // Config injection: replace placeholder in index.html
80
+ if (ext === ".html" && data.includes("__OMEM_API_URL__")) {
81
+ body = data
82
+ .toString("utf-8")
83
+ .replace(
84
+ /window\.__OMEM_API_URL__\s*=\s*["']__OMEM_API_URL__["']/,
85
+ `window.__OMEM_API_URL__ = "${apiUrl}"`,
86
+ );
87
+ }
88
+
89
+ res.writeHead(200, {
90
+ "Content-Type": contentType,
91
+ "Cache-Control":
92
+ ext === ".html"
93
+ ? "no-cache, no-store, must-revalidate"
94
+ : "public, max-age=86400",
95
+ });
96
+ res.end(body);
97
+ });
98
+ }
99
+
100
+ // ── Server lifecycle ─────────────────────────────────────────────────────
101
+
102
+ let server: http.Server | null = null;
103
+ let heartbeatTimer: ReturnType<typeof setInterval> | null = null;
104
+ let pidFilePath = "";
105
+ let heartbeatFilePath = "";
106
+
107
+ function cleanup(): void {
108
+ if (heartbeatTimer) {
109
+ clearInterval(heartbeatTimer);
110
+ heartbeatTimer = null;
111
+ }
112
+ if (server) {
113
+ server.closeAllConnections?.();
114
+ const forceTimer = setTimeout(() => {
115
+ try { fs.unlinkSync(pidFilePath); } catch { /* ignore */ }
116
+ process.exit(0);
117
+ }, 3000);
118
+ server.close(() => {
119
+ clearTimeout(forceTimer);
120
+ try { fs.unlinkSync(pidFilePath); } catch { /* ignore */ }
121
+ process.exit(0);
122
+ });
123
+ } else {
124
+ try { fs.unlinkSync(pidFilePath); } catch { /* ignore */ }
125
+ process.exit(0);
126
+ }
127
+ }
128
+
129
+ function startServer(config: ChildConfig): void {
130
+ const { port, webDir, apiUrl } = config;
131
+
132
+ pidFilePath = path.join(os.tmpdir(), `cerebro-web-${port}.pid`);
133
+ heartbeatFilePath = path.join(os.tmpdir(), `cerebro-web-${port}.heartbeat`);
134
+
135
+ const indexPath = path.join(webDir, "index.html");
136
+
137
+ // 写 PID 文件(子进程自己的 PID)
138
+ try {
139
+ fs.writeFileSync(pidFilePath, String(process.pid));
140
+ } catch {
141
+ console.error("[cerebro:web-child] Failed to write PID file");
142
+ }
143
+
144
+ // 初始 touch 心跳文件
145
+ try {
146
+ fs.writeFileSync(heartbeatFilePath, "");
147
+ } catch {
148
+ console.error("[cerebro:web-child] Failed to create heartbeat file");
149
+ }
150
+
151
+ server = http.createServer(
152
+ (req: http.IncomingMessage, res: http.ServerResponse) => {
153
+ // ── /health 端点 ──
154
+ if (req.url === "/health" || req.url === "/health/") {
155
+ res.writeHead(200, { "Content-Type": "application/json" });
156
+ res.end(JSON.stringify({ status: "ok", service: "cerebro", port }));
157
+ return;
158
+ }
159
+
160
+ // Only handle GET / HEAD
161
+ if (req.method !== "GET" && req.method !== "HEAD") {
162
+ res.writeHead(405, { "Content-Type": "text/plain" });
163
+ res.end("Method Not Allowed");
164
+ return;
165
+ }
166
+
167
+ // Parse URL, strip query string
168
+ const url = new URL(req.url || "/", `http://localhost:${port}`);
169
+ // new URL() already decodes percent-encoding; no double-decode
170
+ const pathname = url.pathname;
171
+
172
+ // Resolve safe file path
173
+ const safePath = resolveSafe(webDir, pathname);
174
+
175
+ if (!safePath) {
176
+ res.writeHead(403, { "Content-Type": "text/plain" });
177
+ res.end("Forbidden");
178
+ return;
179
+ }
180
+
181
+ // Try to serve the file directly
182
+ fs.stat(safePath, (statErr, stats) => {
183
+ if (!statErr && stats.isFile()) {
184
+ serveFile(res, safePath, apiUrl);
185
+ return;
186
+ }
187
+
188
+ // SPA fallback: serve index.html for non-file paths
189
+ fs.stat(indexPath, (idxErr, idxStats) => {
190
+ if (idxErr || !idxStats.isFile()) {
191
+ res.writeHead(404, { "Content-Type": "text/plain" });
192
+ res.end("Not Found");
193
+ return;
194
+ }
195
+ serveFile(res, indexPath, apiUrl);
196
+ });
197
+ });
198
+ },
199
+ );
200
+
201
+ server.on("error", (err: NodeJS.ErrnoException) => {
202
+ console.error(`[cerebro:web-child] Server error: ${err.message}`);
203
+ process.send?.({ type: "error", message: err.message });
204
+ cleanup();
205
+ });
206
+
207
+ server.listen(port, "127.0.0.1", () => {
208
+ console.log(
209
+ `[cerebro:web-child] Server listening on http://localhost:${port}`,
210
+ );
211
+ process.send?.({ type: "ready", port });
212
+ });
213
+
214
+ // ── 心跳检测:每 30 秒检查心跳文件 mtime ──
215
+ heartbeatTimer = setInterval(() => {
216
+ try {
217
+ const stat = fs.statSync(heartbeatFilePath);
218
+ if (Date.now() - stat.mtimeMs > 60_000) {
219
+ console.log(
220
+ "[cerebro:web-child] Heartbeat expired, shutting down",
221
+ );
222
+ cleanup();
223
+ }
224
+ } catch {
225
+ // 心跳文件不存在,可能被清理,继续等待不主动退出
226
+ }
227
+ }, 30_000);
228
+
229
+ // 确保定时器不阻止进程退出
230
+ if (heartbeatTimer) heartbeatTimer.unref();
231
+
232
+ // ── 信号处理 ──
233
+ process.on("SIGTERM", cleanup);
234
+ process.on("SIGINT", cleanup);
235
+ }
236
+
237
+ // ── IPC 监听(只处理第一条消息) ─────────────────────────────────────────
238
+
239
+ let started = false;
240
+
241
+ process.on("message", (config: ChildConfig) => {
242
+ if (started) return;
243
+ started = true;
244
+ startServer(config);
245
+ });
package/src/web-server.ts CHANGED
@@ -1,6 +1,14 @@
1
- import * as http from "node:http";
1
+ /**
2
+ * web-server.ts — Cerebro Web Server Manager (spawn mode)
3
+ *
4
+ * 不再直接创建 HTTP server,而是 fork 独立子进程 (web-server-child.ts)。
5
+ * 多窗口共享一个 server,任一窗口关闭不影响其他窗口。
6
+ * 子进程通过心跳文件 mtime 探测 plugin 存活状态,全部退出后自动关闭。
7
+ */
8
+ import { fork } from "node:child_process";
2
9
  import * as fs from "node:fs";
3
10
  import * as path from "node:path";
11
+ import * as os from "node:os";
4
12
  import { fileURLToPath } from "node:url";
5
13
 
6
14
  const __filename = fileURLToPath(import.meta.url);
@@ -13,170 +21,185 @@ export interface WebServerConfig {
13
21
  port?: number;
14
22
  }
15
23
 
16
- // ── MIME map ─────────────────────────────────────────────────────────────
17
-
18
- const MIME_TYPES: Record<string, string> = {
19
- ".html": "text/html; charset=utf-8",
20
- ".js": "application/javascript; charset=utf-8",
21
- ".mjs": "application/javascript; charset=utf-8",
22
- ".css": "text/css; charset=utf-8",
23
- ".json": "application/json; charset=utf-8",
24
- ".svg": "image/svg+xml",
25
- ".png": "image/png",
26
- ".jpg": "image/jpeg",
27
- ".jpeg": "image/jpeg",
28
- ".gif": "image/gif",
29
- ".ico": "image/x-icon",
30
- ".woff": "font/woff",
31
- ".woff2": "font/woff2",
32
- ".ttf": "font/ttf",
33
- ".eot": "application/vnd.ms-fontobject",
34
- ".webp": "image/webp",
35
- ".webmanifest": "application/manifest+json",
36
- ".map": "application/json",
37
- ".txt": "text/plain; charset=utf-8",
38
- };
39
-
40
- function getMimeType(ext: string): string {
41
- return MIME_TYPES[ext] || "application/octet-stream";
24
+ export interface WebServerHandle {
25
+ address(): { port: number; family: string; address: string } | string | null;
42
26
  }
43
27
 
44
- // ── Safe path resolver (prevent traversal) ───────────────────────────────
28
+ // ── Helpers ──────────────────────────────────────────────────────────────
45
29
 
46
- function resolveSafe(baseDir: string, pathname: string): string | null {
47
- // Strip leading slash so path.resolve treats it as relative
48
- const relative = pathname.startsWith("/") ? pathname.slice(1) : pathname;
49
- const resolved = path.resolve(baseDir, relative || ".");
50
- if (!resolved.startsWith(baseDir + path.sep) && resolved !== baseDir) {
51
- return null;
30
+ /** Touch a file update mtime or create if missing */
31
+ function touchFile(filePath: string): void {
32
+ try {
33
+ fs.utimesSync(filePath, new Date(), new Date());
34
+ } catch {
35
+ try {
36
+ fs.writeFileSync(filePath, "");
37
+ } catch { /* ignore */ }
52
38
  }
53
- return resolved;
54
39
  }
55
40
 
56
- // ── Start / Stop ─────────────────────────────────────────────────────────
57
-
58
- export function startWebServer(config: WebServerConfig): Promise<http.Server | null> {
59
- return new Promise((resolve) => {
60
- const webDir = path.resolve(__dirname, "..", "web");
41
+ /** Check if a process with the given PID is still running */
42
+ function isProcessAlive(pid: number): boolean {
43
+ try {
44
+ process.kill(pid, 0);
45
+ return true;
46
+ } catch {
47
+ return false;
48
+ }
49
+ }
61
50
 
62
- // Check web directory exists
63
- if (!fs.existsSync(webDir)) {
64
- console.warn(`[cerebro:web] Web directory not found: ${webDir}, skipping server start`);
65
- resolve(null);
66
- return;
51
+ /** Probe an existing server's /health endpoint */
52
+ async function probeExistingServer(port: number): Promise<boolean> {
53
+ try {
54
+ const resp = await fetch(`http://127.0.0.1:${port}/health`);
55
+ if (resp.ok) {
56
+ const body = await resp.text();
57
+ return body.includes("cerebro");
67
58
  }
59
+ } catch { /* connection refused → port free */ }
60
+ return false;
61
+ }
62
+
63
+ // ── Start / Stop ─────────────────────────────────────────────────────────
64
+
65
+ export async function startWebServer(
66
+ config: WebServerConfig,
67
+ ): Promise<WebServerHandle | null> {
68
+ const port =
69
+ config.port || parseInt(process.env.OMEM_LOCAL_PORT || "", 10) || 5212;
70
+ const pidFilePath = path.join(os.tmpdir(), `cerebro-web-${port}.pid`);
71
+ const heartbeatFilePath = path.join(
72
+ os.tmpdir(),
73
+ `cerebro-web-${port}.heartbeat`,
74
+ );
75
+
76
+ // ── Step 1: 检查端口是否已有 cerebro server ──
77
+ if (await probeExistingServer(port)) {
78
+ console.log(`[cerebro:web] Reusing existing server on port ${port}`);
79
+ return createHandle(port, heartbeatFilePath);
80
+ }
68
81
 
69
- const indexPath = path.join(webDir, "index.html");
70
- if (!fs.existsSync(indexPath)) {
71
- console.warn(`[cerebro:web] index.html not found in ${webDir}, skipping server start`);
72
- resolve(null);
73
- return;
82
+ // ── Step 2: 检查 PID 文件(可能有其他进程正在 fork) ──
83
+ try {
84
+ const pidStr = fs.readFileSync(pidFilePath, "utf-8").trim();
85
+ const pid = parseInt(pidStr, 10);
86
+ if (pid > 0 && isProcessAlive(pid)) {
87
+ // 有其他进程正在 fork 或运行,等待 200ms 后重试
88
+ await new Promise((r) => setTimeout(r, 200));
89
+ if (await probeExistingServer(port)) {
90
+ console.log(
91
+ `[cerebro:web] Reusing server after PID check on port ${port}`,
92
+ );
93
+ return createHandle(port, heartbeatFilePath);
94
+ }
95
+ } else {
96
+ // 进程已死亡,清理 PID 文件
97
+ try { fs.unlinkSync(pidFilePath); } catch { /* ignore */ }
74
98
  }
99
+ } catch { /* PID 文件不存在,继续 */ }
75
100
 
76
- const port = config.port || parseInt(process.env.OMEM_LOCAL_PORT || "", 10) || 5212;
77
-
78
- const server = http.createServer(
79
- (req: http.IncomingMessage, res: http.ServerResponse) => {
80
- // Only handle GET / HEAD
81
- if (req.method !== "GET" && req.method !== "HEAD") {
82
- res.writeHead(405, { "Content-Type": "text/plain" });
83
- res.end("Method Not Allowed");
84
- return;
85
- }
86
-
87
- // Parse URL, strip query string
88
- const url = new URL(req.url || "/", `http://localhost:${port}`);
89
- const pathname = decodeURIComponent(url.pathname);
90
-
91
- // Resolve safe file path
92
- const safePath = resolveSafe(webDir, pathname);
93
-
94
- if (!safePath) {
95
- res.writeHead(403, { "Content-Type": "text/plain" });
96
- res.end("Forbidden");
97
- return;
98
- }
99
-
100
- // Try to serve the file directly
101
- fs.stat(safePath, (statErr, stats) => {
102
- if (!statErr && stats.isFile()) {
103
- serveFile(res, safePath, config.apiUrl);
104
- return;
105
- }
106
-
107
- // SPA fallback: serve index.html for non-file paths
108
- fs.stat(indexPath, (idxErr, idxStats) => {
109
- if (idxErr || !idxStats.isFile()) {
110
- res.writeHead(404, { "Content-Type": "text/plain" });
111
- res.end("Not Found");
112
- return;
113
- }
114
- serveFile(res, indexPath, config.apiUrl);
115
- });
116
- });
117
- },
101
+ // ── Step 3: 检查 web 目录 ──
102
+ const webDir = path.resolve(__dirname, "..", "web");
103
+ if (!fs.existsSync(webDir)) {
104
+ console.warn(
105
+ `[cerebro:web] Web directory not found: ${webDir}, skipping server start`,
118
106
  );
107
+ return null;
108
+ }
109
+ if (!fs.existsSync(path.join(webDir, "index.html"))) {
110
+ console.warn(
111
+ `[cerebro:web] index.html not found in ${webDir}, skipping server start`,
112
+ );
113
+ return null;
114
+ }
119
115
 
120
- server.on("error", (err: NodeJS.ErrnoException) => {
121
- if (err.code === "EADDRINUSE") {
122
- console.warn(`[cerebro:web] Port ${port} already in use, web server not started`);
123
- } else {
124
- console.warn(`[cerebro:web] Server error: ${err.message}`);
125
- }
126
- resolve(null);
127
- });
116
+ // ── Step 4: PID 文件(标记正在 fork) ──
117
+ try {
118
+ fs.writeFileSync(pidFilePath, String(process.pid));
119
+ } catch { /* ignore */ }
128
120
 
129
- server.listen(port, "127.0.0.1", () => {
130
- const addr = server.address();
131
- const actualPort = typeof addr === "object" && addr ? addr.port : port;
132
- console.log(`[cerebro:web] Static server listening on http://localhost:${actualPort}`);
133
- resolve(server);
134
- });
121
+ // ── Step 5: Fork 子进程 ──
122
+ const childPath = path.resolve(__dirname, "web-server-child.js");
123
+
124
+ const child = fork(childPath, [], {
125
+ detached: true,
126
+ stdio: ["pipe", "pipe", "pipe", "ipc"],
135
127
  });
136
- }
137
128
 
138
- // ── File serving ─────────────────────────────────────────────────────────
139
-
140
- function serveFile(
141
- res: http.ServerResponse,
142
- filePath: string,
143
- apiUrl: string,
144
- ): void {
145
- const ext = path.extname(filePath).toLowerCase();
146
- const contentType = getMimeType(ext);
147
-
148
- fs.readFile(filePath, (err, data) => {
149
- if (err) {
150
- res.writeHead(500, { "Content-Type": "text/plain" });
151
- res.end("Internal Server Error");
152
- return;
153
- }
129
+ // Drain stdout/stderr to prevent pipe buffer from blocking the child
130
+ child.stdout?.on("data", () => {});
131
+ child.stderr?.on("data", () => {});
154
132
 
155
- let body: Buffer | string = data;
133
+ child.unref();
156
134
 
157
- // Config injection: replace placeholder in index.html
158
- if (ext === ".html" && data.includes("__OMEM_API_URL__")) {
159
- body = data.toString("utf-8").replace(/window\.__OMEM_API_URL__\s*=\s*["']__OMEM_API_URL__["']/, `window.__OMEM_API_URL__ = "${apiUrl}"`);
160
- }
135
+ // 发送配置给子进程
136
+ child.send({ port, webDir, apiUrl: config.apiUrl });
137
+
138
+ // ── Step 6: 等待 ready 或超时 5s ──
139
+ const ready = await new Promise<boolean>((resolve) => {
140
+ const timeout = setTimeout(() => resolve(false), 5000);
161
141
 
162
- res.writeHead(200, {
163
- "Content-Type": contentType,
164
- "Cache-Control": ext === ".html" ? "no-cache, no-store, must-revalidate" : "public, max-age=86400",
142
+ child.on("message", (msg: { type: string }) => {
143
+ if (msg.type === "ready") {
144
+ clearTimeout(timeout);
145
+ resolve(true);
146
+ } else if (msg.type === "error") {
147
+ clearTimeout(timeout);
148
+ resolve(false);
149
+ }
165
150
  });
166
- res.end(body);
167
- });
168
- }
169
151
 
170
- // ── Graceful shutdown ────────────────────────────────────────────────────
152
+ child.on("error", () => {
153
+ clearTimeout(timeout);
154
+ resolve(false);
155
+ });
171
156
 
172
- export function stopWebServer(server: http.Server): Promise<void> {
173
- return new Promise((resolve) => {
174
- server.closeAllConnections?.();
175
- const timer = setTimeout(resolve, 3000);
176
- server.close(() => {
177
- clearTimeout(timer);
178
- console.log("[cerebro:web] Server stopped");
179
- resolve();
157
+ child.on("exit", () => {
158
+ clearTimeout(timeout);
159
+ resolve(false);
180
160
  });
181
161
  });
162
+
163
+ if (!ready) {
164
+ console.warn(
165
+ `[cerebro:web] Failed to start web server child process on port ${port}`,
166
+ );
167
+ try { child.kill(); } catch { /* ignore */ }
168
+ try { fs.unlinkSync(pidFilePath); } catch { /* ignore */ }
169
+ return null;
170
+ }
171
+
172
+ console.log(
173
+ `[cerebro:web] Web server child process started on port ${port}`,
174
+ );
175
+ return createHandle(port, heartbeatFilePath);
176
+ }
177
+
178
+ /** Create a handle with address() compat + heartbeat keep-alive */
179
+ function createHandle(
180
+ port: number,
181
+ heartbeatFilePath: string,
182
+ ): WebServerHandle {
183
+ // 初始 touch
184
+ touchFile(heartbeatFilePath);
185
+
186
+ // 每 30 秒 touch 心跳文件,保持子进程存活
187
+ const timer = setInterval(() => {
188
+ touchFile(heartbeatFilePath);
189
+ }, 30_000);
190
+
191
+ // 确保定时器不阻止进程退出
192
+ timer.unref();
193
+
194
+ return {
195
+ address() {
196
+ return { port, family: "IPv4", address: "127.0.0.1" };
197
+ },
198
+ };
199
+ }
200
+
201
+ export function stopWebServer(_handle: WebServerHandle): Promise<void> {
202
+ // Intentionally do NOT touch heartbeat: parent exits → timer stops →
203
+ // heartbeat ages out → child detects mtime > 60s → self-terminate.
204
+ return Promise.resolve();
182
205
  }