dispatcher.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. "use strict";
  2. var __defProp = Object.defineProperty;
  3. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  4. var __getOwnPropNames = Object.getOwnPropertyNames;
  5. var __hasOwnProp = Object.prototype.hasOwnProperty;
  6. var __export = (target, all) => {
  7. for (var name in all)
  8. __defProp(target, name, { get: all[name], enumerable: true });
  9. };
  10. var __copyProps = (to, from, except, desc) => {
  11. if (from && typeof from === "object" || typeof from === "function") {
  12. for (let key of __getOwnPropNames(from))
  13. if (!__hasOwnProp.call(to, key) && key !== except)
  14. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  15. }
  16. return to;
  17. };
  18. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  19. var dispatcher_exports = {};
  20. __export(dispatcher_exports, {
  21. Dispatcher: () => Dispatcher
  22. });
  23. module.exports = __toCommonJS(dispatcher_exports);
  24. var import_utils = require("playwright-core/lib/utils");
  25. var import_utils2 = require("playwright-core/lib/utils");
  26. var import_rebase = require("./rebase");
  27. var import_workerHost = require("./workerHost");
  28. var import_ipc = require("../common/ipc");
  29. class Dispatcher {
  30. constructor(config, reporter, failureTracker) {
  31. this._workerSlots = [];
  32. this._queue = [];
  33. this._workerLimitPerProjectId = /* @__PURE__ */ new Map();
  34. this._queuedOrRunningHashCount = /* @__PURE__ */ new Map();
  35. this._finished = new import_utils.ManualPromise();
  36. this._isStopped = true;
  37. this._extraEnvByProjectId = /* @__PURE__ */ new Map();
  38. this._producedEnvByProjectId = /* @__PURE__ */ new Map();
  39. this._config = config;
  40. this._reporter = reporter;
  41. this._failureTracker = failureTracker;
  42. for (const project of config.projects) {
  43. if (project.workers)
  44. this._workerLimitPerProjectId.set(project.id, project.workers);
  45. }
  46. }
  47. _findFirstJobToRun() {
  48. for (let index = 0; index < this._queue.length; index++) {
  49. const job = this._queue[index];
  50. const projectIdWorkerLimit = this._workerLimitPerProjectId.get(job.projectId);
  51. if (!projectIdWorkerLimit)
  52. return index;
  53. const runningWorkersWithSameProjectId = this._workerSlots.filter((w) => w.busy && w.worker && w.worker.projectId() === job.projectId).length;
  54. if (runningWorkersWithSameProjectId < projectIdWorkerLimit)
  55. return index;
  56. }
  57. return -1;
  58. }
  59. _scheduleJob() {
  60. if (this._isStopped)
  61. return;
  62. const jobIndex = this._findFirstJobToRun();
  63. if (jobIndex === -1)
  64. return;
  65. const job = this._queue[jobIndex];
  66. let workerIndex = this._workerSlots.findIndex((w) => !w.busy && w.worker && w.worker.hash() === job.workerHash && !w.worker.didSendStop());
  67. if (workerIndex === -1)
  68. workerIndex = this._workerSlots.findIndex((w) => !w.busy);
  69. if (workerIndex === -1) {
  70. return;
  71. }
  72. this._queue.splice(jobIndex, 1);
  73. const jobDispatcher = new JobDispatcher(job, this._reporter, this._failureTracker, () => this.stop().catch(() => {
  74. }));
  75. this._workerSlots[workerIndex].busy = true;
  76. this._workerSlots[workerIndex].jobDispatcher = jobDispatcher;
  77. void this._runJobInWorker(workerIndex, jobDispatcher).then(() => {
  78. this._workerSlots[workerIndex].jobDispatcher = void 0;
  79. this._workerSlots[workerIndex].busy = false;
  80. this._checkFinished();
  81. this._scheduleJob();
  82. });
  83. }
  84. async _runJobInWorker(index, jobDispatcher) {
  85. const job = jobDispatcher.job;
  86. if (jobDispatcher.skipWholeJob())
  87. return;
  88. let worker = this._workerSlots[index].worker;
  89. if (worker && (worker.hash() !== job.workerHash || worker.didSendStop())) {
  90. await worker.stop();
  91. worker = void 0;
  92. if (this._isStopped)
  93. return;
  94. }
  95. let startError;
  96. if (!worker) {
  97. worker = this._createWorker(job, index, (0, import_ipc.serializeConfig)(this._config, true));
  98. this._workerSlots[index].worker = worker;
  99. worker.on("exit", () => this._workerSlots[index].worker = void 0);
  100. startError = await worker.start();
  101. if (this._isStopped)
  102. return;
  103. }
  104. if (startError)
  105. jobDispatcher.onExit(startError);
  106. else
  107. jobDispatcher.runInWorker(worker);
  108. const result = await jobDispatcher.jobResult;
  109. this._updateCounterForWorkerHash(job.workerHash, -1);
  110. if (result.didFail)
  111. void worker.stop(
  112. true
  113. /* didFail */
  114. );
  115. else if (this._isWorkerRedundant(worker))
  116. void worker.stop();
  117. if (!this._isStopped && result.newJob) {
  118. this._queue.unshift(result.newJob);
  119. this._updateCounterForWorkerHash(result.newJob.workerHash, 1);
  120. }
  121. }
  122. _checkFinished() {
  123. if (this._finished.isDone())
  124. return;
  125. if (this._queue.length && !this._isStopped)
  126. return;
  127. if (this._workerSlots.some((w) => w.busy))
  128. return;
  129. this._finished.resolve();
  130. }
  131. _isWorkerRedundant(worker) {
  132. let workersWithSameHash = 0;
  133. for (const slot of this._workerSlots) {
  134. if (slot.worker && !slot.worker.didSendStop() && slot.worker.hash() === worker.hash())
  135. workersWithSameHash++;
  136. }
  137. return workersWithSameHash > this._queuedOrRunningHashCount.get(worker.hash());
  138. }
  139. _updateCounterForWorkerHash(hash, delta) {
  140. this._queuedOrRunningHashCount.set(hash, delta + (this._queuedOrRunningHashCount.get(hash) || 0));
  141. }
  142. async run(testGroups, extraEnvByProjectId) {
  143. this._extraEnvByProjectId = extraEnvByProjectId;
  144. this._queue = testGroups;
  145. for (const group of testGroups)
  146. this._updateCounterForWorkerHash(group.workerHash, 1);
  147. this._isStopped = false;
  148. this._workerSlots = [];
  149. if (this._failureTracker.hasReachedMaxFailures())
  150. void this.stop();
  151. for (let i = 0; i < this._config.config.workers; i++)
  152. this._workerSlots.push({ busy: false });
  153. for (let i = 0; i < this._workerSlots.length; i++)
  154. this._scheduleJob();
  155. this._checkFinished();
  156. await this._finished;
  157. }
  158. _createWorker(testGroup, parallelIndex, loaderData) {
  159. const projectConfig = this._config.projects.find((p) => p.id === testGroup.projectId);
  160. const outputDir = projectConfig.project.outputDir;
  161. const recoverFromStepErrors = this._failureTracker.canRecoverFromStepError();
  162. const worker = new import_workerHost.WorkerHost(testGroup, parallelIndex, loaderData, recoverFromStepErrors, this._extraEnvByProjectId.get(testGroup.projectId) || {}, outputDir);
  163. const handleOutput = (params) => {
  164. const chunk = chunkFromParams(params);
  165. if (worker.didFail()) {
  166. return { chunk };
  167. }
  168. const currentlyRunning = this._workerSlots[parallelIndex].jobDispatcher?.currentlyRunning();
  169. if (!currentlyRunning)
  170. return { chunk };
  171. return { chunk, test: currentlyRunning.test, result: currentlyRunning.result };
  172. };
  173. worker.on("stdOut", (params) => {
  174. const { chunk, test, result } = handleOutput(params);
  175. result?.stdout.push(chunk);
  176. this._reporter.onStdOut?.(chunk, test, result);
  177. });
  178. worker.on("stdErr", (params) => {
  179. const { chunk, test, result } = handleOutput(params);
  180. result?.stderr.push(chunk);
  181. this._reporter.onStdErr?.(chunk, test, result);
  182. });
  183. worker.on("teardownErrors", (params) => {
  184. this._failureTracker.onWorkerError();
  185. for (const error of params.fatalErrors)
  186. this._reporter.onError?.(error);
  187. });
  188. worker.on("exit", () => {
  189. const producedEnv = this._producedEnvByProjectId.get(testGroup.projectId) || {};
  190. this._producedEnvByProjectId.set(testGroup.projectId, { ...producedEnv, ...worker.producedEnv() });
  191. });
  192. return worker;
  193. }
  194. producedEnvByProjectId() {
  195. return this._producedEnvByProjectId;
  196. }
  197. async stop() {
  198. if (this._isStopped)
  199. return;
  200. this._isStopped = true;
  201. await Promise.all(this._workerSlots.map(({ worker }) => worker?.stop()));
  202. this._checkFinished();
  203. }
  204. }
  205. class JobDispatcher {
  206. constructor(job, reporter, failureTracker, stopCallback) {
  207. this.jobResult = new import_utils.ManualPromise();
  208. this._listeners = [];
  209. this._failedTests = /* @__PURE__ */ new Set();
  210. this._failedWithNonRetriableError = /* @__PURE__ */ new Set();
  211. this._remainingByTestId = /* @__PURE__ */ new Map();
  212. this._dataByTestId = /* @__PURE__ */ new Map();
  213. this._parallelIndex = 0;
  214. this._workerIndex = 0;
  215. this.job = job;
  216. this._reporter = reporter;
  217. this._failureTracker = failureTracker;
  218. this._stopCallback = stopCallback;
  219. this._remainingByTestId = new Map(this.job.tests.map((e) => [e.id, e]));
  220. }
  221. _onTestBegin(params) {
  222. const test = this._remainingByTestId.get(params.testId);
  223. if (!test) {
  224. return;
  225. }
  226. const result = test._appendTestResult();
  227. this._dataByTestId.set(test.id, { test, result, steps: /* @__PURE__ */ new Map() });
  228. result.parallelIndex = this._parallelIndex;
  229. result.workerIndex = this._workerIndex;
  230. result.startTime = new Date(params.startWallTime);
  231. this._reporter.onTestBegin?.(test, result);
  232. this._currentlyRunning = { test, result };
  233. }
  234. _onTestEnd(params) {
  235. if (this._failureTracker.hasReachedMaxFailures()) {
  236. params.status = "interrupted";
  237. params.errors = [];
  238. }
  239. const data = this._dataByTestId.get(params.testId);
  240. if (!data) {
  241. return;
  242. }
  243. this._dataByTestId.delete(params.testId);
  244. this._remainingByTestId.delete(params.testId);
  245. const { result, test } = data;
  246. result.duration = params.duration;
  247. result.errors = params.errors;
  248. result.error = result.errors[0];
  249. result.status = params.status;
  250. result.annotations = params.annotations;
  251. test.annotations = [...params.annotations];
  252. test.expectedStatus = params.expectedStatus;
  253. test.timeout = params.timeout;
  254. const isFailure = result.status !== "skipped" && result.status !== test.expectedStatus;
  255. if (isFailure)
  256. this._failedTests.add(test);
  257. if (params.hasNonRetriableError)
  258. this._addNonretriableTestAndSerialModeParents(test);
  259. this._reportTestEnd(test, result);
  260. this._currentlyRunning = void 0;
  261. }
  262. _addNonretriableTestAndSerialModeParents(test) {
  263. this._failedWithNonRetriableError.add(test);
  264. for (let parent = test.parent; parent; parent = parent.parent) {
  265. if (parent._parallelMode === "serial")
  266. this._failedWithNonRetriableError.add(parent);
  267. }
  268. }
  269. _onStepBegin(params) {
  270. const data = this._dataByTestId.get(params.testId);
  271. if (!data) {
  272. return;
  273. }
  274. const { result, steps, test } = data;
  275. const parentStep = params.parentStepId ? steps.get(params.parentStepId) : void 0;
  276. const step = {
  277. title: params.title,
  278. titlePath: () => {
  279. const parentPath = parentStep?.titlePath() || [];
  280. return [...parentPath, params.title];
  281. },
  282. parent: parentStep,
  283. category: params.category,
  284. startTime: new Date(params.wallTime),
  285. duration: -1,
  286. steps: [],
  287. attachments: [],
  288. annotations: [],
  289. location: params.location
  290. };
  291. steps.set(params.stepId, step);
  292. (parentStep || result).steps.push(step);
  293. this._reporter.onStepBegin?.(test, result, step);
  294. }
  295. _onStepEnd(params) {
  296. const data = this._dataByTestId.get(params.testId);
  297. if (!data) {
  298. return;
  299. }
  300. const { result, steps, test } = data;
  301. const step = steps.get(params.stepId);
  302. if (!step) {
  303. this._reporter.onStdErr?.("Internal error: step end without step begin: " + params.stepId, test, result);
  304. return;
  305. }
  306. step.duration = params.wallTime - step.startTime.getTime();
  307. if (params.error)
  308. step.error = params.error;
  309. if (params.suggestedRebaseline)
  310. (0, import_rebase.addSuggestedRebaseline)(step.location, params.suggestedRebaseline);
  311. step.annotations = params.annotations;
  312. steps.delete(params.stepId);
  313. this._reporter.onStepEnd?.(test, result, step);
  314. }
  315. _onStepRecoverFromError(resumeAfterStepError, params) {
  316. const data = this._dataByTestId.get(params.testId);
  317. if (!data) {
  318. resumeAfterStepError({ stepId: params.stepId, status: "failed" });
  319. return;
  320. }
  321. const { steps } = data;
  322. const step = steps.get(params.stepId);
  323. if (!step) {
  324. resumeAfterStepError({ stepId: params.stepId, status: "failed" });
  325. return;
  326. }
  327. const testError = {
  328. ...params.error,
  329. location: step.location
  330. };
  331. this._failureTracker.recoverFromStepError(params.stepId, testError, resumeAfterStepError);
  332. }
  333. _onAttach(params) {
  334. const data = this._dataByTestId.get(params.testId);
  335. if (!data) {
  336. return;
  337. }
  338. const attachment = {
  339. name: params.name,
  340. path: params.path,
  341. contentType: params.contentType,
  342. body: params.body !== void 0 ? Buffer.from(params.body, "base64") : void 0
  343. };
  344. data.result.attachments.push(attachment);
  345. if (params.stepId) {
  346. const step = data.steps.get(params.stepId);
  347. if (step)
  348. step.attachments.push(attachment);
  349. else
  350. this._reporter.onStdErr?.("Internal error: step id not found: " + params.stepId);
  351. }
  352. }
  353. _failTestWithErrors(test, errors) {
  354. const runData = this._dataByTestId.get(test.id);
  355. let result;
  356. if (runData) {
  357. result = runData.result;
  358. } else {
  359. result = test._appendTestResult();
  360. this._reporter.onTestBegin?.(test, result);
  361. }
  362. result.errors = [...errors];
  363. result.error = result.errors[0];
  364. result.status = errors.length ? "failed" : "skipped";
  365. this._reportTestEnd(test, result);
  366. this._failedTests.add(test);
  367. }
  368. _massSkipTestsFromRemaining(testIds, errors) {
  369. for (const test of this._remainingByTestId.values()) {
  370. if (!testIds.has(test.id))
  371. continue;
  372. if (!this._failureTracker.hasReachedMaxFailures()) {
  373. this._failTestWithErrors(test, errors);
  374. errors = [];
  375. }
  376. this._remainingByTestId.delete(test.id);
  377. }
  378. if (errors.length) {
  379. this._failureTracker.onWorkerError();
  380. for (const error of errors)
  381. this._reporter.onError?.(error);
  382. }
  383. }
  384. _onDone(params) {
  385. if (!this._remainingByTestId.size && !this._failedTests.size && !params.fatalErrors.length && !params.skipTestsDueToSetupFailure.length && !params.fatalUnknownTestIds && !params.unexpectedExitError) {
  386. this._finished({ didFail: false });
  387. return;
  388. }
  389. for (const testId of params.fatalUnknownTestIds || []) {
  390. const test = this._remainingByTestId.get(testId);
  391. if (test) {
  392. this._remainingByTestId.delete(testId);
  393. this._failTestWithErrors(test, [{ message: `Test not found in the worker process. Make sure test title does not change.` }]);
  394. }
  395. }
  396. if (params.fatalErrors.length) {
  397. this._massSkipTestsFromRemaining(new Set(this._remainingByTestId.keys()), params.fatalErrors);
  398. }
  399. this._massSkipTestsFromRemaining(new Set(params.skipTestsDueToSetupFailure), []);
  400. if (params.unexpectedExitError) {
  401. if (this._currentlyRunning)
  402. this._massSkipTestsFromRemaining(/* @__PURE__ */ new Set([this._currentlyRunning.test.id]), [params.unexpectedExitError]);
  403. else
  404. this._massSkipTestsFromRemaining(new Set(this._remainingByTestId.keys()), [params.unexpectedExitError]);
  405. }
  406. const retryCandidates = /* @__PURE__ */ new Set();
  407. const serialSuitesWithFailures = /* @__PURE__ */ new Set();
  408. for (const failedTest of this._failedTests) {
  409. if (this._failedWithNonRetriableError.has(failedTest))
  410. continue;
  411. retryCandidates.add(failedTest);
  412. let outermostSerialSuite;
  413. for (let parent = failedTest.parent; parent; parent = parent.parent) {
  414. if (parent._parallelMode === "serial")
  415. outermostSerialSuite = parent;
  416. }
  417. if (outermostSerialSuite && !this._failedWithNonRetriableError.has(outermostSerialSuite))
  418. serialSuitesWithFailures.add(outermostSerialSuite);
  419. }
  420. const testsBelongingToSomeSerialSuiteWithFailures = [...this._remainingByTestId.values()].filter((test) => {
  421. let parent = test.parent;
  422. while (parent && !serialSuitesWithFailures.has(parent))
  423. parent = parent.parent;
  424. return !!parent;
  425. });
  426. this._massSkipTestsFromRemaining(new Set(testsBelongingToSomeSerialSuiteWithFailures.map((test) => test.id)), []);
  427. for (const serialSuite of serialSuitesWithFailures) {
  428. serialSuite.allTests().forEach((test) => retryCandidates.add(test));
  429. }
  430. const remaining = [...this._remainingByTestId.values()];
  431. for (const test of retryCandidates) {
  432. if (test.results.length < test.retries + 1)
  433. remaining.push(test);
  434. }
  435. const newJob = remaining.length ? { ...this.job, tests: remaining } : void 0;
  436. this._finished({ didFail: true, newJob });
  437. }
  438. onExit(data) {
  439. const unexpectedExitError = data.unexpectedly ? {
  440. message: `Error: worker process exited unexpectedly (code=${data.code}, signal=${data.signal})`
  441. } : void 0;
  442. this._onDone({ skipTestsDueToSetupFailure: [], fatalErrors: [], unexpectedExitError });
  443. }
  444. _finished(result) {
  445. import_utils.eventsHelper.removeEventListeners(this._listeners);
  446. this.jobResult.resolve(result);
  447. }
  448. runInWorker(worker) {
  449. this._parallelIndex = worker.parallelIndex;
  450. this._workerIndex = worker.workerIndex;
  451. const runPayload = {
  452. file: this.job.requireFile,
  453. entries: this.job.tests.map((test) => {
  454. return { testId: test.id, retry: test.results.length };
  455. })
  456. };
  457. worker.runTestGroup(runPayload);
  458. const resumeAfterStepError = worker.resumeAfterStepError.bind(worker);
  459. this._listeners = [
  460. import_utils.eventsHelper.addEventListener(worker, "testBegin", this._onTestBegin.bind(this)),
  461. import_utils.eventsHelper.addEventListener(worker, "testEnd", this._onTestEnd.bind(this)),
  462. import_utils.eventsHelper.addEventListener(worker, "stepBegin", this._onStepBegin.bind(this)),
  463. import_utils.eventsHelper.addEventListener(worker, "stepEnd", this._onStepEnd.bind(this)),
  464. import_utils.eventsHelper.addEventListener(worker, "stepRecoverFromError", this._onStepRecoverFromError.bind(this, resumeAfterStepError)),
  465. import_utils.eventsHelper.addEventListener(worker, "attach", this._onAttach.bind(this)),
  466. import_utils.eventsHelper.addEventListener(worker, "done", this._onDone.bind(this)),
  467. import_utils.eventsHelper.addEventListener(worker, "exit", this.onExit.bind(this))
  468. ];
  469. }
  470. skipWholeJob() {
  471. const allTestsSkipped = this.job.tests.every((test) => test.expectedStatus === "skipped");
  472. if (allTestsSkipped && !this._failureTracker.hasReachedMaxFailures()) {
  473. for (const test of this.job.tests) {
  474. const result = test._appendTestResult();
  475. this._reporter.onTestBegin?.(test, result);
  476. result.status = "skipped";
  477. this._reportTestEnd(test, result);
  478. }
  479. return true;
  480. }
  481. return false;
  482. }
  483. currentlyRunning() {
  484. return this._currentlyRunning;
  485. }
  486. _reportTestEnd(test, result) {
  487. this._reporter.onTestEnd?.(test, result);
  488. const hadMaxFailures = this._failureTracker.hasReachedMaxFailures();
  489. this._failureTracker.onTestEnd(test, result);
  490. if (this._failureTracker.hasReachedMaxFailures()) {
  491. this._stopCallback();
  492. if (!hadMaxFailures)
  493. this._reporter.onError?.({ message: import_utils2.colors.red(`Testing stopped early after ${this._failureTracker.maxFailures()} maximum allowed failures.`) });
  494. }
  495. }
  496. }
  497. function chunkFromParams(params) {
  498. if (typeof params.text === "string")
  499. return params.text;
  500. return Buffer.from(params.buffer, "base64");
  501. }
  502. // Annotate the CommonJS export names for ESM import in node:
  503. 0 && (module.exports = {
  504. Dispatcher
  505. });