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