electron-window-recorder-timeout.ts 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import { spawn } from "node:child_process";
  2. const DEFAULT_COMMAND_TIMEOUT_MS = 30_000;
  3. const MAX_COMMAND_TIMEOUT_MS = 5 * 60_000;
  4. export interface RunElectronRecordingCommandOptions {
  5. signal?: AbortSignal;
  6. timeoutMs?: number;
  7. }
  8. export function runElectronRecordingCommand(
  9. command: string,
  10. args: string[],
  11. options: RunElectronRecordingCommandOptions = {},
  12. ): Promise<void> {
  13. return new Promise((resolveCommand, reject) => {
  14. const child = spawn(command, args, { stdio: ["ignore", "ignore", "pipe"] });
  15. let stderr = "";
  16. let settled = false;
  17. let timeout: ReturnType<typeof setTimeout> | undefined;
  18. const cleanup = () => {
  19. if (timeout) {
  20. clearTimeout(timeout);
  21. }
  22. options.signal?.removeEventListener("abort", handleAbort);
  23. };
  24. const finish = (error?: Error) => {
  25. if (settled) {
  26. return;
  27. }
  28. settled = true;
  29. cleanup();
  30. if (error) {
  31. reject(error);
  32. } else {
  33. resolveCommand();
  34. }
  35. };
  36. const terminate = (error: Error) => {
  37. // 修复原因:ffmpeg 卡死时只 reject promise 会留下子进程;必须先强制终止,
  38. // close/error 后续回调再通过 settled 统一去重和清理 timer。
  39. if (!child.killed) {
  40. child.kill("SIGKILL");
  41. }
  42. finish(error);
  43. };
  44. const handleAbort = () => {
  45. terminate(asError(options.signal?.reason, `${command} aborted`));
  46. };
  47. child.stderr?.on("data", (chunk) => {
  48. stderr = `${stderr}${String(chunk)}`.slice(-2000);
  49. });
  50. child.on("error", (error) => finish(error));
  51. child.on("close", (code) => {
  52. if (code === 0) {
  53. finish();
  54. return;
  55. }
  56. finish(new Error(`${command} exited with ${code}: ${stderr}`));
  57. });
  58. if (options.signal?.aborted) {
  59. handleAbort();
  60. return;
  61. }
  62. options.signal?.addEventListener("abort", handleAbort, { once: true });
  63. const timeoutMs = normalizeTimeoutMs(options.timeoutMs);
  64. timeout = setTimeout(() => {
  65. terminate(new Error(`${command} timed out after ${timeoutMs}ms`));
  66. }, timeoutMs);
  67. timeout.unref?.();
  68. });
  69. }
  70. export async function runWithTimeout<T>(
  71. run: () => Promise<T>,
  72. timeoutMs: number,
  73. label: string,
  74. onTimeout?: (error: Error) => void,
  75. ): Promise<T> {
  76. let timeout: ReturnType<typeof setTimeout> | undefined;
  77. const timeoutPromise = new Promise<never>((_resolve, reject) => {
  78. timeout = setTimeout(() => {
  79. const error = new Error(`${label} timed out after ${timeoutMs}ms`);
  80. onTimeout?.(error);
  81. reject(error);
  82. }, timeoutMs);
  83. });
  84. try {
  85. return await Promise.race([run(), timeoutPromise]);
  86. } finally {
  87. if (timeout) {
  88. clearTimeout(timeout);
  89. }
  90. }
  91. }
  92. function normalizeTimeoutMs(value: number | undefined): number {
  93. if (!Number.isFinite(value) || !value) {
  94. return DEFAULT_COMMAND_TIMEOUT_MS;
  95. }
  96. return Math.max(1, Math.min(MAX_COMMAND_TIMEOUT_MS, Math.round(value)));
  97. }
  98. function asError(value: unknown, fallback: string): Error {
  99. if (value instanceof Error) {
  100. return value;
  101. }
  102. return new Error(value ? String(value) : fallback);
  103. }