PackFileCacheStrategy.js 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const FileSystemInfo = require("../FileSystemInfo");
  7. const ProgressPlugin = require("../ProgressPlugin");
  8. const { formatSize } = require("../SizeFormatHelpers");
  9. const SerializerMiddleware = require("../serialization/SerializerMiddleware");
  10. const LazySet = require("../util/LazySet");
  11. const makeSerializable = require("../util/makeSerializable");
  12. const memoize = require("../util/memoize");
  13. const {
  14. createFileSerializer,
  15. NOT_SERIALIZABLE
  16. } = require("../util/serialization");
  17. /** @typedef {import("../../declarations/WebpackOptions").SnapshotOptions} SnapshotOptions */
  18. /** @typedef {import("../Cache").Etag} Etag */
  19. /** @typedef {import("../Compiler")} Compiler */
  20. /** @typedef {import("../FileSystemInfo").ResolveBuildDependenciesResult} ResolveBuildDependenciesResult */
  21. /** @typedef {import("../FileSystemInfo").ResolveResults} ResolveResults */
  22. /** @typedef {import("../FileSystemInfo").Snapshot} Snapshot */
  23. /** @typedef {import("../logging/Logger").Logger} Logger */
  24. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  25. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  26. /** @typedef {typeof import("../util/Hash")} Hash */
  27. /** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */
  28. /** @typedef {Set<string>} Items */
  29. /** @typedef {Set<string>} BuildDependencies */
  30. /** @typedef {Map<string, PackItemInfo>} ItemInfo */
  31. class PackContainer {
  32. /**
  33. * @param {Pack} data stored data
  34. * @param {string} version version identifier
  35. * @param {Snapshot} buildSnapshot snapshot of all build dependencies
  36. * @param {BuildDependencies} buildDependencies list of all unresolved build dependencies captured
  37. * @param {ResolveResults} resolveResults result of the resolved build dependencies
  38. * @param {Snapshot} resolveBuildDependenciesSnapshot snapshot of the dependencies of the build dependencies resolving
  39. */
  40. constructor(
  41. data,
  42. version,
  43. buildSnapshot,
  44. buildDependencies,
  45. resolveResults,
  46. resolveBuildDependenciesSnapshot
  47. ) {
  48. this.data = data;
  49. this.version = version;
  50. this.buildSnapshot = buildSnapshot;
  51. this.buildDependencies = buildDependencies;
  52. this.resolveResults = resolveResults;
  53. this.resolveBuildDependenciesSnapshot = resolveBuildDependenciesSnapshot;
  54. }
  55. /**
  56. * @param {ObjectSerializerContext} context context
  57. */
  58. serialize({ write, writeLazy }) {
  59. write(this.version);
  60. write(this.buildSnapshot);
  61. write(this.buildDependencies);
  62. write(this.resolveResults);
  63. write(this.resolveBuildDependenciesSnapshot);
  64. /** @type {NonNullable<ObjectSerializerContext["writeLazy"]>} */
  65. (writeLazy)(this.data);
  66. }
  67. /**
  68. * @param {ObjectDeserializerContext} context context
  69. */
  70. deserialize({ read }) {
  71. this.version = read();
  72. this.buildSnapshot = read();
  73. this.buildDependencies = read();
  74. this.resolveResults = read();
  75. this.resolveBuildDependenciesSnapshot = read();
  76. this.data = read();
  77. }
  78. }
  79. makeSerializable(
  80. PackContainer,
  81. "webpack/lib/cache/PackFileCacheStrategy",
  82. "PackContainer"
  83. );
  84. const MIN_CONTENT_SIZE = 1024 * 1024; // 1 MB
  85. const CONTENT_COUNT_TO_MERGE = 10;
  86. const MIN_ITEMS_IN_FRESH_PACK = 100;
  87. const MAX_ITEMS_IN_FRESH_PACK = 50000;
  88. const MAX_TIME_IN_FRESH_PACK = 1 * 60 * 1000; // 1 min
  89. /** @typedef {TODO | undefined} Value */
  90. /** @typedef {TODO | undefined} LazyValue */
  91. class PackItemInfo {
  92. /**
  93. * @param {string} identifier identifier of item
  94. * @param {string | null | undefined} etag etag of item
  95. * @param {Value} value fresh value of item
  96. */
  97. constructor(identifier, etag, value) {
  98. this.identifier = identifier;
  99. this.etag = etag;
  100. this.location = -1;
  101. this.lastAccess = Date.now();
  102. this.freshValue = value;
  103. }
  104. }
  105. class Pack {
  106. /**
  107. * @param {Logger} logger a logger
  108. * @param {number} maxAge max age of cache items
  109. */
  110. constructor(logger, maxAge) {
  111. /** @type {ItemInfo} */
  112. this.itemInfo = new Map();
  113. /** @type {(string | undefined)[]} */
  114. this.requests = [];
  115. this.requestsTimeout = undefined;
  116. /** @type {ItemInfo} */
  117. this.freshContent = new Map();
  118. /** @type {(undefined | PackContent)[]} */
  119. this.content = [];
  120. this.invalid = false;
  121. this.logger = logger;
  122. this.maxAge = maxAge;
  123. }
  124. /**
  125. * @param {string} identifier identifier
  126. */
  127. _addRequest(identifier) {
  128. this.requests.push(identifier);
  129. if (this.requestsTimeout === undefined) {
  130. this.requestsTimeout = setTimeout(() => {
  131. this.requests.push(undefined);
  132. this.requestsTimeout = undefined;
  133. }, MAX_TIME_IN_FRESH_PACK);
  134. if (this.requestsTimeout.unref) this.requestsTimeout.unref();
  135. }
  136. }
  137. stopCapturingRequests() {
  138. if (this.requestsTimeout !== undefined) {
  139. clearTimeout(this.requestsTimeout);
  140. this.requestsTimeout = undefined;
  141. }
  142. }
  143. /**
  144. * @param {string} identifier unique name for the resource
  145. * @param {string | null} etag etag of the resource
  146. * @returns {Value} cached content
  147. */
  148. get(identifier, etag) {
  149. const info = this.itemInfo.get(identifier);
  150. this._addRequest(identifier);
  151. if (info === undefined) {
  152. return;
  153. }
  154. if (info.etag !== etag) return null;
  155. info.lastAccess = Date.now();
  156. const loc = info.location;
  157. if (loc === -1) {
  158. return info.freshValue;
  159. }
  160. if (!this.content[loc]) {
  161. return;
  162. }
  163. return /** @type {PackContent} */ (this.content[loc]).get(identifier);
  164. }
  165. /**
  166. * @param {string} identifier unique name for the resource
  167. * @param {string | null} etag etag of the resource
  168. * @param {Value} data cached content
  169. * @returns {void}
  170. */
  171. set(identifier, etag, data) {
  172. if (!this.invalid) {
  173. this.invalid = true;
  174. this.logger.log(`Pack got invalid because of write to: ${identifier}`);
  175. }
  176. const info = this.itemInfo.get(identifier);
  177. if (info === undefined) {
  178. const newInfo = new PackItemInfo(identifier, etag, data);
  179. this.itemInfo.set(identifier, newInfo);
  180. this._addRequest(identifier);
  181. this.freshContent.set(identifier, newInfo);
  182. } else {
  183. const loc = info.location;
  184. if (loc >= 0) {
  185. this._addRequest(identifier);
  186. this.freshContent.set(identifier, info);
  187. const content = /** @type {PackContent} */ (this.content[loc]);
  188. content.delete(identifier);
  189. if (content.items.size === 0) {
  190. this.content[loc] = undefined;
  191. this.logger.debug("Pack %d got empty and is removed", loc);
  192. }
  193. }
  194. info.freshValue = data;
  195. info.lastAccess = Date.now();
  196. info.etag = etag;
  197. info.location = -1;
  198. }
  199. }
  200. getContentStats() {
  201. let count = 0;
  202. let size = 0;
  203. for (const content of this.content) {
  204. if (content !== undefined) {
  205. count++;
  206. const s = content.getSize();
  207. if (s > 0) {
  208. size += s;
  209. }
  210. }
  211. }
  212. return { count, size };
  213. }
  214. /**
  215. * @returns {number} new location of data entries
  216. */
  217. _findLocation() {
  218. let i;
  219. for (i = 0; i < this.content.length && this.content[i] !== undefined; i++);
  220. return i;
  221. }
  222. /**
  223. * @private
  224. * @param {Items} items items
  225. * @param {Items} usedItems used items
  226. * @param {number} newLoc new location
  227. */
  228. _gcAndUpdateLocation(items, usedItems, newLoc) {
  229. let count = 0;
  230. let lastGC;
  231. const now = Date.now();
  232. for (const identifier of items) {
  233. const info = /** @type {PackItemInfo} */ (this.itemInfo.get(identifier));
  234. if (now - info.lastAccess > this.maxAge) {
  235. this.itemInfo.delete(identifier);
  236. items.delete(identifier);
  237. usedItems.delete(identifier);
  238. count++;
  239. lastGC = identifier;
  240. } else {
  241. info.location = newLoc;
  242. }
  243. }
  244. if (count > 0) {
  245. this.logger.log(
  246. "Garbage Collected %d old items at pack %d (%d items remaining) e. g. %s",
  247. count,
  248. newLoc,
  249. items.size,
  250. lastGC
  251. );
  252. }
  253. }
  254. _persistFreshContent() {
  255. /** @typedef {{ items: Items, map: Content, loc: number }} PackItem */
  256. const itemsCount = this.freshContent.size;
  257. if (itemsCount > 0) {
  258. const packCount = Math.ceil(itemsCount / MAX_ITEMS_IN_FRESH_PACK);
  259. const itemsPerPack = Math.ceil(itemsCount / packCount);
  260. /** @type {PackItem[]} */
  261. const packs = [];
  262. let i = 0;
  263. let ignoreNextTimeTick = false;
  264. const createNextPack = () => {
  265. const loc = this._findLocation();
  266. this.content[loc] = /** @type {EXPECTED_ANY} */ (null); // reserve
  267. /** @type {PackItem} */
  268. const pack = {
  269. items: new Set(),
  270. map: new Map(),
  271. loc
  272. };
  273. packs.push(pack);
  274. return pack;
  275. };
  276. let pack = createNextPack();
  277. if (this.requestsTimeout !== undefined)
  278. clearTimeout(this.requestsTimeout);
  279. for (const identifier of this.requests) {
  280. if (identifier === undefined) {
  281. if (ignoreNextTimeTick) {
  282. ignoreNextTimeTick = false;
  283. } else if (pack.items.size >= MIN_ITEMS_IN_FRESH_PACK) {
  284. i = 0;
  285. pack = createNextPack();
  286. }
  287. continue;
  288. }
  289. const info = this.freshContent.get(identifier);
  290. if (info === undefined) continue;
  291. pack.items.add(identifier);
  292. pack.map.set(identifier, info.freshValue);
  293. info.location = pack.loc;
  294. info.freshValue = undefined;
  295. this.freshContent.delete(identifier);
  296. if (++i > itemsPerPack) {
  297. i = 0;
  298. pack = createNextPack();
  299. ignoreNextTimeTick = true;
  300. }
  301. }
  302. this.requests.length = 0;
  303. for (const pack of packs) {
  304. this.content[pack.loc] = new PackContent(
  305. pack.items,
  306. new Set(pack.items),
  307. new PackContentItems(pack.map)
  308. );
  309. }
  310. this.logger.log(
  311. `${itemsCount} fresh items in cache put into pack ${
  312. packs.length > 1
  313. ? packs
  314. .map(pack => `${pack.loc} (${pack.items.size} items)`)
  315. .join(", ")
  316. : packs[0].loc
  317. }`
  318. );
  319. }
  320. }
  321. /**
  322. * Merges small content files to a single content file
  323. */
  324. _optimizeSmallContent() {
  325. // 1. Find all small content files
  326. // Treat unused content files separately to avoid
  327. // a merge-split cycle
  328. /** @type {number[]} */
  329. const smallUsedContents = [];
  330. /** @type {number} */
  331. let smallUsedContentSize = 0;
  332. /** @type {number[]} */
  333. const smallUnusedContents = [];
  334. /** @type {number} */
  335. let smallUnusedContentSize = 0;
  336. for (let i = 0; i < this.content.length; i++) {
  337. const content = this.content[i];
  338. if (content === undefined) continue;
  339. if (content.outdated) continue;
  340. const size = content.getSize();
  341. if (size < 0 || size > MIN_CONTENT_SIZE) continue;
  342. if (content.used.size > 0) {
  343. smallUsedContents.push(i);
  344. smallUsedContentSize += size;
  345. } else {
  346. smallUnusedContents.push(i);
  347. smallUnusedContentSize += size;
  348. }
  349. }
  350. // 2. Check if minimum number is reached
  351. let mergedIndices;
  352. if (
  353. smallUsedContents.length >= CONTENT_COUNT_TO_MERGE ||
  354. smallUsedContentSize > MIN_CONTENT_SIZE
  355. ) {
  356. mergedIndices = smallUsedContents;
  357. } else if (
  358. smallUnusedContents.length >= CONTENT_COUNT_TO_MERGE ||
  359. smallUnusedContentSize > MIN_CONTENT_SIZE
  360. ) {
  361. mergedIndices = smallUnusedContents;
  362. } else return;
  363. /** @type {PackContent[] } */
  364. const mergedContent = [];
  365. // 3. Remove old content entries
  366. for (const i of mergedIndices) {
  367. mergedContent.push(/** @type {PackContent} */ (this.content[i]));
  368. this.content[i] = undefined;
  369. }
  370. // 4. Determine merged items
  371. /** @type {Items} */
  372. const mergedItems = new Set();
  373. /** @type {Items} */
  374. const mergedUsedItems = new Set();
  375. /** @type {((map: Content) => Promise<void>)[]} */
  376. const addToMergedMap = [];
  377. for (const content of mergedContent) {
  378. for (const identifier of content.items) {
  379. mergedItems.add(identifier);
  380. }
  381. for (const identifier of content.used) {
  382. mergedUsedItems.add(identifier);
  383. }
  384. addToMergedMap.push(async map => {
  385. // unpack existing content
  386. // after that values are accessible in .content
  387. await content.unpack(
  388. "it should be merged with other small pack contents"
  389. );
  390. for (const [identifier, value] of /** @type {Content} */ (
  391. content.content
  392. )) {
  393. map.set(identifier, value);
  394. }
  395. });
  396. }
  397. // 5. GC and update location of merged items
  398. const newLoc = this._findLocation();
  399. this._gcAndUpdateLocation(mergedItems, mergedUsedItems, newLoc);
  400. // 6. If not empty, store content somewhere
  401. if (mergedItems.size > 0) {
  402. this.content[newLoc] = new PackContent(
  403. mergedItems,
  404. mergedUsedItems,
  405. memoize(async () => {
  406. /** @type {Content} */
  407. const map = new Map();
  408. await Promise.all(addToMergedMap.map(fn => fn(map)));
  409. return new PackContentItems(map);
  410. })
  411. );
  412. this.logger.log(
  413. "Merged %d small files with %d cache items into pack %d",
  414. mergedContent.length,
  415. mergedItems.size,
  416. newLoc
  417. );
  418. }
  419. }
  420. /**
  421. * Split large content files with used and unused items
  422. * into two parts to separate used from unused items
  423. */
  424. _optimizeUnusedContent() {
  425. // 1. Find a large content file with used and unused items
  426. for (let i = 0; i < this.content.length; i++) {
  427. const content = this.content[i];
  428. if (content === undefined) continue;
  429. const size = content.getSize();
  430. if (size < MIN_CONTENT_SIZE) continue;
  431. const used = content.used.size;
  432. const total = content.items.size;
  433. if (used > 0 && used < total) {
  434. // 2. Remove this content
  435. this.content[i] = undefined;
  436. // 3. Determine items for the used content file
  437. const usedItems = new Set(content.used);
  438. const newLoc = this._findLocation();
  439. this._gcAndUpdateLocation(usedItems, usedItems, newLoc);
  440. // 4. Create content file for used items
  441. if (usedItems.size > 0) {
  442. this.content[newLoc] = new PackContent(
  443. usedItems,
  444. new Set(usedItems),
  445. async () => {
  446. await content.unpack(
  447. "it should be splitted into used and unused items"
  448. );
  449. /** @type {Content} */
  450. const map = new Map();
  451. for (const identifier of usedItems) {
  452. map.set(
  453. identifier,
  454. /** @type {Content} */
  455. (content.content).get(identifier)
  456. );
  457. }
  458. return new PackContentItems(map);
  459. }
  460. );
  461. }
  462. // 5. Determine items for the unused content file
  463. const unusedItems = new Set(content.items);
  464. const usedOfUnusedItems = new Set();
  465. for (const identifier of usedItems) {
  466. unusedItems.delete(identifier);
  467. }
  468. const newUnusedLoc = this._findLocation();
  469. this._gcAndUpdateLocation(unusedItems, usedOfUnusedItems, newUnusedLoc);
  470. // 6. Create content file for unused items
  471. if (unusedItems.size > 0) {
  472. this.content[newUnusedLoc] = new PackContent(
  473. unusedItems,
  474. usedOfUnusedItems,
  475. async () => {
  476. await content.unpack(
  477. "it should be splitted into used and unused items"
  478. );
  479. const map = new Map();
  480. for (const identifier of unusedItems) {
  481. map.set(
  482. identifier,
  483. /** @type {Content} */
  484. (content.content).get(identifier)
  485. );
  486. }
  487. return new PackContentItems(map);
  488. }
  489. );
  490. }
  491. this.logger.log(
  492. "Split pack %d into pack %d with %d used items and pack %d with %d unused items",
  493. i,
  494. newLoc,
  495. usedItems.size,
  496. newUnusedLoc,
  497. unusedItems.size
  498. );
  499. // optimizing only one of them is good enough and
  500. // reduces the amount of serialization needed
  501. return;
  502. }
  503. }
  504. }
  505. /**
  506. * Find the content with the oldest item and run GC on that.
  507. * Only runs for one content to avoid large invalidation.
  508. */
  509. _gcOldestContent() {
  510. /** @type {PackItemInfo | undefined} */
  511. let oldest;
  512. for (const info of this.itemInfo.values()) {
  513. if (oldest === undefined || info.lastAccess < oldest.lastAccess) {
  514. oldest = info;
  515. }
  516. }
  517. if (
  518. Date.now() - /** @type {PackItemInfo} */ (oldest).lastAccess >
  519. this.maxAge
  520. ) {
  521. const loc = /** @type {PackItemInfo} */ (oldest).location;
  522. if (loc < 0) return;
  523. const content = /** @type {PackContent} */ (this.content[loc]);
  524. const items = new Set(content.items);
  525. const usedItems = new Set(content.used);
  526. this._gcAndUpdateLocation(items, usedItems, loc);
  527. this.content[loc] =
  528. items.size > 0
  529. ? new PackContent(items, usedItems, async () => {
  530. await content.unpack(
  531. "it contains old items that should be garbage collected"
  532. );
  533. const map = new Map();
  534. for (const identifier of items) {
  535. map.set(
  536. identifier,
  537. /** @type {Content} */
  538. (content.content).get(identifier)
  539. );
  540. }
  541. return new PackContentItems(map);
  542. })
  543. : undefined;
  544. }
  545. }
  546. /**
  547. * @param {ObjectSerializerContext} context context
  548. */
  549. serialize({ write, writeSeparate }) {
  550. this._persistFreshContent();
  551. this._optimizeSmallContent();
  552. this._optimizeUnusedContent();
  553. this._gcOldestContent();
  554. for (const identifier of this.itemInfo.keys()) {
  555. write(identifier);
  556. }
  557. write(null); // null as marker of the end of keys
  558. for (const info of this.itemInfo.values()) {
  559. write(info.etag);
  560. }
  561. for (const info of this.itemInfo.values()) {
  562. write(info.lastAccess);
  563. }
  564. for (let i = 0; i < this.content.length; i++) {
  565. const content = this.content[i];
  566. if (content !== undefined) {
  567. write(content.items);
  568. content.writeLazy(lazy =>
  569. /** @type {NonNullable<ObjectSerializerContext["writeSeparate"]>} */
  570. (writeSeparate)(lazy, { name: `${i}` })
  571. );
  572. } else {
  573. write(undefined); // undefined marks an empty content slot
  574. }
  575. }
  576. write(null); // null as marker of the end of items
  577. }
  578. /**
  579. * @param {ObjectDeserializerContext & { logger: Logger }} context context
  580. */
  581. deserialize({ read, logger }) {
  582. this.logger = logger;
  583. {
  584. const items = [];
  585. let item = read();
  586. while (item !== null) {
  587. items.push(item);
  588. item = read();
  589. }
  590. this.itemInfo.clear();
  591. const infoItems = items.map(identifier => {
  592. const info = new PackItemInfo(identifier, undefined, undefined);
  593. this.itemInfo.set(identifier, info);
  594. return info;
  595. });
  596. for (const info of infoItems) {
  597. info.etag = read();
  598. }
  599. for (const info of infoItems) {
  600. info.lastAccess = read();
  601. }
  602. }
  603. this.content.length = 0;
  604. let items = read();
  605. while (items !== null) {
  606. if (items === undefined) {
  607. this.content.push(items);
  608. } else {
  609. const idx = this.content.length;
  610. const lazy = read();
  611. this.content.push(
  612. new PackContent(
  613. items,
  614. new Set(),
  615. lazy,
  616. logger,
  617. `${this.content.length}`
  618. )
  619. );
  620. for (const identifier of items) {
  621. /** @type {PackItemInfo} */
  622. (this.itemInfo.get(identifier)).location = idx;
  623. }
  624. }
  625. items = read();
  626. }
  627. }
  628. }
  629. makeSerializable(Pack, "webpack/lib/cache/PackFileCacheStrategy", "Pack");
  630. /** @typedef {Map<string, Value>} Content */
  631. class PackContentItems {
  632. /**
  633. * @param {Content} map items
  634. */
  635. constructor(map) {
  636. this.map = map;
  637. }
  638. /**
  639. * @param {ObjectSerializerContext & { logger: Logger, profile: boolean | undefined }} context context
  640. */
  641. serialize({ write, snapshot, rollback, logger, profile }) {
  642. if (profile) {
  643. write(false);
  644. for (const [key, value] of this.map) {
  645. const s = snapshot();
  646. try {
  647. write(key);
  648. const start = process.hrtime();
  649. write(value);
  650. const durationHr = process.hrtime(start);
  651. const duration = durationHr[0] * 1000 + durationHr[1] / 1e6;
  652. if (duration > 1) {
  653. if (duration > 500)
  654. logger.error(`Serialization of '${key}': ${duration} ms`);
  655. else if (duration > 50)
  656. logger.warn(`Serialization of '${key}': ${duration} ms`);
  657. else if (duration > 10)
  658. logger.info(`Serialization of '${key}': ${duration} ms`);
  659. else if (duration > 5)
  660. logger.log(`Serialization of '${key}': ${duration} ms`);
  661. else logger.debug(`Serialization of '${key}': ${duration} ms`);
  662. }
  663. } catch (err) {
  664. rollback(s);
  665. if (err === NOT_SERIALIZABLE) continue;
  666. const msg = "Skipped not serializable cache item";
  667. const notSerializableErr = /** @type {Error} */ (err);
  668. if (notSerializableErr.message.includes("ModuleBuildError")) {
  669. logger.log(
  670. `${msg} (in build error): ${notSerializableErr.message}`
  671. );
  672. logger.debug(
  673. `${msg} '${key}' (in build error): ${notSerializableErr.stack}`
  674. );
  675. } else {
  676. logger.warn(`${msg}: ${notSerializableErr.message}`);
  677. logger.debug(`${msg} '${key}': ${notSerializableErr.stack}`);
  678. }
  679. }
  680. }
  681. write(null);
  682. return;
  683. }
  684. // Try to serialize all at once
  685. const s = snapshot();
  686. try {
  687. write(true);
  688. write(this.map);
  689. } catch (_err) {
  690. rollback(s);
  691. // Try to serialize each item on it's own
  692. write(false);
  693. for (const [key, value] of this.map) {
  694. const s = snapshot();
  695. try {
  696. write(key);
  697. write(value);
  698. } catch (err) {
  699. rollback(s);
  700. if (err === NOT_SERIALIZABLE) continue;
  701. const notSerializableErr = /** @type {Error} */ (err);
  702. logger.warn(
  703. `Skipped not serializable cache item '${key}': ${notSerializableErr.message}`
  704. );
  705. logger.debug(notSerializableErr.stack);
  706. }
  707. }
  708. write(null);
  709. }
  710. }
  711. /**
  712. * @param {ObjectDeserializerContext & { logger: Logger, profile: boolean | undefined }} context context
  713. */
  714. deserialize({ read, logger, profile }) {
  715. if (read()) {
  716. this.map = read();
  717. } else if (profile) {
  718. const map = new Map();
  719. let key = read();
  720. while (key !== null) {
  721. const start = process.hrtime();
  722. const value = read();
  723. const durationHr = process.hrtime(start);
  724. const duration = durationHr[0] * 1000 + durationHr[1] / 1e6;
  725. if (duration > 1) {
  726. if (duration > 100)
  727. logger.error(`Deserialization of '${key}': ${duration} ms`);
  728. else if (duration > 20)
  729. logger.warn(`Deserialization of '${key}': ${duration} ms`);
  730. else if (duration > 5)
  731. logger.info(`Deserialization of '${key}': ${duration} ms`);
  732. else if (duration > 2)
  733. logger.log(`Deserialization of '${key}': ${duration} ms`);
  734. else logger.debug(`Deserialization of '${key}': ${duration} ms`);
  735. }
  736. map.set(key, value);
  737. key = read();
  738. }
  739. this.map = map;
  740. } else {
  741. const map = new Map();
  742. let key = read();
  743. while (key !== null) {
  744. map.set(key, read());
  745. key = read();
  746. }
  747. this.map = map;
  748. }
  749. }
  750. }
  751. makeSerializable(
  752. PackContentItems,
  753. "webpack/lib/cache/PackFileCacheStrategy",
  754. "PackContentItems"
  755. );
  756. /** @typedef {(() => Promise<PackContentItems> | PackContentItems)} LazyFunction */
  757. class PackContent {
  758. /*
  759. This class can be in these states:
  760. | this.lazy | this.content | this.outdated | state
  761. A1 | undefined | Map | false | fresh content
  762. A2 | undefined | Map | true | (will not happen)
  763. B1 | lazy () => {} | undefined | false | not deserialized
  764. B2 | lazy () => {} | undefined | true | not deserialized, but some items has been removed
  765. C1 | lazy* () => {} | Map | false | deserialized
  766. C2 | lazy* () => {} | Map | true | deserialized, and some items has been removed
  767. this.used is a subset of this.items.
  768. this.items is a subset of this.content.keys() resp. this.lazy().map.keys()
  769. When this.outdated === false, this.items === this.content.keys() resp. this.lazy().map.keys()
  770. When this.outdated === true, this.items should be used to recreated this.lazy/this.content.
  771. When this.lazy and this.content is set, they contain the same data.
  772. this.get must only be called with a valid item from this.items.
  773. In state C this.lazy is unMemoized
  774. */
  775. /**
  776. * @param {Items} items keys
  777. * @param {Items} usedItems used keys
  778. * @param {PackContentItems | (() => Promise<PackContentItems>)} dataOrFn sync or async content
  779. * @param {Logger=} logger logger for logging
  780. * @param {string=} lazyName name of dataOrFn for logging
  781. */
  782. constructor(items, usedItems, dataOrFn, logger, lazyName) {
  783. this.items = items;
  784. /** @type {LazyValue} */
  785. this.lazy = typeof dataOrFn === "function" ? dataOrFn : undefined;
  786. /** @type {Content | undefined} */
  787. this.content = typeof dataOrFn === "function" ? undefined : dataOrFn.map;
  788. this.outdated = false;
  789. this.used = usedItems;
  790. this.logger = logger;
  791. this.lazyName = lazyName;
  792. }
  793. /**
  794. * @param {string} identifier identifier
  795. * @returns {string | Promise<string>} result
  796. */
  797. get(identifier) {
  798. this.used.add(identifier);
  799. if (this.content) {
  800. return this.content.get(identifier);
  801. }
  802. const logger = /** @type {Logger} */ (this.logger);
  803. // We are in state B
  804. const { lazyName } = this;
  805. /** @type {string | undefined} */
  806. let timeMessage;
  807. if (lazyName) {
  808. // only log once
  809. this.lazyName = undefined;
  810. timeMessage = `restore cache content ${lazyName} (${formatSize(
  811. this.getSize()
  812. )})`;
  813. logger.log(
  814. `starting to restore cache content ${lazyName} (${formatSize(
  815. this.getSize()
  816. )}) because of request to: ${identifier}`
  817. );
  818. logger.time(timeMessage);
  819. }
  820. const value = /** @type {LazyFunction} */ (this.lazy)();
  821. if ("then" in value) {
  822. return value.then(data => {
  823. const map = data.map;
  824. if (timeMessage) {
  825. logger.timeEnd(timeMessage);
  826. }
  827. // Move to state C
  828. this.content = map;
  829. this.lazy = SerializerMiddleware.unMemoizeLazy(
  830. /** @type {LazyFunction} */
  831. (this.lazy)
  832. );
  833. return map.get(identifier);
  834. });
  835. }
  836. const map = value.map;
  837. if (timeMessage) {
  838. logger.timeEnd(timeMessage);
  839. }
  840. // Move to state C
  841. this.content = map;
  842. this.lazy = SerializerMiddleware.unMemoizeLazy(
  843. /** @type {LazyFunction} */
  844. (this.lazy)
  845. );
  846. return map.get(identifier);
  847. }
  848. /**
  849. * @param {string} reason explanation why unpack is necessary
  850. * @returns {void | Promise<void>} maybe a promise if lazy
  851. */
  852. unpack(reason) {
  853. if (this.content) return;
  854. const logger = /** @type {Logger} */ (this.logger);
  855. // Move from state B to C
  856. if (this.lazy) {
  857. const { lazyName } = this;
  858. /** @type {string | undefined} */
  859. let timeMessage;
  860. if (lazyName) {
  861. // only log once
  862. this.lazyName = undefined;
  863. timeMessage = `unpack cache content ${lazyName} (${formatSize(
  864. this.getSize()
  865. )})`;
  866. logger.log(
  867. `starting to unpack cache content ${lazyName} (${formatSize(
  868. this.getSize()
  869. )}) because ${reason}`
  870. );
  871. logger.time(timeMessage);
  872. }
  873. const value =
  874. /** @type {PackContentItems | Promise<PackContentItems>} */
  875. (this.lazy());
  876. if ("then" in value) {
  877. return value.then(data => {
  878. if (timeMessage) {
  879. logger.timeEnd(timeMessage);
  880. }
  881. this.content = data.map;
  882. });
  883. }
  884. if (timeMessage) {
  885. logger.timeEnd(timeMessage);
  886. }
  887. this.content = value.map;
  888. }
  889. }
  890. /**
  891. * @returns {number} size of the content or -1 if not known
  892. */
  893. getSize() {
  894. if (!this.lazy) return -1;
  895. const options =
  896. /** @type {{ options: { size?: number } }} */
  897. (this.lazy).options;
  898. if (!options) return -1;
  899. const size = options.size;
  900. if (typeof size !== "number") return -1;
  901. return size;
  902. }
  903. /**
  904. * @param {string} identifier identifier
  905. */
  906. delete(identifier) {
  907. this.items.delete(identifier);
  908. this.used.delete(identifier);
  909. this.outdated = true;
  910. }
  911. /**
  912. * @template T
  913. * @param {(item?: LazyValue) => (() => Promise<PackContentItems> | PackContentItems)} write write function
  914. * @returns {void}
  915. */
  916. writeLazy(write) {
  917. if (!this.outdated && this.lazy) {
  918. // State B1 or C1
  919. // this.lazy is still the valid deserialized version
  920. write(this.lazy);
  921. return;
  922. }
  923. if (!this.outdated && this.content) {
  924. // State A1
  925. const map = new Map(this.content);
  926. // Move to state C1
  927. this.lazy = SerializerMiddleware.unMemoizeLazy(
  928. write(() => new PackContentItems(map))
  929. );
  930. return;
  931. }
  932. if (this.content) {
  933. // State A2 or C2
  934. /** @type {Content} */
  935. const map = new Map();
  936. for (const item of this.items) {
  937. map.set(item, this.content.get(item));
  938. }
  939. // Move to state C1
  940. this.outdated = false;
  941. this.content = map;
  942. this.lazy = SerializerMiddleware.unMemoizeLazy(
  943. write(() => new PackContentItems(map))
  944. );
  945. return;
  946. }
  947. const logger = /** @type {Logger} */ (this.logger);
  948. // State B2
  949. const { lazyName } = this;
  950. /** @type {string | undefined} */
  951. let timeMessage;
  952. if (lazyName) {
  953. // only log once
  954. this.lazyName = undefined;
  955. timeMessage = `unpack cache content ${lazyName} (${formatSize(
  956. this.getSize()
  957. )})`;
  958. logger.log(
  959. `starting to unpack cache content ${lazyName} (${formatSize(
  960. this.getSize()
  961. )}) because it's outdated and need to be serialized`
  962. );
  963. logger.time(timeMessage);
  964. }
  965. const value = /** @type {LazyFunction} */ (this.lazy)();
  966. this.outdated = false;
  967. if ("then" in value) {
  968. // Move to state B1
  969. this.lazy = write(() =>
  970. value.then(data => {
  971. if (timeMessage) {
  972. logger.timeEnd(timeMessage);
  973. }
  974. const oldMap = data.map;
  975. /** @type {Content} */
  976. const map = new Map();
  977. for (const item of this.items) {
  978. map.set(item, oldMap.get(item));
  979. }
  980. // Move to state C1 (or maybe C2)
  981. this.content = map;
  982. this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy);
  983. return new PackContentItems(map);
  984. })
  985. );
  986. } else {
  987. // Move to state C1
  988. if (timeMessage) {
  989. logger.timeEnd(timeMessage);
  990. }
  991. const oldMap = value.map;
  992. /** @type {Content} */
  993. const map = new Map();
  994. for (const item of this.items) {
  995. map.set(item, oldMap.get(item));
  996. }
  997. this.content = map;
  998. this.lazy = write(() => new PackContentItems(map));
  999. }
  1000. }
  1001. }
  1002. /**
  1003. * @param {Buffer} buf buffer
  1004. * @returns {Buffer} buffer that can be collected
  1005. */
  1006. const allowCollectingMemory = buf => {
  1007. const wasted = buf.buffer.byteLength - buf.byteLength;
  1008. if (wasted > 8192 && (wasted > 1048576 || wasted > buf.byteLength)) {
  1009. return Buffer.from(buf);
  1010. }
  1011. return buf;
  1012. };
  1013. class PackFileCacheStrategy {
  1014. /**
  1015. * @param {object} options options
  1016. * @param {Compiler} options.compiler the compiler
  1017. * @param {IntermediateFileSystem} options.fs the filesystem
  1018. * @param {string} options.context the context directory
  1019. * @param {string} options.cacheLocation the location of the cache data
  1020. * @param {string} options.version version identifier
  1021. * @param {Logger} options.logger a logger
  1022. * @param {SnapshotOptions} options.snapshot options regarding snapshotting
  1023. * @param {number} options.maxAge max age of cache items
  1024. * @param {boolean | undefined} options.profile track and log detailed timing information for individual cache items
  1025. * @param {boolean | undefined} options.allowCollectingMemory allow to collect unused memory created during deserialization
  1026. * @param {false | "gzip" | "brotli" | undefined} options.compression compression used
  1027. * @param {boolean | undefined} options.readonly disable storing cache into filesystem
  1028. */
  1029. constructor({
  1030. compiler,
  1031. fs,
  1032. context,
  1033. cacheLocation,
  1034. version,
  1035. logger,
  1036. snapshot,
  1037. maxAge,
  1038. profile,
  1039. allowCollectingMemory,
  1040. compression,
  1041. readonly
  1042. }) {
  1043. this.fileSerializer = createFileSerializer(
  1044. fs,
  1045. /** @type {string | Hash} */
  1046. (compiler.options.output.hashFunction)
  1047. );
  1048. this.fileSystemInfo = new FileSystemInfo(fs, {
  1049. managedPaths: snapshot.managedPaths,
  1050. immutablePaths: snapshot.immutablePaths,
  1051. logger: logger.getChildLogger("webpack.FileSystemInfo"),
  1052. hashFunction: compiler.options.output.hashFunction
  1053. });
  1054. this.compiler = compiler;
  1055. this.context = context;
  1056. this.cacheLocation = cacheLocation;
  1057. this.version = version;
  1058. this.logger = logger;
  1059. this.maxAge = maxAge;
  1060. this.profile = profile;
  1061. this.readonly = readonly;
  1062. this.allowCollectingMemory = allowCollectingMemory;
  1063. this.compression = compression;
  1064. this._extension =
  1065. compression === "brotli"
  1066. ? ".pack.br"
  1067. : compression === "gzip"
  1068. ? ".pack.gz"
  1069. : ".pack";
  1070. this.snapshot = snapshot;
  1071. /** @type {BuildDependencies} */
  1072. this.buildDependencies = new Set();
  1073. /** @type {LazySet<string>} */
  1074. this.newBuildDependencies = new LazySet();
  1075. /** @type {Snapshot | undefined} */
  1076. this.resolveBuildDependenciesSnapshot = undefined;
  1077. /** @type {ResolveResults | undefined} */
  1078. this.resolveResults = undefined;
  1079. /** @type {Snapshot | undefined} */
  1080. this.buildSnapshot = undefined;
  1081. /** @type {Promise<Pack> | undefined} */
  1082. this.packPromise = this._openPack();
  1083. this.storePromise = Promise.resolve();
  1084. }
  1085. /**
  1086. * @returns {Promise<Pack>} pack
  1087. */
  1088. _getPack() {
  1089. if (this.packPromise === undefined) {
  1090. this.packPromise = this.storePromise.then(() => this._openPack());
  1091. }
  1092. return this.packPromise;
  1093. }
  1094. /**
  1095. * @returns {Promise<Pack>} the pack
  1096. */
  1097. _openPack() {
  1098. const { logger, profile, cacheLocation, version } = this;
  1099. /** @type {Snapshot} */
  1100. let buildSnapshot;
  1101. /** @type {BuildDependencies} */
  1102. let buildDependencies;
  1103. /** @type {BuildDependencies} */
  1104. let newBuildDependencies;
  1105. /** @type {Snapshot} */
  1106. let resolveBuildDependenciesSnapshot;
  1107. /** @type {ResolveResults | undefined} */
  1108. let resolveResults;
  1109. logger.time("restore cache container");
  1110. return this.fileSerializer
  1111. .deserialize(null, {
  1112. filename: `${cacheLocation}/index${this._extension}`,
  1113. extension: `${this._extension}`,
  1114. logger,
  1115. profile,
  1116. retainedBuffer: this.allowCollectingMemory
  1117. ? allowCollectingMemory
  1118. : undefined
  1119. })
  1120. .catch(err => {
  1121. if (err.code !== "ENOENT") {
  1122. logger.warn(
  1123. `Restoring pack failed from ${cacheLocation}${this._extension}: ${err}`
  1124. );
  1125. logger.debug(err.stack);
  1126. } else {
  1127. logger.debug(
  1128. `No pack exists at ${cacheLocation}${this._extension}: ${err}`
  1129. );
  1130. }
  1131. return undefined;
  1132. })
  1133. .then(packContainer => {
  1134. logger.timeEnd("restore cache container");
  1135. if (!packContainer) return;
  1136. if (!(packContainer instanceof PackContainer)) {
  1137. logger.warn(
  1138. `Restored pack from ${cacheLocation}${this._extension}, but contained content is unexpected.`,
  1139. packContainer
  1140. );
  1141. return;
  1142. }
  1143. if (packContainer.version !== version) {
  1144. logger.log(
  1145. `Restored pack from ${cacheLocation}${this._extension}, but version doesn't match.`
  1146. );
  1147. return;
  1148. }
  1149. logger.time("check build dependencies");
  1150. return Promise.all([
  1151. new Promise((resolve, reject) => {
  1152. this.fileSystemInfo.checkSnapshotValid(
  1153. packContainer.buildSnapshot,
  1154. (err, valid) => {
  1155. if (err) {
  1156. logger.log(
  1157. `Restored pack from ${cacheLocation}${this._extension}, but checking snapshot of build dependencies errored: ${err}.`
  1158. );
  1159. logger.debug(err.stack);
  1160. return resolve(false);
  1161. }
  1162. if (!valid) {
  1163. logger.log(
  1164. `Restored pack from ${cacheLocation}${this._extension}, but build dependencies have changed.`
  1165. );
  1166. return resolve(false);
  1167. }
  1168. buildSnapshot = packContainer.buildSnapshot;
  1169. return resolve(true);
  1170. }
  1171. );
  1172. }),
  1173. new Promise((resolve, reject) => {
  1174. this.fileSystemInfo.checkSnapshotValid(
  1175. packContainer.resolveBuildDependenciesSnapshot,
  1176. (err, valid) => {
  1177. if (err) {
  1178. logger.log(
  1179. `Restored pack from ${cacheLocation}${this._extension}, but checking snapshot of resolving of build dependencies errored: ${err}.`
  1180. );
  1181. logger.debug(err.stack);
  1182. return resolve(false);
  1183. }
  1184. if (valid) {
  1185. resolveBuildDependenciesSnapshot =
  1186. packContainer.resolveBuildDependenciesSnapshot;
  1187. buildDependencies = packContainer.buildDependencies;
  1188. resolveResults = packContainer.resolveResults;
  1189. return resolve(true);
  1190. }
  1191. logger.log(
  1192. "resolving of build dependencies is invalid, will re-resolve build dependencies"
  1193. );
  1194. this.fileSystemInfo.checkResolveResultsValid(
  1195. packContainer.resolveResults,
  1196. (err, valid) => {
  1197. if (err) {
  1198. logger.log(
  1199. `Restored pack from ${cacheLocation}${this._extension}, but resolving of build dependencies errored: ${err}.`
  1200. );
  1201. logger.debug(err.stack);
  1202. return resolve(false);
  1203. }
  1204. if (valid) {
  1205. newBuildDependencies = packContainer.buildDependencies;
  1206. resolveResults = packContainer.resolveResults;
  1207. return resolve(true);
  1208. }
  1209. logger.log(
  1210. `Restored pack from ${cacheLocation}${this._extension}, but build dependencies resolve to different locations.`
  1211. );
  1212. return resolve(false);
  1213. }
  1214. );
  1215. }
  1216. );
  1217. })
  1218. ])
  1219. .catch(err => {
  1220. logger.timeEnd("check build dependencies");
  1221. throw err;
  1222. })
  1223. .then(([buildSnapshotValid, resolveValid]) => {
  1224. logger.timeEnd("check build dependencies");
  1225. if (buildSnapshotValid && resolveValid) {
  1226. logger.time("restore cache content metadata");
  1227. const d = /** @type {TODO} */ (packContainer).data();
  1228. logger.timeEnd("restore cache content metadata");
  1229. return d;
  1230. }
  1231. return undefined;
  1232. });
  1233. })
  1234. .then(pack => {
  1235. if (pack) {
  1236. pack.maxAge = this.maxAge;
  1237. this.buildSnapshot = buildSnapshot;
  1238. if (buildDependencies) this.buildDependencies = buildDependencies;
  1239. if (newBuildDependencies)
  1240. this.newBuildDependencies.addAll(newBuildDependencies);
  1241. this.resolveResults = resolveResults;
  1242. this.resolveBuildDependenciesSnapshot =
  1243. resolveBuildDependenciesSnapshot;
  1244. return pack;
  1245. }
  1246. return new Pack(logger, this.maxAge);
  1247. })
  1248. .catch(err => {
  1249. this.logger.warn(
  1250. `Restoring pack from ${cacheLocation}${this._extension} failed: ${err}`
  1251. );
  1252. this.logger.debug(err.stack);
  1253. return new Pack(logger, this.maxAge);
  1254. });
  1255. }
  1256. /**
  1257. * @param {string} identifier unique name for the resource
  1258. * @param {Etag | null} etag etag of the resource
  1259. * @param {Value} data cached content
  1260. * @returns {Promise<void>} promise
  1261. */
  1262. store(identifier, etag, data) {
  1263. if (this.readonly) return Promise.resolve();
  1264. return this._getPack().then(pack => {
  1265. pack.set(identifier, etag === null ? null : etag.toString(), data);
  1266. });
  1267. }
  1268. /**
  1269. * @param {string} identifier unique name for the resource
  1270. * @param {Etag | null} etag etag of the resource
  1271. * @returns {Promise<Value>} promise to the cached content
  1272. */
  1273. restore(identifier, etag) {
  1274. return this._getPack()
  1275. .then(pack =>
  1276. pack.get(identifier, etag === null ? null : etag.toString())
  1277. )
  1278. .catch(err => {
  1279. if (err && err.code !== "ENOENT") {
  1280. this.logger.warn(
  1281. `Restoring failed for ${identifier} from pack: ${err}`
  1282. );
  1283. this.logger.debug(err.stack);
  1284. }
  1285. });
  1286. }
  1287. /**
  1288. * @param {LazySet<string> | Iterable<string>} dependencies dependencies to store
  1289. */
  1290. storeBuildDependencies(dependencies) {
  1291. if (this.readonly) return;
  1292. this.newBuildDependencies.addAll(dependencies);
  1293. }
  1294. afterAllStored() {
  1295. const packPromise = this.packPromise;
  1296. if (packPromise === undefined) return Promise.resolve();
  1297. const reportProgress = ProgressPlugin.getReporter(this.compiler);
  1298. return (this.storePromise = packPromise
  1299. .then(pack => {
  1300. pack.stopCapturingRequests();
  1301. if (!pack.invalid) return;
  1302. this.packPromise = undefined;
  1303. this.logger.log("Storing pack...");
  1304. let promise;
  1305. const newBuildDependencies = new Set();
  1306. for (const dep of this.newBuildDependencies) {
  1307. if (!this.buildDependencies.has(dep)) {
  1308. newBuildDependencies.add(dep);
  1309. }
  1310. }
  1311. if (newBuildDependencies.size > 0 || !this.buildSnapshot) {
  1312. if (reportProgress) reportProgress(0.5, "resolve build dependencies");
  1313. this.logger.debug(
  1314. `Capturing build dependencies... (${Array.from(
  1315. newBuildDependencies
  1316. ).join(", ")})`
  1317. );
  1318. promise = new Promise(
  1319. /**
  1320. * @param {(value?: undefined) => void} resolve resolve
  1321. * @param {(reason?: Error) => void} reject reject
  1322. */
  1323. (resolve, reject) => {
  1324. this.logger.time("resolve build dependencies");
  1325. this.fileSystemInfo.resolveBuildDependencies(
  1326. this.context,
  1327. newBuildDependencies,
  1328. (err, result) => {
  1329. this.logger.timeEnd("resolve build dependencies");
  1330. if (err) return reject(err);
  1331. this.logger.time("snapshot build dependencies");
  1332. const {
  1333. files,
  1334. directories,
  1335. missing,
  1336. resolveResults,
  1337. resolveDependencies
  1338. } = /** @type {ResolveBuildDependenciesResult} */ (result);
  1339. if (this.resolveResults) {
  1340. for (const [key, value] of resolveResults) {
  1341. this.resolveResults.set(key, value);
  1342. }
  1343. } else {
  1344. this.resolveResults = resolveResults;
  1345. }
  1346. if (reportProgress) {
  1347. reportProgress(
  1348. 0.6,
  1349. "snapshot build dependencies",
  1350. "resolving"
  1351. );
  1352. }
  1353. this.fileSystemInfo.createSnapshot(
  1354. undefined,
  1355. resolveDependencies.files,
  1356. resolveDependencies.directories,
  1357. resolveDependencies.missing,
  1358. this.snapshot.resolveBuildDependencies,
  1359. (err, snapshot) => {
  1360. if (err) {
  1361. this.logger.timeEnd("snapshot build dependencies");
  1362. return reject(err);
  1363. }
  1364. if (!snapshot) {
  1365. this.logger.timeEnd("snapshot build dependencies");
  1366. return reject(
  1367. new Error("Unable to snapshot resolve dependencies")
  1368. );
  1369. }
  1370. if (this.resolveBuildDependenciesSnapshot) {
  1371. this.resolveBuildDependenciesSnapshot =
  1372. this.fileSystemInfo.mergeSnapshots(
  1373. this.resolveBuildDependenciesSnapshot,
  1374. snapshot
  1375. );
  1376. } else {
  1377. this.resolveBuildDependenciesSnapshot = snapshot;
  1378. }
  1379. if (reportProgress) {
  1380. reportProgress(
  1381. 0.7,
  1382. "snapshot build dependencies",
  1383. "modules"
  1384. );
  1385. }
  1386. this.fileSystemInfo.createSnapshot(
  1387. undefined,
  1388. files,
  1389. directories,
  1390. missing,
  1391. this.snapshot.buildDependencies,
  1392. (err, snapshot) => {
  1393. this.logger.timeEnd("snapshot build dependencies");
  1394. if (err) return reject(err);
  1395. if (!snapshot) {
  1396. return reject(
  1397. new Error("Unable to snapshot build dependencies")
  1398. );
  1399. }
  1400. this.logger.debug("Captured build dependencies");
  1401. if (this.buildSnapshot) {
  1402. this.buildSnapshot =
  1403. this.fileSystemInfo.mergeSnapshots(
  1404. this.buildSnapshot,
  1405. snapshot
  1406. );
  1407. } else {
  1408. this.buildSnapshot = snapshot;
  1409. }
  1410. resolve();
  1411. }
  1412. );
  1413. }
  1414. );
  1415. }
  1416. );
  1417. }
  1418. );
  1419. } else {
  1420. promise = Promise.resolve();
  1421. }
  1422. return promise.then(() => {
  1423. if (reportProgress) reportProgress(0.8, "serialize pack");
  1424. this.logger.time("store pack");
  1425. const updatedBuildDependencies = new Set(this.buildDependencies);
  1426. for (const dep of newBuildDependencies) {
  1427. updatedBuildDependencies.add(dep);
  1428. }
  1429. const content = new PackContainer(
  1430. pack,
  1431. this.version,
  1432. /** @type {Snapshot} */
  1433. (this.buildSnapshot),
  1434. updatedBuildDependencies,
  1435. /** @type {ResolveResults} */
  1436. (this.resolveResults),
  1437. /** @type {Snapshot} */
  1438. (this.resolveBuildDependenciesSnapshot)
  1439. );
  1440. return this.fileSerializer
  1441. .serialize(content, {
  1442. filename: `${this.cacheLocation}/index${this._extension}`,
  1443. extension: `${this._extension}`,
  1444. logger: this.logger,
  1445. profile: this.profile
  1446. })
  1447. .then(() => {
  1448. for (const dep of newBuildDependencies) {
  1449. this.buildDependencies.add(dep);
  1450. }
  1451. this.newBuildDependencies.clear();
  1452. this.logger.timeEnd("store pack");
  1453. const stats = pack.getContentStats();
  1454. this.logger.log(
  1455. "Stored pack (%d items, %d files, %d MiB)",
  1456. pack.itemInfo.size,
  1457. stats.count,
  1458. Math.round(stats.size / 1024 / 1024)
  1459. );
  1460. })
  1461. .catch(err => {
  1462. this.logger.timeEnd("store pack");
  1463. this.logger.warn(`Caching failed for pack: ${err}`);
  1464. this.logger.debug(err.stack);
  1465. });
  1466. });
  1467. })
  1468. .catch(err => {
  1469. this.logger.warn(`Caching failed for pack: ${err}`);
  1470. this.logger.debug(err.stack);
  1471. }));
  1472. }
  1473. clear() {
  1474. this.fileSystemInfo.clear();
  1475. this.buildDependencies.clear();
  1476. this.newBuildDependencies.clear();
  1477. this.resolveBuildDependenciesSnapshot = undefined;
  1478. this.resolveResults = undefined;
  1479. this.buildSnapshot = undefined;
  1480. this.packPromise = undefined;
  1481. }
  1482. }
  1483. module.exports = PackFileCacheStrategy;