chatccc 0.2.16 → 0.2.18

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.
package/src/shared.ts CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  unlinkSync,
9
9
  writeFileSync,
10
10
  } from "node:fs";
11
+ import { createServer } from "node:http";
11
12
  import { dirname, join } from "node:path";
12
13
  import { fileURLToPath } from "node:url";
13
14
  import { WebSocketServer, WebSocket } from "ws";
@@ -210,6 +211,146 @@ export function ensureSingleInstance(pidFile: string): void {
210
211
  });
211
212
  }
212
213
 
214
+ // ---------------------------------------------------------------------------
215
+ // 崩溃黑匣子:进程级别异常 / 信号 / beforeExit 同步落盘
216
+ // ---------------------------------------------------------------------------
217
+ //
218
+ // 设计要点:
219
+ // 1) 全部经由 appendStartupTrace(appendFileSync 同步写盘),保证进程立即退出
220
+ // 时也能落盘。console.error 走的是 createWriteStream 异步缓冲,会丢日志。
221
+ // 2) 默认 onFatal 会主动 process.exit(1)。在 Node 20+ 注册了 unhandledRejection
222
+ // handler 后,默认不再致命退出,会让进程卡在 broken state——主动 exit 让
223
+ // 现象更直观,方便重启与诊断。
224
+ // 3) handler 实现拆成 buildCrashLoggingHandlers(纯函数,无副作用,便于单测)
225
+ // 和 installCrashLogging(把 handler 挂到 process 上,返回 cleanup)。
226
+
227
+ const FATAL_STACK_MAX = 4000;
228
+
229
+ export interface CrashHandlersOptions {
230
+ /** 用于写入诊断的同步函数,默认 appendStartupTrace */
231
+ tracer?: (message: string, extra?: Record<string, unknown>) => void;
232
+ /** 用于刷新文件日志缓冲,默认 noop */
233
+ flush?: () => void;
234
+ /** 致命异常发生后的处理,默认 console.error + process.exit(1) */
235
+ onFatal?: (kind: "uncaughtException" | "unhandledRejection", err: Error) => void;
236
+ /** 信号到来时的处理,默认 noop(清理动作由调用方自己注册其它 listener 完成) */
237
+ onSignal?: (sig: NodeJS.Signals) => void;
238
+ /** beforeExit 时的处理,默认 noop */
239
+ onBeforeExit?: (code: number) => void;
240
+ }
241
+
242
+ export interface CrashLoggingHandlers {
243
+ uncaughtException: (err: unknown) => void;
244
+ unhandledRejection: (reason: unknown) => void;
245
+ signalLogger: (sig: NodeJS.Signals) => void;
246
+ beforeExit: (code: number) => void;
247
+ }
248
+
249
+ function coerceError(reason: unknown): Error {
250
+ if (reason instanceof Error) return reason;
251
+ if (typeof reason === "string") return new Error(reason);
252
+ if (reason === undefined) return new Error("unhandled rejection with reason=undefined");
253
+ if (reason === null) return new Error("unhandled rejection with reason=null");
254
+ try {
255
+ return new Error(JSON.stringify(reason));
256
+ } catch {
257
+ return new Error(String(reason));
258
+ }
259
+ }
260
+
261
+ function truncateStack(stack: string | undefined): string {
262
+ if (!stack) return "";
263
+ return stack.length > FATAL_STACK_MAX
264
+ ? `${stack.slice(0, FATAL_STACK_MAX)}...(truncated)`
265
+ : stack;
266
+ }
267
+
268
+ function safeCall<T extends unknown[]>(fn: ((...args: T) => unknown) | undefined, ...args: T): void {
269
+ if (!fn) return;
270
+ try { fn(...args); } catch { /* swallow: 诊断路径不允许二次抛错 */ }
271
+ }
272
+
273
+ export function buildCrashLoggingHandlers(opts: CrashHandlersOptions = {}): CrashLoggingHandlers {
274
+ const tracer = opts.tracer ?? appendStartupTrace;
275
+ const flush = opts.flush;
276
+ const onFatal = opts.onFatal ?? ((kind, err) => {
277
+ try {
278
+ // 这里仍然走 console.error,是为了让终端 / 文件日志都看得见;但同步 trace 是主线
279
+ console.error(`[FATAL] ${kind}: ${err.message}\n${err.stack ?? ""}`);
280
+ } catch { /* ignore */ }
281
+ process.exit(1);
282
+ });
283
+ const onSignal = opts.onSignal;
284
+ const onBeforeExit = opts.onBeforeExit;
285
+
286
+ const handleFatal = (kind: "uncaughtException" | "unhandledRejection", reason: unknown): void => {
287
+ const err = coerceError(reason);
288
+ safeCall(tracer, `FATAL ${kind}`, {
289
+ message: err.message,
290
+ stack: truncateStack(err.stack),
291
+ });
292
+ safeCall(flush);
293
+ onFatal(kind, err);
294
+ };
295
+
296
+ return {
297
+ uncaughtException: (err) => handleFatal("uncaughtException", err),
298
+ unhandledRejection: (reason) => handleFatal("unhandledRejection", reason),
299
+ signalLogger: (sig) => {
300
+ safeCall(tracer, "signal received", { signal: sig });
301
+ safeCall(flush);
302
+ safeCall(onSignal, sig);
303
+ },
304
+ beforeExit: (code) => {
305
+ safeCall(tracer, "beforeExit", { code });
306
+ safeCall(onBeforeExit, code);
307
+ },
308
+ };
309
+ }
310
+
311
+ export interface InstallCrashLoggingResult {
312
+ handlers: CrashLoggingHandlers;
313
+ cleanup: () => void;
314
+ }
315
+
316
+ /**
317
+ * 把崩溃黑匣子 handler 装到 process 上,返回 cleanup。
318
+ *
319
+ * 注意:本函数只负责 trace + 默认 fatal 退出,**不**接管原有 SIGINT/SIGTERM 清理逻辑
320
+ * (如 relayServer.close)。让调用方在 installCrashLogging 之后再 process.on('SIGINT', ...)
321
+ * 注册自己的清理动作即可——Node EventEmitter 会按注册顺序调用所有 listener,trace 同步
322
+ * 写盘后再走清理,结果稳定。
323
+ */
324
+ export function installCrashLogging(opts: CrashHandlersOptions = {}): InstallCrashLoggingResult {
325
+ const handlers = buildCrashLoggingHandlers(opts);
326
+
327
+ const registrations: Array<{ event: string; fn: (...args: unknown[]) => void }> = [];
328
+ const add = (event: string, fn: (...args: unknown[]) => void): void => {
329
+ process.on(event as Parameters<typeof process.on>[0], fn);
330
+ registrations.push({ event, fn });
331
+ };
332
+
333
+ add("uncaughtException", (err) => handlers.uncaughtException(err));
334
+ add("unhandledRejection", (reason) => handlers.unhandledRejection(reason));
335
+ add("beforeExit", (code) => handlers.beforeExit(code as number));
336
+
337
+ const signals: NodeJS.Signals[] = ["SIGINT", "SIGTERM", "SIGHUP"];
338
+ if (process.platform === "win32") signals.push("SIGBREAK");
339
+ for (const sig of signals) {
340
+ add(sig, () => handlers.signalLogger(sig));
341
+ }
342
+
343
+ return {
344
+ handlers,
345
+ cleanup: () => {
346
+ for (const { event, fn } of registrations) {
347
+ process.off(event as Parameters<typeof process.off>[0], fn);
348
+ }
349
+ registrations.length = 0;
350
+ },
351
+ };
352
+ }
353
+
213
354
  // ---------------------------------------------------------------------------
