stdio-lifecycle.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. import type { Readable } from "node:stream";
  2. const TERMINATION_SIGNALS = ["SIGHUP", "SIGTERM", "SIGINT"] as const;
  3. const DEFAULT_RPC_STOP_TIMEOUT_MS = 1_000;
  4. const DEFAULT_SERVICE_DISPOSE_TIMEOUT_MS = 3_500;
  5. type StdioShutdownPhase = "rpc-stop" | "service-dispose";
  6. interface StdioProcessSignalSource {
  7. on(signal: (typeof TERMINATION_SIGNALS)[number], listener: () => void): unknown;
  8. }
  9. interface StdioProcessLifecycleOptions {
  10. stdin: Readable;
  11. signalSource: StdioProcessSignalSource;
  12. log: (...args: unknown[]) => void;
  13. stopRpc: () => Promise<void>;
  14. dispose: () => Promise<void>;
  15. exit: (code: number) => never | void;
  16. shutdownTimeoutMs?: number;
  17. rpcStopTimeoutMs?: number;
  18. serviceDisposeTimeoutMs?: number;
  19. }
  20. export function registerStdioProcessLifecycle(options: StdioProcessLifecycleOptions): void {
  21. const { stdin, signalSource, log, stopRpc, dispose, exit } = options;
  22. const rpcStopTimeoutMs = Math.max(
  23. options.rpcStopTimeoutMs ?? options.shutdownTimeoutMs ?? DEFAULT_RPC_STOP_TIMEOUT_MS,
  24. 0,
  25. );
  26. const serviceDisposeTimeoutMs = Math.max(
  27. options.serviceDisposeTimeoutMs ??
  28. options.shutdownTimeoutMs ??
  29. DEFAULT_SERVICE_DISPOSE_TIMEOUT_MS,
  30. 0,
  31. );
  32. let shutdownStarted = false;
  33. let requestedExitCode = 0;
  34. const requestShutdown = (exitCode: number): void => {
  35. requestedExitCode = Math.max(requestedExitCode, exitCode);
  36. if (shutdownStarted) {
  37. return;
  38. }
  39. shutdownStarted = true;
  40. void (async () => {
  41. const runPhase = async (
  42. phase: StdioShutdownPhase,
  43. operation: () => Promise<void>,
  44. failureMessage: string,
  45. timeoutMs: number,
  46. ): Promise<boolean> => {
  47. let timeout: ReturnType<typeof setTimeout> | undefined;
  48. const operationResult = operation().then(
  49. () => ({ kind: "completed" as const }),
  50. (error: unknown) => ({ kind: "failed" as const, error }),
  51. );
  52. const timedOut = new Promise<{ kind: "timed-out" }>((resolve) => {
  53. // timer 不能 unref,否则外部 Promise 永久 pending 时它无法独立保证收口。
  54. timeout = setTimeout(() => resolve({ kind: "timed-out" }), timeoutMs);
  55. });
  56. const result = await Promise.race([operationResult, timedOut]);
  57. if (timeout) {
  58. clearTimeout(timeout);
  59. }
  60. if (result.kind === "timed-out") {
  61. log("stdio shutdown timed out", { phase, timeoutMs });
  62. return false;
  63. }
  64. if (result.kind === "failed") {
  65. log(failureMessage, result.error);
  66. return false;
  67. }
  68. return true;
  69. };
  70. // 整个 cleanup 不能只设一个 race;stopRpc 一旦超时就直接 exit,
  71. // service dispose 永远没有机会关闭 Agent 子进程。两个外部异步边界必须各自有界并独立推进。
  72. if (
  73. !(await runPhase("rpc-stop", stopRpc, "stdio shutdown RPC stop failed", rpcStopTimeoutMs))
  74. ) {
  75. requestedExitCode = 1;
  76. }
  77. if (
  78. !(await runPhase(
  79. "service-dispose",
  80. dispose,
  81. "stdio shutdown cleanup failed",
  82. serviceDisposeTimeoutMs,
  83. ))
  84. ) {
  85. requestedExitCode = 1;
  86. }
  87. log("stdio shutdown completed", { exitCode: requestedExitCode });
  88. exit(requestedExitCode);
  89. })();
  90. };
  91. // 远程项目静置时可能长时间没有 client->server RPC 输入,但窗口仍然打开。
  92. // 不能再按空闲时间主动退出;只在 stdio 明确关闭或报错时结束远端 server,
  93. // 让远程连接生命周期跟随用户关闭项目/应用或底层 SSH 断连。
  94. stdin.on("end", () => {
  95. log("stdin closed, shutting down");
  96. requestShutdown(0);
  97. });
  98. stdin.on("error", (error) => {
  99. log("stdin error, shutting down", error);
  100. requestShutdown(1);
  101. });
  102. for (const signal of TERMINATION_SIGNALS) {
  103. signalSource.on(signal, () => {
  104. // SSH 断连在不同 sshd/shell 上可能表现为 stdin EOF,也可能先向前台进程发送信号。
  105. // 两类入口必须进入同一个幂等清理链路,否则 detached Agent 会绕过父进程退出而成为孤儿。
  106. log("termination signal received, shutting down", signal);
  107. requestShutdown(1);
  108. });
  109. }
  110. }