MultiCompiler.js 16 KB

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