214
355
  // 文件日志:同时输出到控制台和日志文件
215
356
  // ---------------------------------------------------------------------------
@@ -246,23 +387,22 @@ export function setupFileLogging(logDir: string, prefix: string): { logPath: str
246
387
  // 本地 WebSocket 中继服务器(同一端口、多客户端广播)
247
388
  // ---------------------------------------------------------------------------
248
389
 
249
- export function createRelayServer(port: number): {
250
- server: WebSocketServer;
390
+ /**
391
+ * 把 WS 中继挂到一个**已存在**的 httpServer 上(不负责 listen / close)。
392
+ *
393
+ * 之所以拆出来:setup → service「在线切换」复用同一个 httpServer,
394
+ * 避免 close + recreate 在 Windows 下的端口释放竞态(EADDRINUSE 抖动)。
395
+ *
396
+ * 调用方负责 httpServer 的生命周期管理(listen / 错误处理 / close)。
397
+ */
398
+ export function attachRelayWebSocket(httpServer: ReturnType<typeof createServer>): {
251
399
  broadcast: (data: unknown) => void;
400
+ close: () => void;
252
401
  } {
253
402
  const clients = new Set<WebSocket>();
254
- const server = new WebSocketServer({ host: "127.0.0.1", port });
255
-
256
- server.on("error", (err: NodeJS.ErrnoException) => {
257
- console.error(`[启动] 本地中继 WebSocket 监听失败:端口 ${port}(${err.code ?? "?"} — ${err.message})`);
258
- console.error(
259
- " 处理建议: 关闭占用该端口的其它程序,或在 .env 中设置 CHATCCC_PORT=其它未占用端口(如 18081)。"
260
- );
261
- printServiceDidNotStart(`本地中继端口 ${port} 无法监听(${err.code ?? "?"} — ${err.message})`);
262
- process.exit(1);
263
- });
403
+ const wsServer = new WebSocketServer({ server: httpServer });
264
404
 
265
- server.on("connection", (ws) => {
405
+ wsServer.on("connection", (ws) => {
266
406
  console.log(`[RELAY] Client connected (total: ${clients.size + 1})`);
267
407
  clients.add(ws);
268
408
  ws.on("close", () => {
@@ -272,8 +412,6 @@ export function createRelayServer(port: number): {
272
412
  ws.on("error", () => { clients.delete(ws); });
273
413
  });
274
414
 
275
- console.log(`[RELAY] Local relay listening on ws://127.0.0.1:${port}`);
276
-
277
415
  const broadcast = (data: unknown): void => {
278
416
  const json = typeof data === "string" ? data : JSON.stringify(data);
279
417
  for (const ws of clients) {
@@ -281,5 +419,40 @@ export function createRelayServer(port: number): {
281
419
  }
282
420
  };
283
421
 
284
- return { server, broadcast };
422
+ // close 用于 setup-activate 失败回滚:解绑 WSServer 在 httpServer 上注册的
423
+ // upgrade 监听并断开所有客户端,避免下次重试 attach 时重复挂载导致泄漏。
424
+ // httpServer 本身不在这里关——它在 setup 模式下还要继续给前端服务。
425
+ const close = (): void => {
426
+ for (const ws of clients) {
427
+ try { ws.terminate(); } catch { /* ok */ }
428
+ }
429
+ clients.clear();
430
+ try { wsServer.close(); } catch { /* ok */ }
431
+ };
432
+
433
+ return { broadcast, close };
434
+ }
435
+
436
+ export function createRelayServer(port: number): {
437
+ server: ReturnType<typeof createServer>;
438
+ broadcast: (data: unknown) => void;
439
+ } {
440
+ const httpServer = createServer();
441
+
442
+ httpServer.on("error", (err: NodeJS.ErrnoException) => {
443
+ console.error(`[启动] 本地中继 WebSocket 监听失败:端口 ${port}(${err.code ?? "?"} — ${err.message})`);
444
+ console.error(
445
+ " 处理建议: 关闭占用该端口的其它程序,或在 config.json 的 port 字段里改成其它未占用端口(如 18081)。"
446
+ );
447
+ printServiceDidNotStart(`本地中继端口 ${port} 无法监听(${err.code ?? "?"} — ${err.message})`);
448
+ process.exit(1);
449
+ });
450
+
451
+ const { broadcast } = attachRelayWebSocket(httpServer);
452
+
453
+ httpServer.listen(port, "127.0.0.1", () => {
454
+ console.log(`[RELAY] Local relay listening on ws://127.0.0.1:${port}`);
455
+ });
456
+
457
+ return { server: httpServer, broadcast };
285
458
  }