PackFileCacheStrategy.js 44 KB

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