e2e-prelaunched-electron.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. import { spawn, type ChildProcess } from "node:child_process";
  2. import { createWriteStream } from "node:fs";
  3. import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
  4. import { join } from "node:path";
  5. import { pipeline } from "node:stream/promises";
  6. type Options = {
  7. binary: string;
  8. args: string[];
  9. cwd: string;
  10. environment: NodeJS.ProcessEnv;
  11. profileDirectory: string;
  12. logDirectory: string;
  13. startupTimeoutMs?: number;
  14. };
  15. type RunningApp = {
  16. child: ChildProcess;
  17. exited: Promise<void>;
  18. exit?: string;
  19. logs: Promise<unknown>[];
  20. };
  21. type ReadyApp = { pid: number; debuggerAddress: string };
  22. const delay = (milliseconds: number) =>
  23. new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
  24. /** runner 是唯一 App 进程 owner;ChromeDriver 只连接,不负责创建应用。 */
  25. export class PrelaunchedElectronOwner {
  26. private current?: RunningApp;
  27. private starting?: Promise<ReadyApp>;
  28. private ready?: ReadyApp;
  29. private attached?: { sessionId: string; pid: number };
  30. private port?: number;
  31. private browserIdentity?: string;
  32. private generation = 0;
  33. constructor(private readonly options: Options) {}
  34. start(): Promise<ReadyApp> {
  35. if (this.starting) return this.starting;
  36. if (this.current && this.current.exit === undefined && this.ready)
  37. return Promise.resolve(this.ready);
  38. const task = this.launch().finally(() => {
  39. if (this.starting === task) this.starting = undefined;
  40. });
  41. this.starting = task;
  42. return task;
  43. }
  44. attach(sessionId: string, pid: number): void {
  45. if (!this.ready || !this.current || this.current.exit !== undefined)
  46. throw new Error("Cannot attach a session without a running App");
  47. if (pid !== this.ready.pid) throw new Error("Connected process does not belong to this runner");
  48. if (this.attached && this.attached.sessionId !== sessionId)
  49. throw new Error("App already belongs to another driver session");
  50. this.attached = { sessionId, pid };
  51. }
  52. async closeSession(sessionId: string, requestQuit: () => Promise<unknown>): Promise<void> {
  53. if (this.attached?.sessionId !== sessionId || this.current?.child.pid !== this.attached.pid)
  54. return;
  55. // reloadSession 会再次删除旧协议会话;先撤销绑定,旧删除不得结束刚启动的新 App。
  56. this.attached = undefined;
  57. const current = this.current;
  58. if (current.exit !== undefined) return;
  59. try {
  60. await requestQuit();
  61. } catch (error) {
  62. if (current.exit === undefined) throw error;
  63. }
  64. if (!(await waitForOwnedExit(current, 10000)))
  65. throw new Error("App did not exit after quit request");
  66. await Promise.allSettled(current.logs);
  67. }
  68. async dispose(): Promise<void> {
  69. const current = this.current;
  70. this.attached = undefined;
  71. if (!current) return;
  72. if (current.exit === undefined) {
  73. current.child.kill("SIGTERM");
  74. await waitForOwnedExit(current, 3000);
  75. if (current.exit === undefined) {
  76. current.child.kill("SIGKILL");
  77. await current.exited;
  78. }
  79. }
  80. await Promise.allSettled(current.logs);
  81. }
  82. private async launch(): Promise<ReadyApp> {
  83. if (this.current) await Promise.allSettled(this.current.logs);
  84. const { profileDirectory, logDirectory, startupTimeoutMs = 20000 } = this.options;
  85. await mkdir(profileDirectory, { recursive: true });
  86. await mkdir(logDirectory, { recursive: true });
  87. const activePortPath = join(profileDirectory, "DevToolsActivePort");
  88. await rm(activePortPath, { force: true });
  89. const environment = { ...this.options.environment };
  90. // ChromeDriver 原本会清掉 NODE_OPTIONS;独立启动也不能继承 WDIO 的 tsx loader。
  91. delete environment.NODE_OPTIONS;
  92. delete environment.ELECTRON_RUN_AS_NODE;
  93. const args = this.options.args.filter(
  94. (arg) => !arg.startsWith("--remote-debugging-port=") && !arg.startsWith("--user-data-dir="),
  95. );
  96. args.push(`--remote-debugging-port=${this.port ?? 0}`, `--user-data-dir=${profileDirectory}`);
  97. const child = spawn(this.options.binary, args, {
  98. cwd: this.options.cwd,
  99. env: environment,
  100. stdio: ["ignore", "pipe", "pipe"],
  101. });
  102. const generation = ++this.generation;
  103. const current: RunningApp = { child, exited: Promise.resolve(), logs: [] };
  104. current.exited = new Promise<void>((resolve) => {
  105. child.once("error", (error) => {
  106. current.exit = String(error);
  107. resolve();
  108. });
  109. child.once("exit", (code, signal) => {
  110. current.exit = `code=${code} signal=${signal}`;
  111. const receipt = writeFile(
  112. join(logDirectory, `app-${generation}.exit.json`),
  113. JSON.stringify({ pid: child.pid, code, signal }),
  114. );
  115. current.logs.push(receipt);
  116. void receipt.finally(resolve).catch(() => undefined);
  117. });
  118. });
  119. current.logs = [
  120. pipeline(
  121. child.stdout!,
  122. createWriteStream(join(logDirectory, `app-${generation}.stdout.log`)),
  123. ).catch(() => undefined),
  124. pipeline(
  125. child.stderr!,
  126. createWriteStream(join(logDirectory, `app-${generation}.stderr.log`)),
  127. ).catch(() => undefined),
  128. ];
  129. this.current = current;
  130. this.ready = undefined;
  131. const deadline = Date.now() + startupTimeoutMs;
  132. try {
  133. while (Date.now() < deadline) {
  134. if (current.exit !== undefined)
  135. throw new Error(`App exited before debugging ready: ${current.exit}`);
  136. if (!this.port) {
  137. try {
  138. const port = Number((await readFile(activePortPath, "utf8")).split("\n")[0]);
  139. if (Number.isInteger(port) && port > 0 && port <= 65535) this.port = port;
  140. } catch (error) {
  141. // 根因:Windows 上 Chromium 写 DevToolsActivePort 期间独占该文件,此时读取报 EBUSY;
  142. // 原来只把 ENOENT 当未就绪,EBUSY 直接让 App 启动失败。两者都说明端口尚未可读,继续轮询。
  143. const code = (error as NodeJS.ErrnoException).code;
  144. if (code !== "ENOENT" && code !== "EBUSY") throw error;
  145. }
  146. }
  147. if (this.port) {
  148. try {
  149. const response = await fetch(`http://127.0.0.1:${this.port}/json/version`, {
  150. signal: AbortSignal.timeout(500),
  151. });
  152. const value = (await response.json()) as { webSocketDebuggerUrl?: string };
  153. if (
  154. response.ok &&
  155. value.webSocketDebuggerUrl &&
  156. value.webSocketDebuggerUrl !== this.browserIdentity
  157. ) {
  158. this.browserIdentity = value.webSocketDebuggerUrl;
  159. this.ready = { pid: child.pid!, debuggerAddress: `127.0.0.1:${this.port}` };
  160. await writeFile(
  161. join(logDirectory, `app-${generation}.launch.json`),
  162. JSON.stringify({
  163. ...this.ready,
  164. binary: this.options.binary,
  165. args,
  166. cwd: this.options.cwd,
  167. }),
  168. );
  169. return this.ready;
  170. }
  171. } catch {
  172. /* 调试端口尚未监听;以真实端口响应与进程退出作为边界。 */
  173. }
  174. }
  175. await delay(50);
  176. }
  177. throw new Error("App debugging endpoint did not become ready");
  178. } catch (error) {
  179. await this.dispose();
  180. throw error;
  181. }
  182. }
  183. }
  184. async function waitForOwnedExit(current: RunningApp, timeoutMs: number): Promise<boolean> {
  185. let timer: ReturnType<typeof setTimeout> | undefined;
  186. try {
  187. return await Promise.race([
  188. current.exited.then(() => true),
  189. new Promise<boolean>((resolve) => {
  190. timer = setTimeout(() => resolve(false), timeoutMs);
  191. }),
  192. ]);
  193. } finally {
  194. if (timer) clearTimeout(timer);
  195. }
  196. }
  197. type OwnedAppCallbacks = {
  198. owner: PrelaunchedElectronOwner;
  199. restartAfterExit(): Promise<ReadyApp>;
  200. bind(browser: WebdriverIO.Browser): Promise<void>;
  201. };
  202. type BrowserWithOwnedApp = WebdriverIO.Browser & { __zcodeE2EOwnedApp?: OwnedAppCallbacks };
  203. export async function restartPrelaunchedElectronAfterExit(
  204. browser: WebdriverIO.Browser,
  205. ): Promise<void> {
  206. await (browser as BrowserWithOwnedApp).__zcodeE2EOwnedApp?.restartAfterExit();
  207. }
  208. export async function bindPrelaunchedElectronSession(
  209. browser: WebdriverIO.Browser,
  210. owner?: PrelaunchedElectronOwner,
  211. ): Promise<void> {
  212. const bound = browser as BrowserWithOwnedApp;
  213. if (owner && !bound.__zcodeE2EOwnedApp) {
  214. // config与spec可被loader实例化多次;操作闭包显式绑定到同一个browser,不查模块全局状态。
  215. Object.defineProperty(bound, "__zcodeE2EOwnedApp", {
  216. configurable: true,
  217. value: {
  218. owner,
  219. restartAfterExit: () => owner.start(),
  220. bind: async (current: WebdriverIO.Browser) =>
  221. owner.attach(current.sessionId, await current.electron.execute(() => process.pid)),
  222. } satisfies OwnedAppCallbacks,
  223. });
  224. browser.overwriteCommand(
  225. "deleteSession" as never,
  226. async function (
  227. this: WebdriverIO.Browser,
  228. original: (...args: unknown[]) => Promise<unknown>,
  229. ...args: unknown[]
  230. ) {
  231. const sessionId = this.sessionId;
  232. const result = await original(...args);
  233. // attach会话删除只分离driver;通过既有main bridge请求正常退出,再交给真实退出屏障。
  234. await owner.closeSession(sessionId, () =>
  235. this.electron.execute((electron) => electron.app.quit()),
  236. );
  237. return result;
  238. } as never,
  239. );
  240. }
  241. if (owner && bound.__zcodeE2EOwnedApp?.owner !== owner)
  242. throw new Error("Browser already has another App owner");
  243. await bound.__zcodeE2EOwnedApp?.bind(browser);
  244. }