PackFileCacheStrategy.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430
  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. const msg = "Skipped not serializable cache item";
  604. if (e.message.includes("ModuleBuildError")) {
  605. logger.log(`${msg} (in build error): ${e.message}`);
  606. logger.debug(`${msg} '${key}' (in build error): ${e.stack}`);
  607. } else {
  608. logger.warn(`${msg}: ${e.message}`);
  609. logger.debug(`${msg} '${key}': ${e.stack}`);
  610. }
  611. }
  612. }
  613. write(null);
  614. return;
  615. }
  616. // Try to serialize all at once
  617. const s = snapshot();
  618. try {
  619. write(true);
  620. write(this.map);
  621. } catch (e) {
  622. rollback(s);
  623. // Try to serialize each item on it's own
  624. write(false);
  625. for (const [key, value] of this.map) {
  626. const s = snapshot();
  627. try {
  628. write(key);
  629. write(value);
  630. } catch (e) {
  631. rollback(s);
  632. if (e === NOT_SERIALIZABLE) continue;
  633. logger.warn(
  634. `Skipped not serializable cache item '${key}': ${e.message}`
  635. );
  636. logger.debug(e.stack);
  637. }
  638. }
  639. write(null);
  640. }
  641. }
  642. deserialize({ read, logger, profile }) {
  643. if (read()) {
  644. this.map = read();
  645. } else if (profile) {
  646. const map = new Map();
  647. let key = read();
  648. while (key !== null) {
  649. const start = process.hrtime();
  650. const value = read();
  651. const durationHr = process.hrtime(start);
  652. const duration = durationHr[0] * 1000 + durationHr[1] / 1e6;
  653. if (duration > 1) {
  654. if (duration > 100)
  655. logger.error(`Deserialization of '${key}': ${duration} ms`);
  656. else if (duration > 20)
  657. logger.warn(`Deserialization of '${key}': ${duration} ms`);
  658. else if (duration > 5)
  659. logger.info(`Deserialization of '${key}': ${duration} ms`);
  660. else if (duration > 2)
  661. logger.log(`Deserialization of '${key}': ${duration} ms`);
  662. else logger.debug(`Deserialization of '${key}': ${duration} ms`);
  663. }
  664. map.set(key, value);
  665. key = read();
  666. }
  667. this.map = map;
  668. } else {
  669. const map = new Map();
  670. let key = read();
  671. while (key !== null) {
  672. map.set(key, read());
  673. key = read();
  674. }
  675. this.map = map;
  676. }
  677. }
  678. }
  679. makeSerializable(
  680. PackContentItems,
  681. "webpack/lib/cache/PackFileCacheStrategy",
  682. "PackContentItems"
  683. );
  684. class PackContent {
  685. /*
  686. This class can be in these states:
  687. | this.lazy | this.content | this.outdated | state
  688. A1 | undefined | Map | false | fresh content
  689. A2 | undefined | Map | true | (will not happen)
  690. B1 | lazy () => {} | undefined | false | not deserialized
  691. B2 | lazy () => {} | undefined | true | not deserialized, but some items has been removed
  692. C1 | lazy* () => {} | Map | false | deserialized
  693. C2 | lazy* () => {} | Map | true | deserialized, and some items has been removed
  694. this.used is a subset of this.items.
  695. this.items is a subset of this.content.keys() resp. this.lazy().map.keys()
  696. When this.outdated === false, this.items === this.content.keys() resp. this.lazy().map.keys()
  697. When this.outdated === true, this.items should be used to recreated this.lazy/this.content.
  698. When this.lazy and this.content is set, they contain the same data.
  699. this.get must only be called with a valid item from this.items.
  700. In state C this.lazy is unMemoized
  701. */
  702. /**
  703. * @param {Set<string>} items keys
  704. * @param {Set<string>} usedItems used keys
  705. * @param {PackContentItems | function(): Promise<PackContentItems>} dataOrFn sync or async content
  706. * @param {Logger=} logger logger for logging
  707. * @param {string=} lazyName name of dataOrFn for logging
  708. */
  709. constructor(items, usedItems, dataOrFn, logger, lazyName) {
  710. this.items = items;
  711. /** @type {function(): Promise<PackContentItems> | PackContentItems} */
  712. this.lazy = typeof dataOrFn === "function" ? dataOrFn : undefined;
  713. /** @type {Map<string, any>} */
  714. this.content = typeof dataOrFn === "function" ? undefined : dataOrFn.map;
  715. this.outdated = false;
  716. this.used = usedItems;
  717. this.logger = logger;
  718. this.lazyName = lazyName;
  719. }
  720. get(identifier) {
  721. this.used.add(identifier);
  722. if (this.content) {
  723. return this.content.get(identifier);
  724. }
  725. // We are in state B
  726. const { lazyName } = this;
  727. let timeMessage;
  728. if (lazyName) {
  729. // only log once
  730. this.lazyName = undefined;
  731. timeMessage = `restore cache content ${lazyName} (${formatSize(
  732. this.getSize()
  733. )})`;
  734. this.logger.log(
  735. `starting to restore cache content ${lazyName} (${formatSize(
  736. this.getSize()
  737. )}) because of request to: ${identifier}`
  738. );
  739. this.logger.time(timeMessage);
  740. }
  741. const value = this.lazy();
  742. if ("then" in value) {
  743. return value.then(data => {
  744. const map = data.map;
  745. if (timeMessage) {
  746. this.logger.timeEnd(timeMessage);
  747. }
  748. // Move to state C
  749. this.content = map;
  750. this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy);
  751. return map.get(identifier);
  752. });
  753. } else {
  754. const map = value.map;
  755. if (timeMessage) {
  756. this.logger.timeEnd(timeMessage);
  757. }
  758. // Move to state C
  759. this.content = map;
  760. this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy);
  761. return map.get(identifier);
  762. }
  763. }
  764. /**
  765. * @param {string} reason explanation why unpack is necessary
  766. * @returns {void | Promise} maybe a promise if lazy
  767. */
  768. unpack(reason) {
  769. if (this.content) return;
  770. // Move from state B to C
  771. if (this.lazy) {
  772. const { lazyName } = this;
  773. let timeMessage;
  774. if (lazyName) {
  775. // only log once
  776. this.lazyName = undefined;
  777. timeMessage = `unpack cache content ${lazyName} (${formatSize(
  778. this.getSize()
  779. )})`;
  780. this.logger.log(
  781. `starting to unpack cache content ${lazyName} (${formatSize(
  782. this.getSize()
  783. )}) because ${reason}`
  784. );
  785. this.logger.time(timeMessage);
  786. }
  787. const value = this.lazy();
  788. if ("then" in value) {
  789. return value.then(data => {
  790. if (timeMessage) {
  791. this.logger.timeEnd(timeMessage);
  792. }
  793. this.content = data.map;
  794. });
  795. } else {
  796. if (timeMessage) {
  797. this.logger.timeEnd(timeMessage);
  798. }
  799. this.content = value.map;
  800. }
  801. }
  802. }
  803. /**
  804. * @returns {number} size of the content or -1 if not known
  805. */
  806. getSize() {
  807. if (!this.lazy) return -1;
  808. const options = /** @type {any} */ (this.lazy).options;
  809. if (!options) return -1;
  810. const size = options.size;
  811. if (typeof size !== "number") return -1;
  812. return size;
  813. }
  814. delete(identifier) {
  815. this.items.delete(identifier);
  816. this.used.delete(identifier);
  817. this.outdated = true;
  818. }
  819. /**
  820. * @template T
  821. * @param {function(any): function(): Promise<PackContentItems> | PackContentItems} write write function
  822. * @returns {void}
  823. */
  824. writeLazy(write) {
  825. if (!this.outdated && this.lazy) {
  826. // State B1 or C1
  827. // this.lazy is still the valid deserialized version
  828. write(this.lazy);
  829. return;
  830. }
  831. if (!this.outdated && this.content) {
  832. // State A1
  833. const map = new Map(this.content);
  834. // Move to state C1
  835. this.lazy = SerializerMiddleware.unMemoizeLazy(
  836. write(() => new PackContentItems(map))
  837. );
  838. return;
  839. }
  840. if (this.content) {
  841. // State A2 or C2
  842. /** @type {Map<string, any>} */
  843. const map = new Map();
  844. for (const item of this.items) {
  845. map.set(item, this.content.get(item));
  846. }
  847. // Move to state C1
  848. this.outdated = false;
  849. this.content = map;
  850. this.lazy = SerializerMiddleware.unMemoizeLazy(
  851. write(() => new PackContentItems(map))
  852. );
  853. return;
  854. }
  855. // State B2
  856. const { lazyName } = this;
  857. let timeMessage;
  858. if (lazyName) {
  859. // only log once
  860. this.lazyName = undefined;
  861. timeMessage = `unpack cache content ${lazyName} (${formatSize(
  862. this.getSize()
  863. )})`;
  864. this.logger.log(
  865. `starting to unpack cache content ${lazyName} (${formatSize(
  866. this.getSize()
  867. )}) because it's outdated and need to be serialized`
  868. );
  869. this.logger.time(timeMessage);
  870. }
  871. const value = this.lazy();
  872. this.outdated = false;
  873. if ("then" in value) {
  874. // Move to state B1
  875. this.lazy = write(() =>
  876. value.then(data => {
  877. if (timeMessage) {
  878. this.logger.timeEnd(timeMessage);
  879. }
  880. const oldMap = data.map;
  881. /** @type {Map<string, any>} */
  882. const map = new Map();
  883. for (const item of this.items) {
  884. map.set(item, oldMap.get(item));
  885. }
  886. // Move to state C1 (or maybe C2)
  887. this.content = map;
  888. this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy);
  889. return new PackContentItems(map);
  890. })
  891. );
  892. } else {
  893. // Move to state C1
  894. if (timeMessage) {
  895. this.logger.timeEnd(timeMessage);
  896. }
  897. const oldMap = value.map;
  898. /** @type {Map<string, any>} */
  899. const map = new Map();
  900. for (const item of this.items) {
  901. map.set(item, oldMap.get(item));
  902. }
  903. this.content = map;
  904. this.lazy = write(() => new PackContentItems(map));
  905. }
  906. }
  907. }
  908. const allowCollectingMemory = buf => {
  909. const wasted = buf.buffer.byteLength - buf.byteLength;
  910. if (wasted > 8192 && (wasted > 1048576 || wasted > buf.byteLength)) {
  911. return Buffer.from(buf);
  912. }
  913. return buf;
  914. };
  915. class PackFileCacheStrategy {
  916. /**
  917. * @param {Object} options options
  918. * @param {Compiler} options.compiler the compiler
  919. * @param {IntermediateFileSystem} options.fs the filesystem
  920. * @param {string} options.context the context directory
  921. * @param {string} options.cacheLocation the location of the cache data
  922. * @param {string} options.version version identifier
  923. * @param {Logger} options.logger a logger
  924. * @param {SnapshotOptions} options.snapshot options regarding snapshotting
  925. * @param {number} options.maxAge max age of cache items
  926. * @param {boolean} options.profile track and log detailed timing information for individual cache items
  927. * @param {boolean} options.allowCollectingMemory allow to collect unused memory created during deserialization
  928. * @param {false | "gzip" | "brotli"} options.compression compression used
  929. */
  930. constructor({
  931. compiler,
  932. fs,
  933. context,
  934. cacheLocation,
  935. version,
  936. logger,
  937. snapshot,
  938. maxAge,
  939. profile,
  940. allowCollectingMemory,
  941. compression
  942. }) {
  943. this.fileSerializer = createFileSerializer(
  944. fs,
  945. compiler.options.output.hashFunction
  946. );
  947. this.fileSystemInfo = new FileSystemInfo(fs, {
  948. managedPaths: snapshot.managedPaths,
  949. immutablePaths: snapshot.immutablePaths,
  950. logger: logger.getChildLogger("webpack.FileSystemInfo"),
  951. hashFunction: compiler.options.output.hashFunction
  952. });
  953. this.compiler = compiler;
  954. this.context = context;
  955. this.cacheLocation = cacheLocation;
  956. this.version = version;
  957. this.logger = logger;
  958. this.maxAge = maxAge;
  959. this.profile = profile;
  960. this.allowCollectingMemory = allowCollectingMemory;
  961. this.compression = compression;
  962. this._extension =
  963. compression === "brotli"
  964. ? ".pack.br"
  965. : compression === "gzip"
  966. ? ".pack.gz"
  967. : ".pack";
  968. this.snapshot = snapshot;
  969. /** @type {Set<string>} */
  970. this.buildDependencies = new Set();
  971. /** @type {LazySet<string>} */
  972. this.newBuildDependencies = new LazySet();
  973. /** @type {Snapshot} */
  974. this.resolveBuildDependenciesSnapshot = undefined;
  975. /** @type {Map<string, string | false>} */
  976. this.resolveResults = undefined;
  977. /** @type {Snapshot} */
  978. this.buildSnapshot = undefined;
  979. /** @type {Promise<Pack>} */
  980. this.packPromise = this._openPack();
  981. this.storePromise = Promise.resolve();
  982. }
  983. _getPack() {
  984. if (this.packPromise === undefined) {
  985. this.packPromise = this.storePromise.then(() => this._openPack());
  986. }
  987. return this.packPromise;
  988. }
  989. /**
  990. * @returns {Promise<Pack>} the pack
  991. */
  992. _openPack() {
  993. const { logger, profile, cacheLocation, version } = this;
  994. /** @type {Snapshot} */
  995. let buildSnapshot;
  996. /** @type {Set<string>} */
  997. let buildDependencies;
  998. /** @type {Set<string>} */
  999. let newBuildDependencies;
  1000. /** @type {Snapshot} */
  1001. let resolveBuildDependenciesSnapshot;
  1002. /** @type {Map<string, string | false>} */
  1003. let resolveResults;
  1004. logger.time("restore cache container");
  1005. return this.fileSerializer
  1006. .deserialize(null, {
  1007. filename: `${cacheLocation}/index${this._extension}`,
  1008. extension: `${this._extension}`,
  1009. logger,
  1010. profile,
  1011. retainedBuffer: this.allowCollectingMemory
  1012. ? allowCollectingMemory
  1013. : undefined
  1014. })
  1015. .catch(err => {
  1016. if (err.code !== "ENOENT") {
  1017. logger.warn(
  1018. `Restoring pack failed from ${cacheLocation}${this._extension}: ${err}`
  1019. );
  1020. logger.debug(err.stack);
  1021. } else {
  1022. logger.debug(
  1023. `No pack exists at ${cacheLocation}${this._extension}: ${err}`
  1024. );
  1025. }
  1026. return undefined;
  1027. })
  1028. .then(packContainer => {
  1029. logger.timeEnd("restore cache container");
  1030. if (!packContainer) return undefined;
  1031. if (!(packContainer instanceof PackContainer)) {
  1032. logger.warn(
  1033. `Restored pack from ${cacheLocation}${this._extension}, but contained content is unexpected.`,
  1034. packContainer
  1035. );
  1036. return undefined;
  1037. }
  1038. if (packContainer.version !== version) {
  1039. logger.log(
  1040. `Restored pack from ${cacheLocation}${this._extension}, but version doesn't match.`
  1041. );
  1042. return undefined;
  1043. }
  1044. logger.time("check build dependencies");
  1045. return Promise.all([
  1046. new Promise((resolve, reject) => {
  1047. this.fileSystemInfo.checkSnapshotValid(
  1048. packContainer.buildSnapshot,
  1049. (err, valid) => {
  1050. if (err) {
  1051. logger.log(
  1052. `Restored pack from ${cacheLocation}${this._extension}, but checking snapshot of build dependencies errored: ${err}.`
  1053. );
  1054. logger.debug(err.stack);
  1055. return resolve(false);
  1056. }
  1057. if (!valid) {
  1058. logger.log(
  1059. `Restored pack from ${cacheLocation}${this._extension}, but build dependencies have changed.`
  1060. );
  1061. return resolve(false);
  1062. }
  1063. buildSnapshot = packContainer.buildSnapshot;
  1064. return resolve(true);
  1065. }
  1066. );
  1067. }),
  1068. new Promise((resolve, reject) => {
  1069. this.fileSystemInfo.checkSnapshotValid(
  1070. packContainer.resolveBuildDependenciesSnapshot,
  1071. (err, valid) => {
  1072. if (err) {
  1073. logger.log(
  1074. `Restored pack from ${cacheLocation}${this._extension}, but checking snapshot of resolving of build dependencies errored: ${err}.`
  1075. );
  1076. logger.debug(err.stack);
  1077. return resolve(false);
  1078. }
  1079. if (valid) {
  1080. resolveBuildDependenciesSnapshot =
  1081. packContainer.resolveBuildDependenciesSnapshot;
  1082. buildDependencies = packContainer.buildDependencies;
  1083. resolveResults = packContainer.resolveResults;
  1084. return resolve(true);
  1085. }
  1086. logger.log(
  1087. "resolving of build dependencies is invalid, will re-resolve build dependencies"
  1088. );
  1089. this.fileSystemInfo.checkResolveResultsValid(
  1090. packContainer.resolveResults,
  1091. (err, valid) => {
  1092. if (err) {
  1093. logger.log(
  1094. `Restored pack from ${cacheLocation}${this._extension}, but resolving of build dependencies errored: ${err}.`
  1095. );
  1096. logger.debug(err.stack);
  1097. return resolve(false);
  1098. }
  1099. if (valid) {
  1100. newBuildDependencies = packContainer.buildDependencies;
  1101. resolveResults = packContainer.resolveResults;
  1102. return resolve(true);
  1103. }
  1104. logger.log(
  1105. `Restored pack from ${cacheLocation}${this._extension}, but build dependencies resolve to different locations.`
  1106. );
  1107. return resolve(false);
  1108. }
  1109. );
  1110. }
  1111. );
  1112. })
  1113. ])
  1114. .catch(err => {
  1115. logger.timeEnd("check build dependencies");
  1116. throw err;
  1117. })
  1118. .then(([buildSnapshotValid, resolveValid]) => {
  1119. logger.timeEnd("check build dependencies");
  1120. if (buildSnapshotValid && resolveValid) {
  1121. logger.time("restore cache content metadata");
  1122. const d = packContainer.data();
  1123. logger.timeEnd("restore cache content metadata");
  1124. return d;
  1125. }
  1126. return undefined;
  1127. });
  1128. })
  1129. .then(pack => {
  1130. if (pack) {
  1131. pack.maxAge = this.maxAge;
  1132. this.buildSnapshot = buildSnapshot;
  1133. if (buildDependencies) this.buildDependencies = buildDependencies;
  1134. if (newBuildDependencies)
  1135. this.newBuildDependencies.addAll(newBuildDependencies);
  1136. this.resolveResults = resolveResults;
  1137. this.resolveBuildDependenciesSnapshot =
  1138. resolveBuildDependenciesSnapshot;
  1139. return pack;
  1140. }
  1141. return new Pack(logger, this.maxAge);
  1142. })
  1143. .catch(err => {
  1144. this.logger.warn(
  1145. `Restoring pack from ${cacheLocation}${this._extension} failed: ${err}`
  1146. );
  1147. this.logger.debug(err.stack);
  1148. return new Pack(logger, this.maxAge);
  1149. });
  1150. }
  1151. /**
  1152. * @param {string} identifier unique name for the resource
  1153. * @param {Etag | null} etag etag of the resource
  1154. * @param {any} data cached content
  1155. * @returns {Promise<void>} promise
  1156. */
  1157. store(identifier, etag, data) {
  1158. return this._getPack().then(pack => {
  1159. pack.set(identifier, etag === null ? null : etag.toString(), data);
  1160. });
  1161. }
  1162. /**
  1163. * @param {string} identifier unique name for the resource
  1164. * @param {Etag | null} etag etag of the resource
  1165. * @returns {Promise<any>} promise to the cached content
  1166. */
  1167. restore(identifier, etag) {
  1168. return this._getPack()
  1169. .then(pack =>
  1170. pack.get(identifier, etag === null ? null : etag.toString())
  1171. )
  1172. .catch(err => {
  1173. if (err && err.code !== "ENOENT") {
  1174. this.logger.warn(
  1175. `Restoring failed for ${identifier} from pack: ${err}`
  1176. );
  1177. this.logger.debug(err.stack);
  1178. }
  1179. });
  1180. }
  1181. storeBuildDependencies(dependencies) {
  1182. this.newBuildDependencies.addAll(dependencies);
  1183. }
  1184. afterAllStored() {
  1185. const packPromise = this.packPromise;
  1186. if (packPromise === undefined) return Promise.resolve();
  1187. const reportProgress = ProgressPlugin.getReporter(this.compiler);
  1188. return (this.storePromise = packPromise
  1189. .then(pack => {
  1190. pack.stopCapturingRequests();
  1191. if (!pack.invalid) return;
  1192. this.packPromise = undefined;
  1193. this.logger.log(`Storing pack...`);
  1194. let promise;
  1195. const newBuildDependencies = new Set();
  1196. for (const dep of this.newBuildDependencies) {
  1197. if (!this.buildDependencies.has(dep)) {
  1198. newBuildDependencies.add(dep);
  1199. }
  1200. }
  1201. if (newBuildDependencies.size > 0 || !this.buildSnapshot) {
  1202. if (reportProgress) reportProgress(0.5, "resolve build dependencies");
  1203. this.logger.debug(
  1204. `Capturing build dependencies... (${Array.from(
  1205. newBuildDependencies
  1206. ).join(", ")})`
  1207. );
  1208. promise = new Promise((resolve, reject) => {
  1209. this.logger.time("resolve build dependencies");
  1210. this.fileSystemInfo.resolveBuildDependencies(
  1211. this.context,
  1212. newBuildDependencies,
  1213. (err, result) => {
  1214. this.logger.timeEnd("resolve build dependencies");
  1215. if (err) return reject(err);
  1216. this.logger.time("snapshot build dependencies");
  1217. const {
  1218. files,
  1219. directories,
  1220. missing,
  1221. resolveResults,
  1222. resolveDependencies
  1223. } = result;
  1224. if (this.resolveResults) {
  1225. for (const [key, value] of resolveResults) {
  1226. this.resolveResults.set(key, value);
  1227. }
  1228. } else {
  1229. this.resolveResults = resolveResults;
  1230. }
  1231. if (reportProgress) {
  1232. reportProgress(
  1233. 0.6,
  1234. "snapshot build dependencies",
  1235. "resolving"
  1236. );
  1237. }
  1238. this.fileSystemInfo.createSnapshot(
  1239. undefined,
  1240. resolveDependencies.files,
  1241. resolveDependencies.directories,
  1242. resolveDependencies.missing,
  1243. this.snapshot.resolveBuildDependencies,
  1244. (err, snapshot) => {
  1245. if (err) {
  1246. this.logger.timeEnd("snapshot build dependencies");
  1247. return reject(err);
  1248. }
  1249. if (!snapshot) {
  1250. this.logger.timeEnd("snapshot build dependencies");
  1251. return reject(
  1252. new Error("Unable to snapshot resolve dependencies")
  1253. );
  1254. }
  1255. if (this.resolveBuildDependenciesSnapshot) {
  1256. this.resolveBuildDependenciesSnapshot =
  1257. this.fileSystemInfo.mergeSnapshots(
  1258. this.resolveBuildDependenciesSnapshot,
  1259. snapshot
  1260. );
  1261. } else {
  1262. this.resolveBuildDependenciesSnapshot = snapshot;
  1263. }
  1264. if (reportProgress) {
  1265. reportProgress(
  1266. 0.7,
  1267. "snapshot build dependencies",
  1268. "modules"
  1269. );
  1270. }
  1271. this.fileSystemInfo.createSnapshot(
  1272. undefined,
  1273. files,
  1274. directories,
  1275. missing,
  1276. this.snapshot.buildDependencies,
  1277. (err, snapshot) => {
  1278. this.logger.timeEnd("snapshot build dependencies");
  1279. if (err) return reject(err);
  1280. if (!snapshot) {
  1281. return reject(
  1282. new Error("Unable to snapshot build dependencies")
  1283. );
  1284. }
  1285. this.logger.debug("Captured build dependencies");
  1286. if (this.buildSnapshot) {
  1287. this.buildSnapshot =
  1288. this.fileSystemInfo.mergeSnapshots(
  1289. this.buildSnapshot,
  1290. snapshot
  1291. );
  1292. } else {
  1293. this.buildSnapshot = snapshot;
  1294. }
  1295. resolve();
  1296. }
  1297. );
  1298. }
  1299. );
  1300. }
  1301. );
  1302. });
  1303. } else {
  1304. promise = Promise.resolve();
  1305. }
  1306. return promise.then(() => {
  1307. if (reportProgress) reportProgress(0.8, "serialize pack");
  1308. this.logger.time(`store pack`);
  1309. const updatedBuildDependencies = new Set(this.buildDependencies);
  1310. for (const dep of newBuildDependencies) {
  1311. updatedBuildDependencies.add(dep);
  1312. }
  1313. const content = new PackContainer(
  1314. pack,
  1315. this.version,
  1316. this.buildSnapshot,
  1317. updatedBuildDependencies,
  1318. this.resolveResults,
  1319. this.resolveBuildDependenciesSnapshot
  1320. );
  1321. return this.fileSerializer
  1322. .serialize(content, {
  1323. filename: `${this.cacheLocation}/index${this._extension}`,
  1324. extension: `${this._extension}`,
  1325. logger: this.logger,
  1326. profile: this.profile
  1327. })
  1328. .then(() => {
  1329. for (const dep of newBuildDependencies) {
  1330. this.buildDependencies.add(dep);
  1331. }
  1332. this.newBuildDependencies.clear();
  1333. this.logger.timeEnd(`store pack`);
  1334. const stats = pack.getContentStats();
  1335. this.logger.log(
  1336. "Stored pack (%d items, %d files, %d MiB)",
  1337. pack.itemInfo.size,
  1338. stats.count,
  1339. Math.round(stats.size / 1024 / 1024)
  1340. );
  1341. })
  1342. .catch(err => {
  1343. this.logger.timeEnd(`store pack`);
  1344. this.logger.warn(`Caching failed for pack: ${err}`);
  1345. this.logger.debug(err.stack);
  1346. });
  1347. });
  1348. })
  1349. .catch(err => {
  1350. this.logger.warn(`Caching failed for pack: ${err}`);
  1351. this.logger.debug(err.stack);
  1352. }));
  1353. }
  1354. clear() {
  1355. this.fileSystemInfo.clear();
  1356. this.buildDependencies.clear();
  1357. this.newBuildDependencies.clear();
  1358. this.resolveBuildDependenciesSnapshot = undefined;
  1359. this.resolveResults = undefined;
  1360. this.buildSnapshot = undefined;
  1361. this.packPromise = undefined;
  1362. }
  1363. }
  1364. module.exports = PackFileCacheStrategy;