ResolverCachePlugin.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const LazySet = require("../util/LazySet");
  7. const makeSerializable = require("../util/makeSerializable");
  8. /** @typedef {import("enhanced-resolve").Resolver} Resolver */
  9. /** @typedef {import("../CacheFacade").ItemCacheFacade} ItemCacheFacade */
  10. /** @typedef {import("../Compiler")} Compiler */
  11. /** @typedef {import("../FileSystemInfo")} FileSystemInfo */
  12. /** @typedef {import("../FileSystemInfo").Snapshot} Snapshot */
  13. class CacheEntry {
  14. constructor(result, snapshot) {
  15. this.result = result;
  16. this.snapshot = snapshot;
  17. }
  18. serialize({ write }) {
  19. write(this.result);
  20. write(this.snapshot);
  21. }
  22. deserialize({ read }) {
  23. this.result = read();
  24. this.snapshot = read();
  25. }
  26. }
  27. makeSerializable(CacheEntry, "webpack/lib/cache/ResolverCachePlugin");
  28. /**
  29. * @template T
  30. * @param {Set<T> | LazySet<T>} set set to add items to
  31. * @param {Set<T> | LazySet<T>} otherSet set to add items from
  32. * @returns {void}
  33. */
  34. const addAllToSet = (set, otherSet) => {
  35. if (set instanceof LazySet) {
  36. set.addAll(otherSet);
  37. } else {
  38. for (const item of otherSet) {
  39. set.add(item);
  40. }
  41. }
  42. };
  43. /**
  44. * @param {object} object an object
  45. * @param {boolean} excludeContext if true, context is not included in string
  46. * @returns {string} stringified version
  47. */
  48. const objectToString = (object, excludeContext) => {
  49. let str = "";
  50. for (const key in object) {
  51. if (excludeContext && key === "context") continue;
  52. const value = object[key];
  53. if (typeof value === "object" && value !== null) {
  54. str += `|${key}=[${objectToString(value, false)}|]`;
  55. } else {
  56. str += `|${key}=|${value}`;
  57. }
  58. }
  59. return str;
  60. };
  61. class ResolverCachePlugin {
  62. /**
  63. * Apply the plugin
  64. * @param {Compiler} compiler the compiler instance
  65. * @returns {void}
  66. */
  67. apply(compiler) {
  68. const cache = compiler.getCache("ResolverCachePlugin");
  69. /** @type {FileSystemInfo} */
  70. let fileSystemInfo;
  71. let snapshotOptions;
  72. let realResolves = 0;
  73. let cachedResolves = 0;
  74. let cacheInvalidResolves = 0;
  75. let concurrentResolves = 0;
  76. compiler.hooks.thisCompilation.tap("ResolverCachePlugin", compilation => {
  77. snapshotOptions = compilation.options.snapshot.resolve;
  78. fileSystemInfo = compilation.fileSystemInfo;
  79. compilation.hooks.finishModules.tap("ResolverCachePlugin", () => {
  80. if (realResolves + cachedResolves > 0) {
  81. const logger = compilation.getLogger("webpack.ResolverCachePlugin");
  82. logger.log(
  83. `${Math.round(
  84. (100 * realResolves) / (realResolves + cachedResolves)
  85. )}% really resolved (${realResolves} real resolves with ${cacheInvalidResolves} cached but invalid, ${cachedResolves} cached valid, ${concurrentResolves} concurrent)`
  86. );
  87. realResolves = 0;
  88. cachedResolves = 0;
  89. cacheInvalidResolves = 0;
  90. concurrentResolves = 0;
  91. }
  92. });
  93. });
  94. /**
  95. * @param {ItemCacheFacade} itemCache cache
  96. * @param {Resolver} resolver the resolver
  97. * @param {object} resolveContext context for resolving meta info
  98. * @param {object} request the request info object
  99. * @param {function((Error | null)=, object=): void} callback callback function
  100. * @returns {void}
  101. */
  102. const doRealResolve = (
  103. itemCache,
  104. resolver,
  105. resolveContext,
  106. request,
  107. callback
  108. ) => {
  109. realResolves++;
  110. const newRequest = {
  111. _ResolverCachePluginCacheMiss: true,
  112. ...request
  113. };
  114. const newResolveContext = {
  115. ...resolveContext,
  116. stack: new Set(),
  117. /** @type {LazySet<string>} */
  118. missingDependencies: new LazySet(),
  119. /** @type {LazySet<string>} */
  120. fileDependencies: new LazySet(),
  121. /** @type {LazySet<string>} */
  122. contextDependencies: new LazySet()
  123. };
  124. let yieldResult;
  125. let withYield = false;
  126. if (typeof newResolveContext.yield === "function") {
  127. yieldResult = [];
  128. withYield = true;
  129. newResolveContext.yield = obj => yieldResult.push(obj);
  130. }
  131. const propagate = key => {
  132. if (resolveContext[key]) {
  133. addAllToSet(resolveContext[key], newResolveContext[key]);
  134. }
  135. };
  136. const resolveTime = Date.now();
  137. resolver.doResolve(
  138. resolver.hooks.resolve,
  139. newRequest,
  140. "Cache miss",
  141. newResolveContext,
  142. (err, result) => {
  143. propagate("fileDependencies");
  144. propagate("contextDependencies");
  145. propagate("missingDependencies");
  146. if (err) return callback(err);
  147. const fileDependencies = newResolveContext.fileDependencies;
  148. const contextDependencies = newResolveContext.contextDependencies;
  149. const missingDependencies = newResolveContext.missingDependencies;
  150. fileSystemInfo.createSnapshot(
  151. resolveTime,
  152. fileDependencies,
  153. contextDependencies,
  154. missingDependencies,
  155. snapshotOptions,
  156. (err, snapshot) => {
  157. if (err) return callback(err);
  158. const resolveResult = withYield ? yieldResult : result;
  159. // since we intercept resolve hook
  160. // we still can get result in callback
  161. if (withYield && result) yieldResult.push(result);
  162. if (!snapshot) {
  163. if (resolveResult) return callback(null, resolveResult);
  164. return callback();
  165. }
  166. itemCache.store(
  167. new CacheEntry(resolveResult, snapshot),
  168. storeErr => {
  169. if (storeErr) return callback(storeErr);
  170. if (resolveResult) return callback(null, resolveResult);
  171. callback();
  172. }
  173. );
  174. }
  175. );
  176. }
  177. );
  178. };
  179. compiler.resolverFactory.hooks.resolver.intercept({
  180. factory(type, hook) {
  181. /** @type {Map<string, (function(Error=, object=): void)[]>} */
  182. const activeRequests = new Map();
  183. /** @type {Map<string, [function(Error=, object=): void, function(Error=, object=): void][]>} */
  184. const activeRequestsWithYield = new Map();
  185. hook.tap(
  186. "ResolverCachePlugin",
  187. /**
  188. * @param {Resolver} resolver the resolver
  189. * @param {object} options resolve options
  190. * @param {object} userOptions resolve options passed by the user
  191. * @returns {void}
  192. */
  193. (resolver, options, userOptions) => {
  194. if (options.cache !== true) return;
  195. const optionsIdent = objectToString(userOptions, false);
  196. const cacheWithContext =
  197. options.cacheWithContext !== undefined
  198. ? options.cacheWithContext
  199. : false;
  200. resolver.hooks.resolve.tapAsync(
  201. {
  202. name: "ResolverCachePlugin",
  203. stage: -100
  204. },
  205. (request, resolveContext, callback) => {
  206. if (
  207. /** @type {TODO} */ (request)._ResolverCachePluginCacheMiss ||
  208. !fileSystemInfo
  209. ) {
  210. return callback();
  211. }
  212. const withYield = typeof resolveContext.yield === "function";
  213. const identifier = `${type}${
  214. withYield ? "|yield" : "|default"
  215. }${optionsIdent}${objectToString(request, !cacheWithContext)}`;
  216. if (withYield) {
  217. const activeRequest = activeRequestsWithYield.get(identifier);
  218. if (activeRequest) {
  219. activeRequest[0].push(callback);
  220. activeRequest[1].push(
  221. /** @type {TODO} */ (resolveContext.yield)
  222. );
  223. return;
  224. }
  225. } else {
  226. const activeRequest = activeRequests.get(identifier);
  227. if (activeRequest) {
  228. activeRequest.push(callback);
  229. return;
  230. }
  231. }
  232. const itemCache = cache.getItemCache(identifier, null);
  233. let callbacks, yields;
  234. const done = withYield
  235. ? (err, result) => {
  236. if (callbacks === undefined) {
  237. if (err) {
  238. callback(err);
  239. } else {
  240. if (result)
  241. for (const r of result) resolveContext.yield(r);
  242. callback(null, null);
  243. }
  244. yields = undefined;
  245. callbacks = false;
  246. } else {
  247. if (err) {
  248. for (const cb of callbacks) cb(err);
  249. } else {
  250. for (let i = 0; i < callbacks.length; i++) {
  251. const cb = callbacks[i];
  252. const yield_ = yields[i];
  253. if (result) for (const r of result) yield_(r);
  254. cb(null, null);
  255. }
  256. }
  257. activeRequestsWithYield.delete(identifier);
  258. yields = undefined;
  259. callbacks = false;
  260. }
  261. }
  262. : (err, result) => {
  263. if (callbacks === undefined) {
  264. callback(err, result);
  265. callbacks = false;
  266. } else {
  267. for (const callback of callbacks) {
  268. callback(err, result);
  269. }
  270. activeRequests.delete(identifier);
  271. callbacks = false;
  272. }
  273. };
  274. /**
  275. * @param {Error=} err error if any
  276. * @param {CacheEntry=} cacheEntry cache entry
  277. * @returns {void}
  278. */
  279. const processCacheResult = (err, cacheEntry) => {
  280. if (err) return done(err);
  281. if (cacheEntry) {
  282. const { snapshot, result } = cacheEntry;
  283. fileSystemInfo.checkSnapshotValid(
  284. snapshot,
  285. (err, valid) => {
  286. if (err || !valid) {
  287. cacheInvalidResolves++;
  288. return doRealResolve(
  289. itemCache,
  290. resolver,
  291. resolveContext,
  292. request,
  293. done
  294. );
  295. }
  296. cachedResolves++;
  297. if (resolveContext.missingDependencies) {
  298. addAllToSet(
  299. /** @type {LazySet<string>} */
  300. (resolveContext.missingDependencies),
  301. snapshot.getMissingIterable()
  302. );
  303. }
  304. if (resolveContext.fileDependencies) {
  305. addAllToSet(
  306. /** @type {LazySet<string>} */
  307. (resolveContext.fileDependencies),
  308. snapshot.getFileIterable()
  309. );
  310. }
  311. if (resolveContext.contextDependencies) {
  312. addAllToSet(
  313. /** @type {LazySet<string>} */
  314. (resolveContext.contextDependencies),
  315. snapshot.getContextIterable()
  316. );
  317. }
  318. done(null, result);
  319. }
  320. );
  321. } else {
  322. doRealResolve(
  323. itemCache,
  324. resolver,
  325. resolveContext,
  326. request,
  327. done
  328. );
  329. }
  330. };
  331. itemCache.get(processCacheResult);
  332. if (withYield && callbacks === undefined) {
  333. callbacks = [callback];
  334. yields = [resolveContext.yield];
  335. activeRequestsWithYield.set(
  336. identifier,
  337. /** @type {[any, any]} */ ([callbacks, yields])
  338. );
  339. } else if (callbacks === undefined) {
  340. callbacks = [callback];
  341. activeRequests.set(identifier, callbacks);
  342. }
  343. }
  344. );
  345. }
  346. );
  347. return hook;
  348. }
  349. });
  350. }
  351. }
  352. module.exports = ResolverCachePlugin;