PackFileCacheStrategy.js 40 KB

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