PackFileCacheStrategy.js 44 KB

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