MultiCompiler.js 16 KB

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