IdleFileCachePlugin.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const Cache = require("../Cache");
  7. const ProgressPlugin = require("../ProgressPlugin");
  8. /** @typedef {import("../Compiler")} Compiler */
  9. /** @typedef {import("./PackFileCacheStrategy")} PackFileCacheStrategy */
  10. const BUILD_DEPENDENCIES_KEY = Symbol();
  11. class IdleFileCachePlugin {
  12. /**
  13. * @param {PackFileCacheStrategy} strategy cache strategy
  14. * @param {number} idleTimeout timeout
  15. * @param {number} idleTimeoutForInitialStore initial timeout
  16. * @param {number} idleTimeoutAfterLargeChanges timeout after changes
  17. */
  18. constructor(
  19. strategy,
  20. idleTimeout,
  21. idleTimeoutForInitialStore,
  22. idleTimeoutAfterLargeChanges
  23. ) {
  24. this.strategy = strategy;
  25. this.idleTimeout = idleTimeout;
  26. this.idleTimeoutForInitialStore = idleTimeoutForInitialStore;
  27. this.idleTimeoutAfterLargeChanges = idleTimeoutAfterLargeChanges;
  28. }
  29. /**
  30. * Apply the plugin
  31. * @param {Compiler} compiler the compiler instance
  32. * @returns {void}
  33. */
  34. apply(compiler) {
  35. let strategy = this.strategy;
  36. const idleTimeout = this.idleTimeout;
  37. const idleTimeoutForInitialStore = Math.min(
  38. idleTimeout,
  39. this.idleTimeoutForInitialStore
  40. );
  41. const idleTimeoutAfterLargeChanges = this.idleTimeoutAfterLargeChanges;
  42. const resolvedPromise = Promise.resolve();
  43. let timeSpendInBuild = 0;
  44. let timeSpendInStore = 0;
  45. let avgTimeSpendInStore = 0;
  46. /** @type {Map<string | typeof BUILD_DEPENDENCIES_KEY, () => Promise<void>>} */
  47. const pendingIdleTasks = new Map();
  48. compiler.cache.hooks.store.tap(
  49. { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK },
  50. (identifier, etag, data) => {
  51. pendingIdleTasks.set(identifier, () =>
  52. strategy.store(identifier, etag, data)
  53. );
  54. }
  55. );
  56. compiler.cache.hooks.get.tapPromise(
  57. { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK },
  58. (identifier, etag, gotHandlers) => {
  59. const restore = () =>
  60. strategy.restore(identifier, etag).then(cacheEntry => {
  61. if (cacheEntry === undefined) {
  62. gotHandlers.push((result, callback) => {
  63. if (result !== undefined) {
  64. pendingIdleTasks.set(identifier, () =>
  65. strategy.store(identifier, etag, result)
  66. );
  67. }
  68. callback();
  69. });
  70. } else {
  71. return cacheEntry;
  72. }
  73. });
  74. const pendingTask = pendingIdleTasks.get(identifier);
  75. if (pendingTask !== undefined) {
  76. pendingIdleTasks.delete(identifier);
  77. return pendingTask().then(restore);
  78. }
  79. return restore();
  80. }
  81. );
  82. compiler.cache.hooks.storeBuildDependencies.tap(
  83. { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK },
  84. dependencies => {
  85. pendingIdleTasks.set(BUILD_DEPENDENCIES_KEY, () =>
  86. Promise.resolve().then(() =>
  87. strategy.storeBuildDependencies(dependencies)
  88. )
  89. );
  90. }
  91. );
  92. compiler.cache.hooks.shutdown.tapPromise(
  93. { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK },
  94. () => {
  95. if (idleTimer) {
  96. clearTimeout(idleTimer);
  97. idleTimer = undefined;
  98. }
  99. isIdle = false;
  100. const reportProgress = ProgressPlugin.getReporter(compiler);
  101. const jobs = Array.from(pendingIdleTasks.values());
  102. if (reportProgress) reportProgress(0, "process pending cache items");
  103. const promises = jobs.map(fn => fn());
  104. pendingIdleTasks.clear();
  105. promises.push(currentIdlePromise);
  106. const promise = Promise.all(promises);
  107. currentIdlePromise = promise.then(() => strategy.afterAllStored());
  108. if (reportProgress) {
  109. currentIdlePromise = currentIdlePromise.then(() => {
  110. reportProgress(1, `stored`);
  111. });
  112. }
  113. return currentIdlePromise.then(() => {
  114. // Reset strategy
  115. if (strategy.clear) strategy.clear();
  116. });
  117. }
  118. );
  119. /** @type {Promise<any>} */
  120. let currentIdlePromise = resolvedPromise;
  121. let isIdle = false;
  122. let isInitialStore = true;
  123. const processIdleTasks = () => {
  124. if (isIdle) {
  125. const startTime = Date.now();
  126. if (pendingIdleTasks.size > 0) {
  127. const promises = [currentIdlePromise];
  128. const maxTime = startTime + 100;
  129. let maxCount = 100;
  130. for (const [filename, factory] of pendingIdleTasks) {
  131. pendingIdleTasks.delete(filename);
  132. promises.push(factory());
  133. if (maxCount-- <= 0 || Date.now() > maxTime) break;
  134. }
  135. currentIdlePromise = Promise.all(promises);
  136. currentIdlePromise.then(() => {
  137. timeSpendInStore += Date.now() - startTime;
  138. // Allow to exit the process between
  139. idleTimer = setTimeout(processIdleTasks, 0);
  140. idleTimer.unref();
  141. });
  142. return;
  143. }
  144. currentIdlePromise = currentIdlePromise
  145. .then(async () => {
  146. await strategy.afterAllStored();
  147. timeSpendInStore += Date.now() - startTime;
  148. avgTimeSpendInStore =
  149. Math.max(avgTimeSpendInStore, timeSpendInStore) * 0.9 +
  150. timeSpendInStore * 0.1;
  151. timeSpendInStore = 0;
  152. timeSpendInBuild = 0;
  153. })
  154. .catch(err => {
  155. const logger = compiler.getInfrastructureLogger(
  156. "IdleFileCachePlugin"
  157. );
  158. logger.warn(`Background tasks during idle failed: ${err.message}`);
  159. logger.debug(err.stack);
  160. });
  161. isInitialStore = false;
  162. }
  163. };
  164. /** @type {ReturnType<typeof setTimeout> | undefined} */
  165. let idleTimer = undefined;
  166. compiler.cache.hooks.beginIdle.tap(
  167. { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK },
  168. () => {
  169. const isLargeChange = timeSpendInBuild > avgTimeSpendInStore * 2;
  170. if (isInitialStore && idleTimeoutForInitialStore < idleTimeout) {
  171. compiler
  172. .getInfrastructureLogger("IdleFileCachePlugin")
  173. .log(
  174. `Initial cache was generated and cache will be persisted in ${
  175. idleTimeoutForInitialStore / 1000
  176. }s.`
  177. );
  178. } else if (
  179. isLargeChange &&
  180. idleTimeoutAfterLargeChanges < idleTimeout
  181. ) {
  182. compiler
  183. .getInfrastructureLogger("IdleFileCachePlugin")
  184. .log(
  185. `Spend ${Math.round(timeSpendInBuild) / 1000}s in build and ${
  186. Math.round(avgTimeSpendInStore) / 1000
  187. }s in average in cache store. This is considered as large change and cache will be persisted in ${
  188. idleTimeoutAfterLargeChanges / 1000
  189. }s.`
  190. );
  191. }
  192. idleTimer = setTimeout(
  193. () => {
  194. idleTimer = undefined;
  195. isIdle = true;
  196. resolvedPromise.then(processIdleTasks);
  197. },
  198. Math.min(
  199. isInitialStore ? idleTimeoutForInitialStore : Infinity,
  200. isLargeChange ? idleTimeoutAfterLargeChanges : Infinity,
  201. idleTimeout
  202. )
  203. );
  204. idleTimer.unref();
  205. }
  206. );
  207. compiler.cache.hooks.endIdle.tap(
  208. { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK },
  209. () => {
  210. if (idleTimer) {
  211. clearTimeout(idleTimer);
  212. idleTimer = undefined;
  213. }
  214. isIdle = false;
  215. }
  216. );
  217. compiler.hooks.done.tap("IdleFileCachePlugin", stats => {
  218. // 10% build overhead is ignored, as it's not cacheable
  219. timeSpendInBuild *= 0.9;
  220. timeSpendInBuild +=
  221. /** @type {number} */ (stats.endTime) -
  222. /** @type {number} */ (stats.startTime);
  223. });
  224. }
  225. }
  226. module.exports = IdleFileCachePlugin;