ResolverCachePlugin.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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/lib/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. missingDependencies: new LazySet(),
  118. fileDependencies: new LazySet(),
  119. contextDependencies: new LazySet()
  120. };
  121. let yieldResult;
  122. let withYield = false;
  123. if (typeof newResolveContext.yield === "function") {
  124. yieldResult = [];
  125. withYield = true;
  126. newResolveContext.yield = obj => yieldResult.push(obj);
  127. }
  128. const propagate = key => {
  129. if (resolveContext[key]) {
  130. addAllToSet(resolveContext[key], newResolveContext[key]);
  131. }
  132. };
  133. const resolveTime = Date.now();
  134. resolver.doResolve(
  135. resolver.hooks.resolve,
  136. newRequest,
  137. "Cache miss",
  138. newResolveContext,
  139. (err, result) => {
  140. propagate("fileDependencies");
  141. propagate("contextDependencies");
  142. propagate("missingDependencies");
  143. if (err) return callback(err);
  144. const fileDependencies = newResolveContext.fileDependencies;
  145. const contextDependencies = newResolveContext.contextDependencies;
  146. const missingDependencies = newResolveContext.missingDependencies;
  147. fileSystemInfo.createSnapshot(
  148. resolveTime,
  149. fileDependencies,
  150. contextDependencies,
  151. missingDependencies,
  152. snapshotOptions,
  153. (err, snapshot) => {
  154. if (err) return callback(err);
  155. const resolveResult = withYield ? yieldResult : result;
  156. // since we intercept resolve hook
  157. // we still can get result in callback
  158. if (withYield && result) yieldResult.push(result);
  159. if (!snapshot) {
  160. if (resolveResult) return callback(null, resolveResult);
  161. return callback();
  162. }
  163. itemCache.store(
  164. new CacheEntry(resolveResult, snapshot),
  165. storeErr => {
  166. if (storeErr) return callback(storeErr);
  167. if (resolveResult) return callback(null, resolveResult);
  168. callback();
  169. }
  170. );
  171. }
  172. );
  173. }
  174. );
  175. };
  176. compiler.resolverFactory.hooks.resolver.intercept({
  177. factory(type, hook) {
  178. /** @type {Map<string, (function(Error=, Object=): void)[]>} */
  179. const activeRequests = new Map();
  180. /** @type {Map<string, [function(Error=, Object=): void, function(Error=, Object=): void][]>} */
  181. const activeRequestsWithYield = new Map();
  182. hook.tap(
  183. "ResolverCachePlugin",
  184. /**
  185. * @param {Resolver} resolver the resolver
  186. * @param {Object} options resolve options
  187. * @param {Object} userOptions resolve options passed by the user
  188. * @returns {void}
  189. */
  190. (resolver, options, userOptions) => {
  191. if (options.cache !== true) return;
  192. const optionsIdent = objectToString(userOptions, false);
  193. const cacheWithContext =
  194. options.cacheWithContext !== undefined
  195. ? options.cacheWithContext
  196. : false;
  197. resolver.hooks.resolve.tapAsync(
  198. {
  199. name: "ResolverCachePlugin",
  200. stage: -100
  201. },
  202. (request, resolveContext, callback) => {
  203. if (request._ResolverCachePluginCacheMiss || !fileSystemInfo) {
  204. return callback();
  205. }
  206. const withYield = typeof resolveContext.yield === "function";
  207. const identifier = `${type}${
  208. withYield ? "|yield" : "|default"
  209. }${optionsIdent}${objectToString(request, !cacheWithContext)}`;
  210. if (withYield) {
  211. const activeRequest = activeRequestsWithYield.get(identifier);
  212. if (activeRequest) {
  213. activeRequest[0].push(callback);
  214. activeRequest[1].push(resolveContext.yield);
  215. return;
  216. }
  217. } else {
  218. const activeRequest = activeRequests.get(identifier);
  219. if (activeRequest) {
  220. activeRequest.push(callback);
  221. return;
  222. }
  223. }
  224. const itemCache = cache.getItemCache(identifier, null);
  225. let callbacks, yields;
  226. const done = withYield
  227. ? (err, result) => {
  228. if (callbacks === undefined) {
  229. if (err) {
  230. callback(err);
  231. } else {
  232. if (result)
  233. for (const r of result) resolveContext.yield(r);
  234. callback(null, null);
  235. }
  236. yields = undefined;
  237. callbacks = false;
  238. } else {
  239. if (err) {
  240. for (const cb of callbacks) cb(err);
  241. } else {
  242. for (let i = 0; i < callbacks.length; i++) {
  243. const cb = callbacks[i];
  244. const yield_ = yields[i];
  245. if (result) for (const r of result) yield_(r);
  246. cb(null, null);
  247. }
  248. }
  249. activeRequestsWithYield.delete(identifier);
  250. yields = undefined;
  251. callbacks = false;
  252. }
  253. }
  254. : (err, result) => {
  255. if (callbacks === undefined) {
  256. callback(err, result);
  257. callbacks = false;
  258. } else {
  259. for (const callback of callbacks) {
  260. callback(err, result);
  261. }
  262. activeRequests.delete(identifier);
  263. callbacks = false;
  264. }
  265. };
  266. /**
  267. * @param {Error=} err error if any
  268. * @param {CacheEntry=} cacheEntry cache entry
  269. * @returns {void}
  270. */
  271. const processCacheResult = (err, cacheEntry) => {
  272. if (err) return done(err);
  273. if (cacheEntry) {
  274. const { snapshot, result } = cacheEntry;
  275. fileSystemInfo.checkSnapshotValid(
  276. snapshot,
  277. (err, valid) => {
  278. if (err || !valid) {
  279. cacheInvalidResolves++;
  280. return doRealResolve(
  281. itemCache,
  282. resolver,
  283. resolveContext,
  284. request,
  285. done
  286. );
  287. }
  288. cachedResolves++;
  289. if (resolveContext.missingDependencies) {
  290. addAllToSet(
  291. resolveContext.missingDependencies,
  292. snapshot.getMissingIterable()
  293. );
  294. }
  295. if (resolveContext.fileDependencies) {
  296. addAllToSet(
  297. resolveContext.fileDependencies,
  298. snapshot.getFileIterable()
  299. );
  300. }
  301. if (resolveContext.contextDependencies) {
  302. addAllToSet(
  303. resolveContext.contextDependencies,
  304. snapshot.getContextIterable()
  305. );
  306. }
  307. done(null, result);
  308. }
  309. );
  310. } else {
  311. doRealResolve(
  312. itemCache,
  313. resolver,
  314. resolveContext,
  315. request,
  316. done
  317. );
  318. }
  319. };
  320. itemCache.get(processCacheResult);
  321. if (withYield && callbacks === undefined) {
  322. callbacks = [callback];
  323. yields = [resolveContext.yield];
  324. activeRequestsWithYield.set(
  325. identifier,
  326. /** @type {[any, any]} */ ([callbacks, yields])
  327. );
  328. } else if (callbacks === undefined) {
  329. callbacks = [callback];
  330. activeRequests.set(identifier, callbacks);
  331. }
  332. }
  333. );
  334. }
  335. );
  336. return hook;
  337. }
  338. });
  339. }
  340. }
  341. module.exports = ResolverCachePlugin;