e2e-step-process.mjs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. import { spawn } from "node:child_process";
  2. import process from "node:process";
  3. import {
  4. quoteArgsForWindowsShell,
  5. resolveSpawnRuntimeOptions,
  6. } from "../../../scripts/spawn-command.mjs";
  7. function formatStepError(error) {
  8. return error instanceof Error ? error.message : String(error);
  9. }
  10. function createStepStartFailure(error) {
  11. return { exitCode: 1, error: formatStepError(error) };
  12. }
  13. function normalizeStepExecution(value) {
  14. if (value && typeof value === "object" && "result" in value) {
  15. return {
  16. result: Promise.resolve(value.result),
  17. terminate: typeof value.terminate === "function" ? () => value.terminate() : undefined,
  18. };
  19. }
  20. return { result: Promise.resolve(value), terminate: undefined };
  21. }
  22. function normalizeStepResult(result) {
  23. if (!result || typeof result !== "object") {
  24. return createStepStartFailure(new Error("step returned no result"));
  25. }
  26. return {
  27. exitCode: Number.isInteger(result.exitCode) ? result.exitCode : 1,
  28. ...(result.signal ? { signal: String(result.signal) } : {}),
  29. ...(result.error ? { error: String(result.error) } : {}),
  30. };
  31. }
  32. export function startStepExecution(runStep, step) {
  33. let execution;
  34. try {
  35. execution = normalizeStepExecution(runStep(step));
  36. } catch (error) {
  37. execution = normalizeStepExecution(createStepStartFailure(error));
  38. }
  39. return {
  40. result: execution.result.then(normalizeStepResult, (error) => createStepStartFailure(error)),
  41. terminate: execution.terminate,
  42. };
  43. }
  44. export function spawnCancellableStep(step) {
  45. if (step.timeoutMs !== undefined && (!Number.isFinite(step.timeoutMs) || step.timeoutMs <= 0)) {
  46. return {
  47. result: Promise.resolve(createStepStartFailure(new Error("Invalid step timeout"))),
  48. terminate() {},
  49. };
  50. }
  51. let child;
  52. try {
  53. const runtimeOptions = resolveSpawnRuntimeOptions(step.command);
  54. child = spawn(
  55. step.command,
  56. runtimeOptions.shell ? quoteArgsForWindowsShell(step.args) : step.args,
  57. {
  58. cwd: step.cwd,
  59. env: step.env,
  60. stdio: "inherit",
  61. // 编译器可能派生后代;POSIX 用独立进程组,Windows 沿用下方 taskkill /T。
  62. detached: step.killProcessTree === true && process.platform !== "win32",
  63. ...runtimeOptions,
  64. },
  65. );
  66. } catch (error) {
  67. return {
  68. result: Promise.resolve(createStepStartFailure(error)),
  69. terminate() {},
  70. };
  71. }
  72. let forceKillTimer;
  73. let timeoutTimer;
  74. let timedOut = false;
  75. let terminationRequested = false;
  76. const result = new Promise((resolveRun) => {
  77. let settled = false;
  78. const settle = (value) => {
  79. if (settled) return;
  80. settled = true;
  81. if (forceKillTimer) clearTimeout(forceKillTimer);
  82. if (timeoutTimer) clearTimeout(timeoutTimer);
  83. resolveRun(value);
  84. };
  85. // 修复原因:spawn 的 error 过去会 reject Promise.all,导致其他 shard 未等待、manifest 未写入。
  86. child.once("error", (error) => settle(createStepStartFailure(error)));
  87. child.once("close", (code, signal) => {
  88. settle({
  89. exitCode: timedOut ? 1 : (code ?? 1),
  90. signal: signal ?? undefined,
  91. ...(timedOut ? { error: `step timed out after ${step.timeoutMs}ms` } : {}),
  92. });
  93. });
  94. });
  95. const execution = {
  96. result,
  97. terminate() {
  98. if (
  99. terminationRequested ||
  100. !child.pid ||
  101. (!step.killProcessTree && (child.exitCode !== null || child.signalCode !== null))
  102. ) {
  103. return;
  104. }
  105. terminationRequested = true;
  106. if (timeoutTimer) clearTimeout(timeoutTimer);
  107. if (process.platform === "win32") {
  108. // pnpm 下还有 WDIO/Electron 等后代进程,Windows 必须按进程树强制终止。
  109. const killChildFallback = () => {
  110. try {
  111. child.kill();
  112. } catch {
  113. // 原进程可能已在 taskkill 启动失败前退出。
  114. }
  115. };
  116. let taskkill;
  117. try {
  118. taskkill = spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
  119. stdio: "ignore",
  120. windowsHide: true,
  121. });
  122. } catch {
  123. killChildFallback();
  124. return;
  125. }
  126. taskkill.once("error", killChildFallback);
  127. taskkill.once("close", (code) => {
  128. if (code !== 0 && child.exitCode === null && child.signalCode === null) {
  129. killChildFallback();
  130. }
  131. });
  132. return;
  133. }
  134. try {
  135. const kill = (signal) =>
  136. step.killProcessTree ? process.kill(-child.pid, signal) : child.kill(signal);
  137. const signal = step.killSignal ?? "SIGTERM";
  138. kill(signal);
  139. if (signal !== "SIGKILL")
  140. forceKillTimer = setTimeout(() => {
  141. try {
  142. kill("SIGKILL");
  143. } catch {
  144. // SIGTERM 后已经退出时无需继续处理。
  145. }
  146. }, 5_000);
  147. forceKillTimer?.unref?.();
  148. } catch {
  149. // close/error 会负责产生最终结果,终止请求本身不应绕过收口。
  150. }
  151. },
  152. };
  153. if (step.timeoutMs !== undefined) {
  154. timeoutTimer = setTimeout(() => {
  155. timedOut = true;
  156. execution.terminate();
  157. }, step.timeoutMs);
  158. }
  159. return execution;
  160. }