process-errors.ts 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. import { randomUUID } from "node:crypto";
  2. import {
  3. ZCODE_PROCESS_DIAGNOSTIC_PREFIX,
  4. ZCODE_PROCESS_DIAGNOSTIC_NAME_MAX_CHARS,
  5. ZCODE_PROCESS_DIAGNOSTIC_MESSAGE_MAX_CHARS,
  6. ZCODE_PROCESS_DIAGNOSTIC_STACK_MAX_CHARS,
  7. type ZCodeProcessDiagnostic,
  8. } from "@zcode/shared/process-diagnostic";
  9. export interface CliProcessErrorBoundaryTarget {
  10. on(event: string, listener: (...args: unknown[]) => void): unknown;
  11. off(event: string, listener: (...args: unknown[]) => void): unknown;
  12. }
  13. export interface CliProcessErrorBoundaryOptions {
  14. onFatal: (reason: unknown) => void;
  15. target?: CliProcessErrorBoundaryTarget;
  16. stderr?: {
  17. write(chunk: string): unknown;
  18. };
  19. }
  20. interface MonitoredException {
  21. error: unknown;
  22. origin: string;
  23. }
  24. /**
  25. * 为协议型 CLI 安装最后一道进程级异常边界。
  26. *
  27. * 先保留一次诊断,再交给入口 lifecycle 有界关闭。未知异常不能继续保活接单,
  28. * 更不能把坏 stderr 的写入失败递归报告;调用方必须先安装 stderr 输出边界。
  29. */
  30. export function installCliProcessErrorBoundary(
  31. options: CliProcessErrorBoundaryOptions,
  32. ): () => void {
  33. const target = options.target ?? (process as unknown as CliProcessErrorBoundaryTarget);
  34. const stderr = options.stderr ?? process.stderr;
  35. let monitoredException: MonitoredException | undefined;
  36. let fatal = false;
  37. const reportFatal = (
  38. kind: "uncaughtException" | "unhandledRejection",
  39. origin: string,
  40. reason: unknown,
  41. ) => {
  42. if (fatal) return;
  43. fatal = true;
  44. writeProcessErrorDiagnostic(stderr, kind, origin, reason);
  45. options.onFatal(reason);
  46. };
  47. const onUncaughtExceptionMonitor = (error: unknown, origin: unknown): void => {
  48. monitoredException = {
  49. error,
  50. origin: typeof origin === "string" ? origin : "uncaughtException",
  51. };
  52. };
  53. const onUncaughtException = (error: unknown): void => {
  54. const matchingMonitor = monitoredException?.error === error ? monitoredException : undefined;
  55. const origin = matchingMonitor ? matchingMonitor.origin : "uncaughtException";
  56. monitoredException = undefined;
  57. // Node strict 模式先触发 uncaughtException,处理后再触发 unhandledRejection。
  58. // 统一由 rejection listener 报告,避免同一 Promise 错误生成两个不同 errorId。
  59. if (origin === "unhandledRejection") return;
  60. reportFatal("uncaughtException", origin, error);
  61. };
  62. const onUnhandledRejection = (reason: unknown): void => {
  63. monitoredException = undefined;
  64. reportFatal("unhandledRejection", "unhandledRejection", reason);
  65. };
  66. target.on("uncaughtExceptionMonitor", onUncaughtExceptionMonitor);
  67. target.on("uncaughtException", onUncaughtException);
  68. target.on("unhandledRejection", onUnhandledRejection);
  69. return () => {
  70. target.off("uncaughtExceptionMonitor", onUncaughtExceptionMonitor);
  71. target.off("uncaughtException", onUncaughtException);
  72. target.off("unhandledRejection", onUnhandledRejection);
  73. monitoredException = undefined;
  74. };
  75. }
  76. function writeProcessErrorDiagnostic(
  77. stderr: { write(chunk: string): unknown },
  78. kind: "uncaughtException" | "unhandledRejection",
  79. origin: string,
  80. reason: unknown,
  81. ): void {
  82. try {
  83. const detail = formatProcessError(reason).slice(0, ZCODE_PROCESS_DIAGNOSTIC_STACK_MAX_CHARS);
  84. const diagnostic: ZCodeProcessDiagnostic = {
  85. version: 1,
  86. errorId: randomUUID(),
  87. kind,
  88. origin: origin === "unhandledRejection" ? origin : "uncaughtException",
  89. name: (reason instanceof Error ? reason.name || "Error" : "Error").slice(
  90. 0,
  91. ZCODE_PROCESS_DIAGNOSTIC_NAME_MAX_CHARS,
  92. ),
  93. message: (reason instanceof Error ? reason.message : detail).slice(
  94. 0,
  95. ZCODE_PROCESS_DIAGNOSTIC_MESSAGE_MAX_CHARS,
  96. ),
  97. ...(reason instanceof Error && reason.stack ? { stack: detail } : {}),
  98. occurredAt: Date.now(),
  99. };
  100. // 根因:进程存活时旧 stderr 只进 debug,Electron SDK 无法捕获子进程异常。
  101. // 增加单行结构化事件供 Host 立即转发,保留可读文本兼容旧 Host 和 crash tail。
  102. stderr.write(
  103. `${ZCODE_PROCESS_DIAGNOSTIC_PREFIX}${JSON.stringify(diagnostic)}\n[zcode] process error kind=${kind} origin=${origin}\n${detail}\n`,
  104. );
  105. } catch {
  106. // 诊断输出不能再次击穿进程级异常边界。
  107. }
  108. }
  109. function formatProcessError(reason: unknown): string {
  110. if (reason instanceof Error) {
  111. return reason.stack || `${reason.name}: ${reason.message}`;
  112. }
  113. if (typeof reason === "string") {
  114. return reason;
  115. }
  116. try {
  117. const serialized = JSON.stringify(reason);
  118. return serialized === undefined ? String(reason) : serialized;
  119. } catch {
  120. return String(reason);
  121. }
  122. }