MultiCompiler.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const asyncLib = require("neo-async");
  7. const { MultiHook, SyncHook } = require("tapable");
  8. const ConcurrentCompilationError = require("./ConcurrentCompilationError");
  9. const MultiStats = require("./MultiStats");
  10. const MultiWatching = require("./MultiWatching");
  11. const WebpackError = require("./WebpackError");
  12. const ArrayQueue = require("./util/ArrayQueue");
  13. /**
  14. * @template T
  15. * @typedef {import("tapable").AsyncSeriesHook<T>} AsyncSeriesHook<T>
  16. */
  17. /**
  18. * @template T
  19. * @template R
  20. * @typedef {import("tapable").SyncBailHook<T, R>} SyncBailHook<T, R>
  21. */
  22. /** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */
  23. /** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */
  24. /** @typedef {import("./Compiler")} Compiler */
  25. /**
  26. * @template T
  27. * @template [R=void]
  28. * @typedef {import("./webpack").Callback<T, R>} Callback
  29. */
  30. /** @typedef {import("./webpack").ErrorCallback} ErrorCallback */
  31. /** @typedef {import("./Stats")} Stats */
  32. /** @typedef {import("./logging/Logger").Logger} Logger */
  33. /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
  34. /** @typedef {import("./util/fs").IntermediateFileSystem} IntermediateFileSystem */
  35. /** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */
  36. /** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */
  37. /**
  38. * @callback RunWithDependenciesHandler
  39. * @param {Compiler} compiler
  40. * @param {Callback<MultiStats>} callback
  41. * @returns {void}
  42. */
  43. /**
  44. * @typedef {object} MultiCompilerOptions
  45. * @property {number=} parallelism how many Compilers are allows to run at the same time in parallel
  46. */
  47. /** @typedef {ReadonlyArray<WebpackOptions> & MultiCompilerOptions} MultiWebpackOptions */
  48. const CLASS_NAME = "MultiCompiler";
  49. module.exports = class MultiCompiler {
  50. /**
  51. * @param {Compiler[] | Record<string, Compiler>} compilers child compilers
  52. * @param {MultiCompilerOptions} options options
  53. */
  54. constructor(compilers, options) {
  55. if (!Array.isArray(compilers)) {
  56. /** @type {Compiler[]} */
  57. compilers = Object.keys(compilers).map((name) => {
  58. /** @type {Record<string, Compiler>} */
  59. (compilers)[name].name = name;
  60. return /** @type {Record<string, Compiler>} */ (compilers)[name];
  61. });
  62. }
  63. this.hooks = Object.freeze({
  64. /** @type {SyncHook<[MultiStats]>} */
  65. done: new SyncHook(["stats"]),
  66. /** @type {MultiHook<SyncHook<[string | null, number]>>} */
  67. invalid: new MultiHook(compilers.map((c) => c.hooks.invalid)),
  68. /** @type {MultiHook<AsyncSeriesHook<[Compiler]>>} */
  69. run: new MultiHook(compilers.map((c) => c.hooks.run)),
  70. /** @type {SyncHook<[]>} */
  71. watchClose: new SyncHook([]),
  72. /** @type {MultiHook<AsyncSeriesHook<[Compiler]>>} */
  73. watchRun: new MultiHook(compilers.map((c) => c.hooks.watchRun)),
  74. /** @type {MultiHook<SyncBailHook<[string, string, EXPECTED_ANY[] | undefined], true | void>>} */
  75. infrastructureLog: new MultiHook(
  76. compilers.map((c) => c.hooks.infrastructureLog)
  77. )
  78. });
  79. this.compilers = compilers;
  80. /** @type {MultiCompilerOptions} */
  81. this._options = {
  82. parallelism: options.parallelism || Infinity
  83. };
  84. /** @type {WeakMap<Compiler, string[]>} */
  85. this.dependencies = new WeakMap();
  86. this.running = false;
  87. /** @type {(Stats | null)[]} */
  88. const compilerStats = this.compilers.map(() => null);
  89. let doneCompilers = 0;
  90. for (let index = 0; index < this.compilers.length; index++) {
  91. const compiler = this.compilers[index];
  92. const compilerIndex = index;
  93. let compilerDone = false;
  94. // eslint-disable-next-line no-loop-func
  95. compiler.hooks.done.tap(CLASS_NAME, (stats) => {
  96. if (!compilerDone) {
  97. compilerDone = true;
  98. doneCompilers++;
  99. }
  100. compilerStats[compilerIndex] = stats;
  101. if (doneCompilers === this.compilers.length) {
  102. this.hooks.done.call(
  103. new MultiStats(/** @type {Stats[]} */ (compilerStats))
  104. );
  105. }
  106. });
  107. // eslint-disable-next-line no-loop-func
  108. compiler.hooks.invalid.tap(CLASS_NAME, () => {
  109. if (compilerDone) {
  110. compilerDone = false;
  111. doneCompilers--;
  112. }
  113. });
  114. }
  115. this._validateCompilersOptions();
  116. }
  117. _validateCompilersOptions() {
  118. if (this.compilers.length < 2) return;
  119. /**
  120. * @param {Compiler} compiler compiler
  121. * @param {WebpackError} warning warning
  122. */
  123. const addWarning = (compiler, warning) => {
  124. compiler.hooks.thisCompilation.tap(CLASS_NAME, (compilation) => {
  125. compilation.warnings.push(warning);
  126. });
  127. };
  128. /** @type {Set<string>} */
  129. const cacheNames = new Set();
  130. for (const compiler of this.compilers) {
  131. if (compiler.options.cache && "name" in compiler.options.cache) {
  132. const name = /** @type {string} */ (compiler.options.cache.name);
  133. if (cacheNames.has(name)) {
  134. addWarning(
  135. compiler,
  136. new WebpackError(
  137. `${
  138. compiler.name
  139. ? `Compiler with name "${compiler.name}" doesn't use unique cache name. `
  140. : ""
  141. }Please set unique "cache.name" option. Name "${name}" already used.`
  142. )
  143. );
  144. } else {
  145. cacheNames.add(name);
  146. }
  147. }
  148. }
  149. }
  150. get options() {
  151. return Object.assign(
  152. this.compilers.map((c) => c.options),
  153. this._options
  154. );
  155. }
  156. get outputPath() {
  157. let commonPath = this.compilers[0].outputPath;
  158. for (const compiler of this.compilers) {
  159. while (
  160. compiler.outputPath.indexOf(commonPath) !== 0 &&
  161. /[/\\]/.test(commonPath)
  162. ) {
  163. commonPath = commonPath.replace(/[/\\][^/\\]*$/, "");
  164. }
  165. }
  166. if (!commonPath && this.compilers[0].outputPath[0] === "/") return "/";
  167. return commonPath;
  168. }
  169. get inputFileSystem() {
  170. throw new Error("Cannot read inputFileSystem of a MultiCompiler");
  171. }
  172. /**
  173. * @param {InputFileSystem} value the new input file system
  174. */
  175. set inputFileSystem(value) {
  176. for (const compiler of this.compilers) {
  177. compiler.inputFileSystem = value;
  178. }
  179. }
  180. get outputFileSystem() {
  181. throw new Error("Cannot read outputFileSystem of a MultiCompiler");
  182. }
  183. /**
  184. * @param {OutputFileSystem} value the new output file system
  185. */
  186. set outputFileSystem(value) {
  187. for (const compiler of this.compilers) {
  188. compiler.outputFileSystem = value;
  189. }
  190. }
  191. get watchFileSystem() {
  192. throw new Error("Cannot read watchFileSystem of a MultiCompiler");
  193. }
  194. /**
  195. * @param {WatchFileSystem} value the new watch file system
  196. */
  197. set watchFileSystem(value) {
  198. for (const compiler of this.compilers) {
  199. compiler.watchFileSystem = value;
  200. }
  201. }
  202. /**
  203. * @param {IntermediateFileSystem} value the new intermediate file system
  204. */
  205. set intermediateFileSystem(value) {
  206. for (const compiler of this.compilers) {
  207. compiler.intermediateFileSystem = value;
  208. }
  209. }
  210. get intermediateFileSystem() {
  211. throw new Error("Cannot read outputFileSystem of a MultiCompiler");
  212. }
  213. /**
  214. * @param {string | (() => string)} name name of the logger, or function called once to get the logger name
  215. * @returns {Logger} a logger with that name
  216. */
  217. getInfrastructureLogger(name) {
  218. return this.compilers[0].getInfrastructureLogger(name);
  219. }
  220. /**
  221. * @param {Compiler} compiler the child compiler
  222. * @param {string[]} dependencies its dependencies
  223. * @returns {void}
  224. */
  225. setDependencies(compiler, dependencies) {
  226. this.dependencies.set(compiler, dependencies);
  227. }
  228. /**
  229. * @param {Callback<MultiStats>} callback signals when the validation is complete
  230. * @returns {boolean} true if the dependencies are valid
  231. */
  232. validateDependencies(callback) {
  233. /** @type {Set<{ source: Compiler, target: Compiler }>} */
  234. const edges = new Set();
  235. /** @type {string[]} */
  236. const missing = [];
  237. /**
  238. * @param {Compiler} compiler compiler
  239. * @returns {boolean} target was found
  240. */
  241. const targetFound = (compiler) => {
  242. for (const edge of edges) {
  243. if (edge.target === compiler) {
  244. return true;
  245. }
  246. }
  247. return false;
  248. };
  249. /**
  250. * @param {{ source: Compiler, target: Compiler }} e1 edge 1
  251. * @param {{ source: Compiler, target: Compiler }} e2 edge 2
  252. * @returns {number} result
  253. */
  254. const sortEdges = (e1, e2) =>
  255. /** @type {string} */
  256. (e1.source.name).localeCompare(/** @type {string} */ (e2.source.name)) ||
  257. /** @type {string} */
  258. (e1.target.name).localeCompare(/** @type {string} */ (e2.target.name));
  259. for (const source of this.compilers) {
  260. const dependencies = this.dependencies.get(source);
  261. if (dependencies) {
  262. for (const dep of dependencies) {
  263. const target = this.compilers.find((c) => c.name === dep);
  264. if (!target) {
  265. missing.push(dep);
  266. } else {
  267. edges.add({
  268. source,
  269. target
  270. });
  271. }
  272. }
  273. }
  274. }
  275. /** @type {string[]} */
  276. const errors = missing.map(
  277. (m) => `Compiler dependency \`${m}\` not found.`
  278. );
  279. const stack = this.compilers.filter((c) => !targetFound(c));
  280. while (stack.length > 0) {
  281. const current = stack.pop();
  282. for (const edge of edges) {
  283. if (edge.source === current) {
  284. edges.delete(edge);
  285. const target = edge.target;
  286. if (!targetFound(target)) {
  287. stack.push(target);
  288. }
  289. }
  290. }
  291. }
  292. if (edges.size > 0) {
  293. /** @type {string[]} */
  294. const lines = [...edges]
  295. .sort(sortEdges)
  296. .map((edge) => `${edge.source.name} -> ${edge.target.name}`);
  297. lines.unshift("Circular dependency found in compiler dependencies.");
  298. errors.unshift(lines.join("\n"));
  299. }
  300. if (errors.length > 0) {
  301. const message = errors.join("\n");
  302. callback(new Error(message));
  303. return false;
  304. }
  305. return true;
  306. }
  307. // TODO webpack 6 remove
  308. /**
  309. * @deprecated This method should have been private
  310. * @param {Compiler[]} compilers the child compilers
  311. * @param {RunWithDependenciesHandler} fn a handler to run for each compiler
  312. * @param {Callback<Stats[]>} callback the compiler's handler
  313. * @returns {void}
  314. */
  315. runWithDependencies(compilers, fn, callback) {
  316. /** @type {Set<string>} */
  317. const fulfilledNames = new Set();
  318. let remainingCompilers = compilers;
  319. /**
  320. * @param {string} d dependency
  321. * @returns {boolean} when dependency was fulfilled
  322. */
  323. const isDependencyFulfilled = (d) => fulfilledNames.has(d);
  324. /**
  325. * @returns {Compiler[]} compilers
  326. */
  327. const getReadyCompilers = () => {
  328. /** @type {Compiler[]} */
  329. const readyCompilers = [];
  330. const list = remainingCompilers;
  331. remainingCompilers = [];
  332. for (const c of list) {
  333. const dependencies = this.dependencies.get(c);
  334. const ready =
  335. !dependencies || dependencies.every(isDependencyFulfilled);
  336. if (ready) {
  337. readyCompilers.push(c);
  338. } else {
  339. remainingCompilers.push(c);
  340. }
  341. }
  342. return readyCompilers;
  343. };
  344. /**
  345. * @param {Callback<Stats[]>} callback callback
  346. * @returns {void}
  347. */
  348. const runCompilers = (callback) => {
  349. if (remainingCompilers.length === 0) return callback(null);
  350. asyncLib.map(
  351. getReadyCompilers(),
  352. (compiler, callback) => {
  353. fn(compiler, (err) => {
  354. if (err) return callback(err);
  355. fulfilledNames.add(/** @type {string} */ (compiler.name));
  356. runCompilers(callback);
  357. });
  358. },
  359. (err, results) => {
  360. callback(/** @type {Error | null} */ (err), results);
  361. }
  362. );
  363. };
  364. runCompilers(callback);
  365. }
  366. /**
  367. * @template SetupResult
  368. * @param {(compiler: Compiler, index: number, doneCallback: Callback<Stats>, isBlocked: () => boolean, setChanged: () => void, setInvalid: () => void) => SetupResult} setup setup a single compiler
  369. * @param {(compiler: Compiler, setupResult: SetupResult, callback: Callback<Stats>) => void} run run/continue a single compiler
  370. * @param {Callback<MultiStats>} callback callback when all compilers are done, result includes Stats of all changed compilers
  371. * @returns {SetupResult[]} result of setup
  372. */
  373. _runGraph(setup, run, callback) {
  374. /** @typedef {{ compiler: Compiler, setupResult: undefined | SetupResult, result: undefined | Stats, state: "pending" | "blocked" | "queued" | "starting" | "running" | "running-outdated" | "done", children: Node[], parents: Node[] }} Node */
  375. // State transitions for nodes:
  376. // -> blocked (initial)
  377. // blocked -> starting [running++] (when all parents done)
  378. // queued -> starting [running++] (when processing the queue)
  379. // starting -> running (when run has been called)
  380. // running -> done [running--] (when compilation is done)
  381. // done -> pending (when invalidated from file change)
  382. // pending -> blocked [add to queue] (when invalidated from aggregated changes)
  383. // done -> blocked [add to queue] (when invalidated, from parent invalidation)
  384. // running -> running-outdated (when invalidated, either from change or parent invalidation)
  385. // running-outdated -> blocked [running--] (when compilation is done)
  386. /** @type {Node[]} */
  387. const nodes = this.compilers.map((compiler) => ({
  388. compiler,
  389. setupResult: undefined,
  390. result: undefined,
  391. state: "blocked",
  392. children: [],
  393. parents: []
  394. }));
  395. /** @type {Map<string, Node>} */
  396. const compilerToNode = new Map();
  397. for (const node of nodes) {
  398. compilerToNode.set(/** @type {string} */ (node.compiler.name), node);
  399. }
  400. for (const node of nodes) {
  401. const dependencies = this.dependencies.get(node.compiler);
  402. if (!dependencies) continue;
  403. for (const dep of dependencies) {
  404. const parent = /** @type {Node} */ (compilerToNode.get(dep));
  405. node.parents.push(parent);
  406. parent.children.push(node);
  407. }
  408. }
  409. /** @type {ArrayQueue<Node>} */
  410. const queue = new ArrayQueue();
  411. for (const node of nodes) {
  412. if (node.parents.length === 0) {
  413. node.state = "queued";
  414. queue.enqueue(node);
  415. }
  416. }
  417. let errored = false;
  418. let running = 0;
  419. const parallelism = /** @type {number} */ (this._options.parallelism);
  420. /**
  421. * @param {Node} node node
  422. * @param {(Error | null)=} err error
  423. * @param {Stats=} stats result
  424. * @returns {void}
  425. */
  426. const nodeDone = (node, err, stats) => {
  427. if (errored) return;
  428. if (err) {
  429. errored = true;
  430. return asyncLib.each(
  431. nodes,
  432. (node, callback) => {
  433. if (node.compiler.watching) {
  434. node.compiler.watching.close(callback);
  435. } else {
  436. callback();
  437. }
  438. },
  439. () => callback(err)
  440. );
  441. }
  442. node.result = stats;
  443. running--;
  444. if (node.state === "running") {
  445. node.state = "done";
  446. for (const child of node.children) {
  447. if (child.state === "blocked") queue.enqueue(child);
  448. }
  449. } else if (node.state === "running-outdated") {
  450. node.state = "blocked";
  451. queue.enqueue(node);
  452. }
  453. processQueue();
  454. };
  455. /**
  456. * @param {Node} node node
  457. * @returns {void}
  458. */
  459. const nodeInvalidFromParent = (node) => {
  460. if (node.state === "done") {
  461. node.state = "blocked";
  462. } else if (node.state === "running") {
  463. node.state = "running-outdated";
  464. }
  465. for (const child of node.children) {
  466. nodeInvalidFromParent(child);
  467. }
  468. };
  469. /**
  470. * @param {Node} node node
  471. * @returns {void}
  472. */
  473. const nodeInvalid = (node) => {
  474. if (node.state === "done") {
  475. node.state = "pending";
  476. } else if (node.state === "running") {
  477. node.state = "running-outdated";
  478. }
  479. for (const child of node.children) {
  480. nodeInvalidFromParent(child);
  481. }
  482. };
  483. /**
  484. * @param {Node} node node
  485. * @returns {void}
  486. */
  487. const nodeChange = (node) => {
  488. nodeInvalid(node);
  489. if (node.state === "pending") {
  490. node.state = "blocked";
  491. }
  492. if (node.state === "blocked") {
  493. queue.enqueue(node);
  494. processQueue();
  495. }
  496. };
  497. /** @type {SetupResult[]} */
  498. const setupResults = [];
  499. for (const [i, node] of nodes.entries()) {
  500. setupResults.push(
  501. (node.setupResult = setup(
  502. node.compiler,
  503. i,
  504. nodeDone.bind(null, node),
  505. () => node.state !== "starting" && node.state !== "running",
  506. () => nodeChange(node),
  507. () => nodeInvalid(node)
  508. ))
  509. );
  510. }
  511. let processing = true;
  512. const processQueue = () => {
  513. if (processing) return;
  514. processing = true;
  515. process.nextTick(processQueueWorker);
  516. };
  517. const processQueueWorker = () => {
  518. // eslint-disable-next-line no-unmodified-loop-condition
  519. while (running < parallelism && queue.length > 0 && !errored) {
  520. const node = /** @type {Node} */ (queue.dequeue());
  521. if (
  522. node.state === "queued" ||
  523. (node.state === "blocked" &&
  524. node.parents.every((p) => p.state === "done"))
  525. ) {
  526. running++;
  527. node.state = "starting";
  528. run(
  529. node.compiler,
  530. /** @type {SetupResult} */ (node.setupResult),
  531. nodeDone.bind(null, node)
  532. );
  533. node.state = "running";
  534. }
  535. }
  536. processing = false;
  537. if (
  538. !errored &&
  539. running === 0 &&
  540. nodes.every((node) => node.state === "done")
  541. ) {
  542. /** @type {Stats[]} */
  543. const stats = [];
  544. for (const node of nodes) {
  545. const result = node.result;
  546. if (result) {
  547. node.result = undefined;
  548. stats.push(result);
  549. }
  550. }
  551. if (stats.length > 0) {
  552. callback(null, new MultiStats(stats));
  553. }
  554. }
  555. };
  556. processQueueWorker();
  557. return setupResults;
  558. }
  559. /**
  560. * @param {WatchOptions | WatchOptions[]} watchOptions the watcher's options
  561. * @param {Callback<MultiStats>} handler signals when the call finishes
  562. * @returns {MultiWatching | undefined} a compiler watcher
  563. */
  564. watch(watchOptions, handler) {
  565. if (this.running) {
  566. handler(new ConcurrentCompilationError());
  567. return;
  568. }
  569. this.running = true;
  570. if (this.validateDependencies(handler)) {
  571. const watchings = this._runGraph(
  572. (compiler, idx, callback, isBlocked, setChanged, setInvalid) => {
  573. const watching = compiler.watch(
  574. Array.isArray(watchOptions) ? watchOptions[idx] : watchOptions,
  575. callback
  576. );
  577. if (watching) {
  578. watching._onInvalid = setInvalid;
  579. watching._onChange = setChanged;
  580. watching._isBlocked = isBlocked;
  581. }
  582. return watching;
  583. },
  584. (compiler, watching, _callback) => {
  585. if (compiler.watching !== watching) return;
  586. if (!watching.running) watching.invalidate();
  587. },
  588. handler
  589. );
  590. return new MultiWatching(watchings, this);
  591. }
  592. return new MultiWatching([], this);
  593. }
  594. /**
  595. * @param {Callback<MultiStats>} callback signals when the call finishes
  596. * @returns {void}
  597. */
  598. run(callback) {
  599. if (this.running) {
  600. callback(new ConcurrentCompilationError());
  601. return;
  602. }
  603. this.running = true;
  604. if (this.validateDependencies(callback)) {
  605. this._runGraph(
  606. () => {},
  607. (compiler, setupResult, callback) => compiler.run(callback),
  608. (err, stats) => {
  609. this.running = false;
  610. if (callback !== undefined) {
  611. return callback(err, stats);
  612. }
  613. }
  614. );
  615. }
  616. }
  617. purgeInputFileSystem() {
  618. for (const compiler of this.compilers) {
  619. if (compiler.inputFileSystem && compiler.inputFileSystem.purge) {
  620. compiler.inputFileSystem.purge();
  621. }
  622. }
  623. }
  624. /**
  625. * @param {ErrorCallback} callback signals when the compiler closes
  626. * @returns {void}
  627. */
  628. close(callback) {
  629. asyncLib.each(
  630. this.compilers,
  631. (compiler, callback) => {
  632. compiler.close(callback);
  633. },
  634. (error) => {
  635. callback(/** @type {Error | null} */ (error));
  636. }
  637. );
  638. }
  639. };