PackFileCacheStrategy.js 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897
  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 { getReferencedFilenames } = require("../serialization/FileMiddleware");
  9. const SerializerMiddleware = require("../serialization/SerializerMiddleware");
  10. const LazySet = require("../util/LazySet");
  11. const formatSize = require("../util/formatSize");
  12. const makeSerializable = require("../util/makeSerializable");
  13. const memoize = require("../util/memoize");
  14. const {
  15. NOT_SERIALIZABLE,
  16. createFileSerializer
  17. } = require("../util/serialization");
  18. /** @import { SnapshotOptions } from "../../declarations/WebpackOptions" */
  19. /** @import { FileSystemDependencies } from "../Compilation" */
  20. /** @import { Data, Etag } from "../Cache" */
  21. /** @import Compiler from "../Compiler" */
  22. /**
  23. * @import {
  24. * ResolveBuildDependenciesResult,
  25. * ResolveResults,
  26. * Snapshot
  27. * } from "../FileSystemInfo"
  28. */
  29. /** @import { Logger } from "../logging/Logger" */
  30. /**
  31. * @import {
  32. * ObjectDeserializerContext,
  33. * ObjectSerializerContext
  34. * } from "../serialization/ObjectMiddleware"
  35. */
  36. /** @import { HashFunction } from "../util/Hash" */
  37. /** @import { IntermediateFileSystem } from "../util/fs" */
  38. /** @typedef {Set<string>} Items */
  39. /** @typedef {Set<string>} BuildDependencies */
  40. /** @typedef {Map<string, PackItemInfo>} ItemInfo */
  41. /** @typedef {{ firstSeen: number, size: number }} UnreferencedFile */
  42. /** @typedef {Map<string, UnreferencedFile>} UnreferencedFiles */
  43. // Unreferenced files are kept for this long to not race concurrent builds sharing the cache directory.
  44. const CLEANUP_GRACE_PERIOD = 30 * 60 * 1000;
  45. // Records when each unreferenced file was first seen. Aging by recorded time keeps
  46. // orphans expiring across caches restored with refreshed modification times.
  47. const UNREFERENCED_FILE = "unreferenced.json";
  48. // A file written this recently may belong to a concurrent build that reused the name,
  49. // in which case the recorded time describes the previous file and must not be trusted.
  50. const CLEANUP_RECENT_WRITE_PERIOD = 60 * 1000;
  51. class PackContainer {
  52. /**
  53. * Creates an instance of PackContainer.
  54. * @param {Pack} data stored data
  55. * @param {string} version version identifier
  56. * @param {InstanceType<Snapshot>} buildSnapshot snapshot of all build dependencies
  57. * @param {BuildDependencies} buildDependencies list of all unresolved build dependencies captured
  58. * @param {ResolveResults} resolveResults result of the resolved build dependencies
  59. * @param {InstanceType<Snapshot>} resolveBuildDependenciesSnapshot snapshot of the dependencies of the build dependencies resolving
  60. */
  61. constructor(
  62. data,
  63. version,
  64. buildSnapshot,
  65. buildDependencies,
  66. resolveResults,
  67. resolveBuildDependenciesSnapshot
  68. ) {
  69. /** @type {Pack | (() => Pack)} */
  70. this.data = data;
  71. /** @type {string} */
  72. this.version = version;
  73. /** @type {InstanceType<Snapshot>} */
  74. this.buildSnapshot = buildSnapshot;
  75. /** @type {BuildDependencies} */
  76. this.buildDependencies = buildDependencies;
  77. /** @type {ResolveResults} */
  78. this.resolveResults = resolveResults;
  79. /** @type {InstanceType<Snapshot>} */
  80. this.resolveBuildDependenciesSnapshot = resolveBuildDependenciesSnapshot;
  81. }
  82. /**
  83. * Serializes this instance into the provided serializer context.
  84. * @param {ObjectSerializerContext} context context
  85. */
  86. serialize({ write, writeLazy }) {
  87. write(this.version);
  88. write(this.buildSnapshot);
  89. write(this.buildDependencies);
  90. write(this.resolveResults);
  91. write(this.resolveBuildDependenciesSnapshot);
  92. /** @type {NonNullable<ObjectSerializerContext["writeLazy"]>} */
  93. (writeLazy)(this.data);
  94. }
  95. /**
  96. * Restores this instance from the provided deserializer context.
  97. * @param {ObjectDeserializerContext} context context
  98. */
  99. deserialize({ read }) {
  100. this.version = read();
  101. this.buildSnapshot = read();
  102. this.buildDependencies = read();
  103. this.resolveResults = read();
  104. this.resolveBuildDependenciesSnapshot = read();
  105. this.data = read();
  106. }
  107. }
  108. makeSerializable(
  109. PackContainer,
  110. "webpack/lib/cache/PackFileCacheStrategy",
  111. "PackContainer"
  112. );
  113. const MIN_CONTENT_SIZE = 1024 * 1024; // 1 MB
  114. const CONTENT_COUNT_TO_MERGE = 10;
  115. const MIN_ITEMS_IN_FRESH_PACK = 100;
  116. const MAX_ITEMS_IN_FRESH_PACK = 50000;
  117. const MAX_TIME_IN_FRESH_PACK = 60 * 1000; // 1 min
  118. class PackItemInfo {
  119. /**
  120. * Creates an instance of PackItemInfo.
  121. * @param {string} identifier identifier of item
  122. * @param {string | null | undefined} etag etag of item
  123. * @param {Data} value fresh value of item
  124. */
  125. constructor(identifier, etag, value) {
  126. /** @type {string} */
  127. this.identifier = identifier;
  128. /** @type {string | null | undefined} */
  129. this.etag = etag;
  130. /** @type {number} */
  131. this.location = -1;
  132. /** @type {number} */
  133. this.lastAccess = Date.now();
  134. /** @type {Data} */
  135. this.freshValue = value;
  136. }
  137. }
  138. class Pack {
  139. /**
  140. * Creates an instance of Pack.
  141. * @param {Logger} logger a logger
  142. * @param {number} maxAge max age of cache items
  143. */
  144. constructor(logger, maxAge) {
  145. /** @type {ItemInfo} */
  146. this.itemInfo = new Map();
  147. /** @type {(string | undefined)[]} */
  148. this.requests = [];
  149. /** @type {undefined | NodeJS.Timeout} */
  150. this.requestsTimeout = undefined;
  151. /** @type {ItemInfo} */
  152. this.freshContent = new Map();
  153. /** @type {(undefined | PackContent)[]} */
  154. this.content = [];
  155. /** @type {boolean} */
  156. this.invalid = false;
  157. /** @type {Logger} */
  158. this.logger = logger;
  159. /** @type {number} */
  160. this.maxAge = maxAge;
  161. }
  162. /**
  163. * Adds the provided identifier to the pack.
  164. * @param {string} identifier identifier
  165. */
  166. _addRequest(identifier) {
  167. this.requests.push(identifier);
  168. if (this.requestsTimeout === undefined) {
  169. this.requestsTimeout = setTimeout(() => {
  170. this.requests.push(undefined);
  171. this.requestsTimeout = undefined;
  172. }, MAX_TIME_IN_FRESH_PACK);
  173. if (this.requestsTimeout.unref) this.requestsTimeout.unref();
  174. }
  175. }
  176. stopCapturingRequests() {
  177. if (this.requestsTimeout !== undefined) {
  178. clearTimeout(this.requestsTimeout);
  179. this.requestsTimeout = undefined;
  180. }
  181. }
  182. /**
  183. * Returns cached content.
  184. * @param {string} identifier unique name for the resource
  185. * @param {string | null} etag etag of the resource
  186. * @returns {Data} cached content
  187. */
  188. get(identifier, etag) {
  189. const info = this.itemInfo.get(identifier);
  190. this._addRequest(identifier);
  191. if (info === undefined) {
  192. return;
  193. }
  194. if (info.etag !== etag) return null;
  195. info.lastAccess = Date.now();
  196. const loc = info.location;
  197. if (loc === -1) {
  198. return info.freshValue;
  199. }
  200. if (!this.content[loc]) {
  201. return;
  202. }
  203. return /** @type {PackContent} */ (this.content[loc]).get(identifier);
  204. }
  205. /**
  206. * Updates value using the provided identifier.
  207. * @param {string} identifier unique name for the resource
  208. * @param {string | null} etag etag of the resource
  209. * @param {Data} data cached content
  210. * @returns {void}
  211. */
  212. set(identifier, etag, data) {
  213. if (!this.invalid) {
  214. this.invalid = true;
  215. this.logger.log(`Pack got invalid because of write to: ${identifier}`);
  216. }
  217. const info = this.itemInfo.get(identifier);
  218. if (info === undefined) {
  219. const newInfo = new PackItemInfo(identifier, etag, data);
  220. this.itemInfo.set(identifier, newInfo);
  221. this._addRequest(identifier);
  222. this.freshContent.set(identifier, newInfo);
  223. } else {
  224. const loc = info.location;
  225. if (loc >= 0) {
  226. this._addRequest(identifier);
  227. this.freshContent.set(identifier, info);
  228. const content = /** @type {PackContent} */ (this.content[loc]);
  229. content.delete(identifier);
  230. if (content.items.size === 0) {
  231. this.content[loc] = undefined;
  232. this.logger.debug("Pack %d got empty and is removed", loc);
  233. }
  234. }
  235. info.freshValue = data;
  236. info.lastAccess = Date.now();
  237. info.etag = etag;
  238. info.location = -1;
  239. }
  240. }
  241. getContentStats() {
  242. let count = 0;
  243. let size = 0;
  244. for (const content of this.content) {
  245. if (content !== undefined) {
  246. count++;
  247. const s = content.getSize();
  248. if (s > 0) {
  249. size += s;
  250. }
  251. }
  252. }
  253. return { count, size };
  254. }
  255. /**
  256. * Returns new location of data entries.
  257. * @returns {number} new location of data entries
  258. */
  259. _findLocation() {
  260. /** @type {number} */
  261. let i;
  262. for (i = 0; i < this.content.length && this.content[i] !== undefined; i++);
  263. return i;
  264. }
  265. /**
  266. * Gc and update location.
  267. * @private
  268. * @param {Items} items items
  269. * @param {Items} usedItems used items
  270. * @param {number} newLoc new location
  271. */
  272. _gcAndUpdateLocation(items, usedItems, newLoc) {
  273. let count = 0;
  274. /** @type {undefined | string} */
  275. let lastGC;
  276. const now = Date.now();
  277. for (const identifier of items) {
  278. const info = /** @type {PackItemInfo} */ (this.itemInfo.get(identifier));
  279. if (now - info.lastAccess > this.maxAge) {
  280. this.itemInfo.delete(identifier);
  281. items.delete(identifier);
  282. usedItems.delete(identifier);
  283. count++;
  284. lastGC = identifier;
  285. } else {
  286. info.location = newLoc;
  287. }
  288. }
  289. if (count > 0) {
  290. this.logger.log(
  291. "Garbage Collected %d old items at pack %d (%d items remaining) e. g. %s",
  292. count,
  293. newLoc,
  294. items.size,
  295. lastGC
  296. );
  297. }
  298. }
  299. _persistFreshContent() {
  300. /** @typedef {{ items: Items, map: Content, loc: number }} PackItem */
  301. const itemsCount = this.freshContent.size;
  302. if (itemsCount > 0) {
  303. const packCount = Math.ceil(itemsCount / MAX_ITEMS_IN_FRESH_PACK);
  304. const itemsPerPack = Math.ceil(itemsCount / packCount);
  305. /** @type {PackItem[]} */
  306. const packs = [];
  307. let i = 0;
  308. let ignoreNextTimeTick = false;
  309. const createNextPack = () => {
  310. const loc = this._findLocation();
  311. this.content[loc] = /** @type {EXPECTED_ANY} */ (null); // reserve
  312. /** @type {PackItem} */
  313. const pack = {
  314. items: new Set(),
  315. map: new Map(),
  316. loc
  317. };
  318. packs.push(pack);
  319. return pack;
  320. };
  321. let pack = createNextPack();
  322. if (this.requestsTimeout !== undefined) {
  323. clearTimeout(this.requestsTimeout);
  324. }
  325. for (const identifier of this.requests) {
  326. if (identifier === undefined) {
  327. if (ignoreNextTimeTick) {
  328. ignoreNextTimeTick = false;
  329. } else if (pack.items.size >= MIN_ITEMS_IN_FRESH_PACK) {
  330. i = 0;
  331. pack = createNextPack();
  332. }
  333. continue;
  334. }
  335. const info = this.freshContent.get(identifier);
  336. if (info === undefined) continue;
  337. pack.items.add(identifier);
  338. pack.map.set(identifier, info.freshValue);
  339. info.location = pack.loc;
  340. info.freshValue = undefined;
  341. this.freshContent.delete(identifier);
  342. if (++i > itemsPerPack) {
  343. i = 0;
  344. pack = createNextPack();
  345. ignoreNextTimeTick = true;
  346. }
  347. }
  348. this.requests.length = 0;
  349. for (const pack of packs) {
  350. this.content[pack.loc] = new PackContent(
  351. pack.items,
  352. new Set(pack.items),
  353. new PackContentItems(pack.map)
  354. );
  355. }
  356. this.logger.log(
  357. `${itemsCount} fresh items in cache put into pack ${
  358. packs.length > 1
  359. ? packs
  360. .map((pack) => `${pack.loc} (${pack.items.size} items)`)
  361. .join(", ")
  362. : packs[0].loc
  363. }`
  364. );
  365. }
  366. }
  367. /**
  368. * Merges small content files to a single content file
  369. */
  370. _optimizeSmallContent() {
  371. // 1. Find all small content files
  372. // Treat unused content files separately to avoid
  373. // a merge-split cycle
  374. /** @type {number[]} */
  375. const smallUsedContents = [];
  376. /** @type {number} */
  377. let smallUsedContentSize = 0;
  378. /** @type {number[]} */
  379. const smallUnusedContents = [];
  380. /** @type {number} */
  381. let smallUnusedContentSize = 0;
  382. for (let i = 0; i < this.content.length; i++) {
  383. const content = this.content[i];
  384. if (content === undefined) continue;
  385. if (content.outdated) continue;
  386. const size = content.getSize();
  387. if (size < 0 || size > MIN_CONTENT_SIZE) continue;
  388. if (content.used.size > 0) {
  389. smallUsedContents.push(i);
  390. smallUsedContentSize += size;
  391. } else {
  392. smallUnusedContents.push(i);
  393. smallUnusedContentSize += size;
  394. }
  395. }
  396. // 2. Check if minimum number is reached
  397. /** @type {number[]} */
  398. let mergedIndices;
  399. if (
  400. smallUsedContents.length >= CONTENT_COUNT_TO_MERGE ||
  401. smallUsedContentSize > MIN_CONTENT_SIZE
  402. ) {
  403. mergedIndices = smallUsedContents;
  404. } else if (
  405. smallUnusedContents.length >= CONTENT_COUNT_TO_MERGE ||
  406. smallUnusedContentSize > MIN_CONTENT_SIZE
  407. ) {
  408. mergedIndices = smallUnusedContents;
  409. } else {
  410. return;
  411. }
  412. /** @type {PackContent[]} */
  413. const mergedContent = [];
  414. // 3. Remove old content entries
  415. for (const i of mergedIndices) {
  416. mergedContent.push(/** @type {PackContent} */ (this.content[i]));
  417. this.content[i] = undefined;
  418. }
  419. // 4. Determine merged items
  420. /** @type {Items} */
  421. const mergedItems = new Set();
  422. /** @type {Items} */
  423. const mergedUsedItems = new Set();
  424. /** @type {((map: Content) => Promise<void>)[]} */
  425. const addToMergedMap = [];
  426. for (const content of mergedContent) {
  427. for (const identifier of content.items) {
  428. mergedItems.add(identifier);
  429. }
  430. for (const identifier of content.used) {
  431. mergedUsedItems.add(identifier);
  432. }
  433. addToMergedMap.push(async (map) => {
  434. // unpack existing content
  435. // after that values are accessible in .content
  436. await content.unpack(
  437. "it should be merged with other small pack contents"
  438. );
  439. for (const [identifier, value] of /** @type {Content} */ (
  440. content.content
  441. )) {
  442. map.set(identifier, value);
  443. }
  444. });
  445. }
  446. // 5. GC and update location of merged items
  447. const newLoc = this._findLocation();
  448. this._gcAndUpdateLocation(mergedItems, mergedUsedItems, newLoc);
  449. // 6. If not empty, store content somewhere
  450. if (mergedItems.size > 0) {
  451. this.content[newLoc] = new PackContent(
  452. mergedItems,
  453. mergedUsedItems,
  454. memoize(async () => {
  455. /** @type {Content} */
  456. const map = new Map();
  457. await Promise.all(addToMergedMap.map((fn) => fn(map)));
  458. return new PackContentItems(map);
  459. })
  460. );
  461. this.logger.log(
  462. "Merged %d small files with %d cache items into pack %d",
  463. mergedContent.length,
  464. mergedItems.size,
  465. newLoc
  466. );
  467. }
  468. }
  469. /**
  470. * Split large content files with used and unused items
  471. * into two parts to separate used from unused items
  472. */
  473. _optimizeUnusedContent() {
  474. // 1. Find a large content file with used and unused items
  475. for (let i = 0; i < this.content.length; i++) {
  476. const content = this.content[i];
  477. if (content === undefined) continue;
  478. const size = content.getSize();
  479. if (size < MIN_CONTENT_SIZE) continue;
  480. const used = content.used.size;
  481. const total = content.items.size;
  482. if (used > 0 && used < total) {
  483. // 2. Remove this content
  484. this.content[i] = undefined;
  485. // 3. Determine items for the used content file
  486. const usedItems = new Set(content.used);
  487. const newLoc = this._findLocation();
  488. this._gcAndUpdateLocation(usedItems, usedItems, newLoc);
  489. // 4. Create content file for used items
  490. if (usedItems.size > 0) {
  491. this.content[newLoc] = new PackContent(
  492. usedItems,
  493. new Set(usedItems),
  494. async () => {
  495. await content.unpack(
  496. "it should be splitted into used and unused items"
  497. );
  498. /** @type {Content} */
  499. const map = new Map();
  500. for (const identifier of usedItems) {
  501. map.set(
  502. identifier,
  503. /** @type {Content} */
  504. (content.content).get(identifier)
  505. );
  506. }
  507. return new PackContentItems(map);
  508. }
  509. );
  510. }
  511. // 5. Determine items for the unused content file
  512. const unusedItems = new Set(content.items);
  513. /** @type {Items} */
  514. const usedOfUnusedItems = new Set();
  515. for (const identifier of usedItems) {
  516. unusedItems.delete(identifier);
  517. }
  518. const newUnusedLoc = this._findLocation();
  519. this._gcAndUpdateLocation(unusedItems, usedOfUnusedItems, newUnusedLoc);
  520. // 6. Create content file for unused items
  521. if (unusedItems.size > 0) {
  522. this.content[newUnusedLoc] = new PackContent(
  523. unusedItems,
  524. usedOfUnusedItems,
  525. async () => {
  526. await content.unpack(
  527. "it should be splitted into used and unused items"
  528. );
  529. /** @type {Content} */
  530. const map = new Map();
  531. for (const identifier of unusedItems) {
  532. map.set(
  533. identifier,
  534. /** @type {Content} */
  535. (content.content).get(identifier)
  536. );
  537. }
  538. return new PackContentItems(map);
  539. }
  540. );
  541. }
  542. this.logger.log(
  543. "Split pack %d into pack %d with %d used items and pack %d with %d unused items",
  544. i,
  545. newLoc,
  546. usedItems.size,
  547. newUnusedLoc,
  548. unusedItems.size
  549. );
  550. // optimizing only one of them is good enough and
  551. // reduces the amount of serialization needed
  552. return;
  553. }
  554. }
  555. }
  556. /**
  557. * Drops every content whose items all expired. Unlike a partial collection this
  558. * never unpacks, so it is not limited to a single content per store and lets a
  559. * long unused cache shrink in one go instead of one pack per build.
  560. */
  561. _gcExpiredContent() {
  562. const now = Date.now();
  563. let packCount = 0;
  564. let itemCount = 0;
  565. for (let loc = 0; loc < this.content.length; loc++) {
  566. const content = this.content[loc];
  567. if (!content) continue;
  568. let expired = true;
  569. for (const identifier of content.items) {
  570. const info = this.itemInfo.get(identifier);
  571. if (info !== undefined && now - info.lastAccess <= this.maxAge) {
  572. expired = false;
  573. break;
  574. }
  575. }
  576. if (!expired) continue;
  577. for (const identifier of content.items) this.itemInfo.delete(identifier);
  578. this.content[loc] = undefined;
  579. packCount++;
  580. itemCount += content.items.size;
  581. }
  582. if (packCount > 0) {
  583. this.logger.log(
  584. "Garbage Collected %d completely expired packs with %d items",
  585. packCount,
  586. itemCount
  587. );
  588. }
  589. }
  590. /**
  591. * Find the content with the oldest item and run GC on that.
  592. * Only runs for one content to avoid large invalidation.
  593. */
  594. _gcOldestContent() {
  595. /** @type {PackItemInfo | undefined} */
  596. let oldest;
  597. for (const info of this.itemInfo.values()) {
  598. if (oldest === undefined || info.lastAccess < oldest.lastAccess) {
  599. oldest = info;
  600. }
  601. }
  602. // collecting expired content may have left no items at all
  603. if (oldest === undefined) return;
  604. if (Date.now() - oldest.lastAccess > this.maxAge) {
  605. const loc = oldest.location;
  606. if (loc < 0) return;
  607. const content = /** @type {PackContent} */ (this.content[loc]);
  608. const items = new Set(content.items);
  609. const usedItems = new Set(content.used);
  610. this._gcAndUpdateLocation(items, usedItems, loc);
  611. this.content[loc] =
  612. items.size > 0
  613. ? new PackContent(items, usedItems, async () => {
  614. await content.unpack(
  615. "it contains old items that should be garbage collected"
  616. );
  617. /** @type {Content} */
  618. const map = new Map();
  619. for (const identifier of items) {
  620. map.set(
  621. identifier,
  622. /** @type {Content} */
  623. (content.content).get(identifier)
  624. );
  625. }
  626. return new PackContentItems(map);
  627. })
  628. : undefined;
  629. }
  630. }
  631. /**
  632. * Serializes this instance into the provided serializer context.
  633. * @param {ObjectSerializerContext} context context
  634. */
  635. serialize({ write, writeSeparate }) {
  636. this._persistFreshContent();
  637. this._optimizeSmallContent();
  638. this._optimizeUnusedContent();
  639. this._gcExpiredContent();
  640. this._gcOldestContent();
  641. for (const identifier of this.itemInfo.keys()) {
  642. write(identifier);
  643. }
  644. write(null); // null as marker of the end of keys
  645. for (const info of this.itemInfo.values()) {
  646. write(info.etag);
  647. }
  648. for (const info of this.itemInfo.values()) {
  649. write(info.lastAccess);
  650. }
  651. for (let i = 0; i < this.content.length; i++) {
  652. const content = this.content[i];
  653. if (content !== undefined) {
  654. write(content.items);
  655. content.writeLazy((lazy) =>
  656. /** @type {NonNullable<ObjectSerializerContext["writeSeparate"]>} */
  657. (writeSeparate)(lazy, { name: `${i}` })
  658. );
  659. } else {
  660. write(undefined); // undefined marks an empty content slot
  661. }
  662. }
  663. write(null); // null as marker of the end of items
  664. }
  665. /**
  666. * Restores this instance from the provided deserializer context.
  667. * @param {ObjectDeserializerContext & { logger: Logger }} context context
  668. */
  669. deserialize({ read, logger }) {
  670. this.logger = logger;
  671. {
  672. const items = [];
  673. let item = read();
  674. while (item !== null) {
  675. items.push(item);
  676. item = read();
  677. }
  678. this.itemInfo.clear();
  679. const infoItems = items.map((identifier) => {
  680. const info = new PackItemInfo(identifier, undefined, undefined);
  681. this.itemInfo.set(identifier, info);
  682. return info;
  683. });
  684. for (const info of infoItems) {
  685. info.etag = read();
  686. }
  687. for (const info of infoItems) {
  688. info.lastAccess = read();
  689. }
  690. }
  691. this.content.length = 0;
  692. let items = read();
  693. while (items !== null) {
  694. if (items === undefined) {
  695. this.content.push(items);
  696. } else {
  697. const idx = this.content.length;
  698. const lazy = read();
  699. this.content.push(
  700. new PackContent(
  701. items,
  702. new Set(),
  703. lazy,
  704. logger,
  705. `${this.content.length}`
  706. )
  707. );
  708. for (const identifier of items) {
  709. /** @type {PackItemInfo} */
  710. (this.itemInfo.get(identifier)).location = idx;
  711. }
  712. }
  713. items = read();
  714. }
  715. }
  716. }
  717. makeSerializable(Pack, "webpack/lib/cache/PackFileCacheStrategy", "Pack");
  718. /** @typedef {Map<string, Data>} Content */
  719. class PackContentItems {
  720. /**
  721. * Creates an instance of PackContentItems.
  722. * @param {Content} map items
  723. */
  724. constructor(map) {
  725. /** @type {Content} */
  726. this.map = map;
  727. }
  728. /**
  729. * Serializes this instance into the provided serializer context.
  730. * @param {ObjectSerializerContext & { logger: Logger, profile: boolean | undefined }} context context
  731. */
  732. serialize({ write, snapshot, rollback, logger, profile }) {
  733. if (profile) {
  734. write(false);
  735. for (const [key, value] of this.map) {
  736. const s = snapshot();
  737. try {
  738. write(key);
  739. const start = process.hrtime();
  740. write(value);
  741. const durationHr = process.hrtime(start);
  742. const duration = durationHr[0] * 1000 + durationHr[1] / 1e6;
  743. if (duration > 1) {
  744. if (duration > 500) {
  745. logger.error(`Serialization of '${key}': ${duration} ms`);
  746. } else if (duration > 50) {
  747. logger.warn(`Serialization of '${key}': ${duration} ms`);
  748. } else if (duration > 10) {
  749. logger.info(`Serialization of '${key}': ${duration} ms`);
  750. } else if (duration > 5) {
  751. logger.log(`Serialization of '${key}': ${duration} ms`);
  752. } else {
  753. logger.debug(`Serialization of '${key}': ${duration} ms`);
  754. }
  755. }
  756. } catch (err) {
  757. rollback(s);
  758. if (err === NOT_SERIALIZABLE) continue;
  759. const msg = "Skipped not serializable cache item";
  760. const notSerializableErr = /** @type {Error} */ (err);
  761. if (notSerializableErr.message.includes("ModuleBuildError")) {
  762. logger.log(
  763. `${msg} (in build error): ${notSerializableErr.message}`
  764. );
  765. logger.debug(
  766. `${msg} '${key}' (in build error): ${notSerializableErr.stack}`
  767. );
  768. } else {
  769. logger.warn(`${msg}: ${notSerializableErr.message}`);
  770. logger.debug(`${msg} '${key}': ${notSerializableErr.stack}`);
  771. }
  772. }
  773. }
  774. write(null);
  775. return;
  776. }
  777. // Try to serialize all at once
  778. const s = snapshot();
  779. try {
  780. write(true);
  781. write(this.map);
  782. } catch (_err) {
  783. rollback(s);
  784. // Try to serialize each item on it's own
  785. write(false);
  786. for (const [key, value] of this.map) {
  787. const s = snapshot();
  788. try {
  789. write(key);
  790. write(value);
  791. } catch (err) {
  792. rollback(s);
  793. if (err === NOT_SERIALIZABLE) continue;
  794. const notSerializableErr = /** @type {Error} */ (err);
  795. logger.warn(
  796. `Skipped not serializable cache item '${key}': ${notSerializableErr.message}`
  797. );
  798. logger.debug(notSerializableErr.stack);
  799. }
  800. }
  801. write(null);
  802. }
  803. }
  804. /**
  805. * Restores this instance from the provided deserializer context.
  806. * @param {ObjectDeserializerContext & { logger: Logger, profile: boolean | undefined }} context context
  807. */
  808. deserialize({ read, logger, profile }) {
  809. if (read()) {
  810. this.map = read();
  811. } else if (profile) {
  812. /** @type {Content} */
  813. const map = new Map();
  814. let key = read();
  815. while (key !== null) {
  816. const start = process.hrtime();
  817. const value = read();
  818. const durationHr = process.hrtime(start);
  819. const duration = durationHr[0] * 1000 + durationHr[1] / 1e6;
  820. if (duration > 1) {
  821. if (duration > 100) {
  822. logger.error(`Deserialization of '${key}': ${duration} ms`);
  823. } else if (duration > 20) {
  824. logger.warn(`Deserialization of '${key}': ${duration} ms`);
  825. } else if (duration > 5) {
  826. logger.info(`Deserialization of '${key}': ${duration} ms`);
  827. } else if (duration > 2) {
  828. logger.log(`Deserialization of '${key}': ${duration} ms`);
  829. } else {
  830. logger.debug(`Deserialization of '${key}': ${duration} ms`);
  831. }
  832. }
  833. map.set(key, value);
  834. key = read();
  835. }
  836. this.map = map;
  837. } else {
  838. /** @type {Content} */
  839. const map = new Map();
  840. let key = read();
  841. while (key !== null) {
  842. map.set(key, read());
  843. key = read();
  844. }
  845. this.map = map;
  846. }
  847. }
  848. }
  849. makeSerializable(
  850. PackContentItems,
  851. "webpack/lib/cache/PackFileCacheStrategy",
  852. "PackContentItems"
  853. );
  854. /** @typedef {(() => Promise<PackContentItems> | PackContentItems) & Partial<{ options: { size?: number } }>} LazyFunction */
  855. class PackContent {
  856. /*
  857. This class can be in these states:
  858. | this.lazy | this.content | this.outdated | state
  859. A1 | undefined | Map | false | fresh content
  860. A2 | undefined | Map | true | (will not happen)
  861. B1 | lazy () => {} | undefined | false | not deserialized
  862. B2 | lazy () => {} | undefined | true | not deserialized, but some items has been removed
  863. C1 | lazy* () => {} | Map | false | deserialized
  864. C2 | lazy* () => {} | Map | true | deserialized, and some items has been removed
  865. this.used is a subset of this.items.
  866. this.items is a subset of this.content.keys() resp. this.lazy().map.keys()
  867. When this.outdated === false, this.items === this.content.keys() resp. this.lazy().map.keys()
  868. When this.outdated === true, this.items should be used to recreated this.lazy/this.content.
  869. When this.lazy and this.content is set, they contain the same data.
  870. this.get must only be called with a valid item from this.items.
  871. In state C this.lazy is unMemoized
  872. */
  873. /**
  874. * Creates an instance of PackContent.
  875. * @param {Items} items keys
  876. * @param {Items} usedItems used keys
  877. * @param {PackContentItems | (() => Promise<PackContentItems>)} dataOrFn sync or async content
  878. * @param {Logger=} logger logger for logging
  879. * @param {string=} lazyName name of dataOrFn for logging
  880. */
  881. constructor(items, usedItems, dataOrFn, logger, lazyName) {
  882. /** @type {Items} */
  883. this.items = items;
  884. /** @type {LazyFunction | undefined} */
  885. this.lazy = typeof dataOrFn === "function" ? dataOrFn : undefined;
  886. /** @type {Content | undefined} */
  887. this.content = typeof dataOrFn === "function" ? undefined : dataOrFn.map;
  888. /** @type {boolean} */
  889. this.outdated = false;
  890. /** @type {Items} */
  891. this.used = usedItems;
  892. /** @type {Logger | undefined} */
  893. this.logger = logger;
  894. /** @type {string | undefined} */
  895. this.lazyName = lazyName;
  896. }
  897. /**
  898. * Returns result.
  899. * @param {string} identifier identifier
  900. * @returns {string | Promise<string>} result
  901. */
  902. get(identifier) {
  903. this.used.add(identifier);
  904. if (this.content) {
  905. return this.content.get(identifier);
  906. }
  907. const logger = /** @type {Logger} */ (this.logger);
  908. // We are in state B
  909. const { lazyName } = this;
  910. /** @type {string | undefined} */
  911. let timeMessage;
  912. if (lazyName) {
  913. // only log once
  914. this.lazyName = undefined;
  915. timeMessage = `restore cache content ${lazyName} (${formatSize(
  916. this.getSize()
  917. )})`;
  918. logger.log(
  919. `starting to restore cache content ${lazyName} (${formatSize(
  920. this.getSize()
  921. )}) because of request to: ${identifier}`
  922. );
  923. logger.time(timeMessage);
  924. }
  925. const value = /** @type {LazyFunction} */ (this.lazy)();
  926. if ("then" in value) {
  927. return value.then((data) => {
  928. const map = data.map;
  929. if (timeMessage) {
  930. logger.timeEnd(timeMessage);
  931. }
  932. // Move to state C
  933. this.content = map;
  934. this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy);
  935. return map.get(identifier);
  936. });
  937. }
  938. const map = value.map;
  939. if (timeMessage) {
  940. logger.timeEnd(timeMessage);
  941. }
  942. // Move to state C
  943. this.content = map;
  944. this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy);
  945. return map.get(identifier);
  946. }
  947. /**
  948. * Returns maybe a promise if lazy.
  949. * @param {string} reason explanation why unpack is necessary
  950. * @returns {void | Promise<void>} maybe a promise if lazy
  951. */
  952. unpack(reason) {
  953. if (this.content) return;
  954. const logger = /** @type {Logger} */ (this.logger);
  955. // Move from state B to C
  956. if (this.lazy) {
  957. const { lazyName } = this;
  958. /** @type {string | undefined} */
  959. let timeMessage;
  960. if (lazyName) {
  961. // only log once
  962. this.lazyName = undefined;
  963. timeMessage = `unpack cache content ${lazyName} (${formatSize(
  964. this.getSize()
  965. )})`;
  966. logger.log(
  967. `starting to unpack cache content ${lazyName} (${formatSize(
  968. this.getSize()
  969. )}) because ${reason}`
  970. );
  971. logger.time(timeMessage);
  972. }
  973. const value =
  974. /** @type {PackContentItems | Promise<PackContentItems>} */
  975. (this.lazy());
  976. if ("then" in value) {
  977. return value.then((data) => {
  978. if (timeMessage) {
  979. logger.timeEnd(timeMessage);
  980. }
  981. this.content = data.map;
  982. });
  983. }
  984. if (timeMessage) {
  985. logger.timeEnd(timeMessage);
  986. }
  987. this.content = value.map;
  988. }
  989. }
  990. /**
  991. * Returns the estimated size for the requested source type.
  992. * @returns {number} size of the content or -1 if not known
  993. */
  994. getSize() {
  995. if (!this.lazy) return -1;
  996. const options =
  997. /** @type {{ options: { size?: number } }} */
  998. (this.lazy).options;
  999. if (!options) return -1;
  1000. const size = options.size;
  1001. if (typeof size !== "number") return -1;
  1002. return size;
  1003. }
  1004. /**
  1005. * Processes the provided identifier.
  1006. * @param {string} identifier identifier
  1007. */
  1008. delete(identifier) {
  1009. this.items.delete(identifier);
  1010. this.used.delete(identifier);
  1011. this.outdated = true;
  1012. }
  1013. /**
  1014. * Processes the provided write.
  1015. * @param {(lazy: LazyFunction) => (() => PackContentItems | Promise<PackContentItems>)} write write function
  1016. * @returns {void}
  1017. */
  1018. writeLazy(write) {
  1019. if (!this.outdated && this.lazy) {
  1020. // State B1 or C1
  1021. // this.lazy is still the valid deserialized version
  1022. write(this.lazy);
  1023. return;
  1024. }
  1025. if (!this.outdated && this.content) {
  1026. // State A1
  1027. const map = new Map(this.content);
  1028. // Move to state C1
  1029. this.lazy = SerializerMiddleware.unMemoizeLazy(
  1030. write(() => new PackContentItems(map))
  1031. );
  1032. return;
  1033. }
  1034. if (this.content) {
  1035. // State A2 or C2
  1036. /** @type {Content} */
  1037. const map = new Map();
  1038. for (const item of this.items) {
  1039. map.set(item, this.content.get(item));
  1040. }
  1041. // Move to state C1
  1042. this.outdated = false;
  1043. this.content = map;
  1044. this.lazy = SerializerMiddleware.unMemoizeLazy(
  1045. write(() => new PackContentItems(map))
  1046. );
  1047. return;
  1048. }
  1049. const logger = /** @type {Logger} */ (this.logger);
  1050. // State B2
  1051. const { lazyName } = this;
  1052. /** @type {string | undefined} */
  1053. let timeMessage;
  1054. if (lazyName) {
  1055. // only log once
  1056. this.lazyName = undefined;
  1057. timeMessage = `unpack cache content ${lazyName} (${formatSize(
  1058. this.getSize()
  1059. )})`;
  1060. logger.log(
  1061. `starting to unpack cache content ${lazyName} (${formatSize(
  1062. this.getSize()
  1063. )}) because it's outdated and need to be serialized`
  1064. );
  1065. logger.time(timeMessage);
  1066. }
  1067. const value = /** @type {LazyFunction} */ (this.lazy)();
  1068. this.outdated = false;
  1069. if ("then" in value) {
  1070. // Move to state B1
  1071. this.lazy = write(() =>
  1072. value.then((data) => {
  1073. if (timeMessage) {
  1074. logger.timeEnd(timeMessage);
  1075. }
  1076. const oldMap = data.map;
  1077. /** @type {Content} */
  1078. const map = new Map();
  1079. for (const item of this.items) {
  1080. map.set(item, oldMap.get(item));
  1081. }
  1082. // Move to state C1 (or maybe C2)
  1083. this.content = map;
  1084. this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy);
  1085. return new PackContentItems(map);
  1086. })
  1087. );
  1088. } else {
  1089. // Move to state C1
  1090. if (timeMessage) {
  1091. logger.timeEnd(timeMessage);
  1092. }
  1093. const oldMap = value.map;
  1094. /** @type {Content} */
  1095. const map = new Map();
  1096. for (const item of this.items) {
  1097. map.set(item, oldMap.get(item));
  1098. }
  1099. this.content = map;
  1100. this.lazy = write(() => new PackContentItems(map));
  1101. }
  1102. }
  1103. }
  1104. /**
  1105. * Allow collecting memory.
  1106. * @param {Buffer} buf buffer
  1107. * @returns {Buffer} buffer that can be collected
  1108. */
  1109. const allowCollectingMemory = (buf) => {
  1110. const wasted = buf.buffer.byteLength - buf.byteLength;
  1111. if (wasted > 8192 && (wasted > 1048576 || wasted > buf.byteLength)) {
  1112. return Buffer.from(buf);
  1113. }
  1114. return buf;
  1115. };
  1116. class PackFileCacheStrategy {
  1117. /**
  1118. * Creates an instance of PackFileCacheStrategy.
  1119. * @param {object} options options
  1120. * @param {Compiler} options.compiler the compiler
  1121. * @param {IntermediateFileSystem} options.fs the filesystem
  1122. * @param {string} options.context the context directory
  1123. * @param {string} options.cacheLocation the location of the cache data
  1124. * @param {string} options.version version identifier
  1125. * @param {Logger} options.logger a logger
  1126. * @param {SnapshotOptions} options.snapshot options regarding snapshotting
  1127. * @param {number} options.maxAge max age of cache items
  1128. * @param {boolean=} options.profile track and log detailed timing information for individual cache items
  1129. * @param {boolean=} options.allowCollectingMemory allow to collect unused memory created during deserialization
  1130. * @param {false | "gzip" | "brotli" | "zstd"=} options.compression compression used
  1131. * @param {boolean=} options.readonly disable storing cache into filesystem
  1132. */
  1133. constructor({
  1134. compiler,
  1135. fs,
  1136. context,
  1137. cacheLocation,
  1138. version,
  1139. logger,
  1140. snapshot,
  1141. maxAge,
  1142. profile,
  1143. allowCollectingMemory,
  1144. compression,
  1145. readonly
  1146. }) {
  1147. /** @type {import("../serialization/Serializer")<PackContainer, null, EXPECTED_OBJECT>} */
  1148. this.fileSerializer = createFileSerializer(
  1149. fs,
  1150. /** @type {HashFunction} */
  1151. (compiler.options.output.hashFunction)
  1152. );
  1153. /** @type {FileSystemInfo} */
  1154. this.fileSystemInfo = new FileSystemInfo(fs, {
  1155. managedPaths: snapshot.managedPaths,
  1156. immutablePaths: snapshot.immutablePaths,
  1157. logger: logger.getChildLogger("webpack.FileSystemInfo"),
  1158. hashFunction: compiler.options.output.hashFunction
  1159. });
  1160. /** @type {Compiler} */
  1161. this.compiler = compiler;
  1162. /** @type {IntermediateFileSystem} */
  1163. this.fs = fs;
  1164. /** @type {string} */
  1165. this.context = context;
  1166. /** @type {string} */
  1167. this.cacheLocation = cacheLocation;
  1168. /** @type {string} */
  1169. this.version = version;
  1170. /** @type {Logger} */
  1171. this.logger = logger;
  1172. /** @type {number} */
  1173. this.maxAge = maxAge;
  1174. /** @type {boolean | undefined} */
  1175. this.profile = profile;
  1176. /** @type {boolean | undefined} */
  1177. this.readonly = readonly;
  1178. /** @type {boolean | undefined} */
  1179. this.allowCollectingMemory = allowCollectingMemory;
  1180. // referenced names per on-disk file, versioned by mtime since concurrent
  1181. // processes may rewrite packs in place under the same name
  1182. /** @type {Map<string, { mtimeMs: number, referenced: string[] }>} */
  1183. this._referencedFilesCache = new Map();
  1184. /** @type {false | "gzip" | "brotli" | "zstd" | undefined} */
  1185. this.compression = compression;
  1186. // eslint-disable-next-line n/no-unsupported-features/node-builtins
  1187. if (compression === "zstd" && !require("zlib").createZstdCompress) {
  1188. throw new Error("cache.compression: 'zstd' requires Node.js >= 22.15.0");
  1189. }
  1190. /** @type {string} */
  1191. this._extension =
  1192. compression === "brotli"
  1193. ? ".pack.br"
  1194. : compression === "gzip"
  1195. ? ".pack.gz"
  1196. : compression === "zstd"
  1197. ? ".pack.zst"
  1198. : ".pack";
  1199. /** @type {SnapshotOptions} */
  1200. this.snapshot = snapshot;
  1201. /** @type {BuildDependencies} */
  1202. this.buildDependencies = new Set();
  1203. /** @type {FileSystemDependencies} */
  1204. this.newBuildDependencies = new LazySet();
  1205. /** @type {InstanceType<Snapshot> | undefined} */
  1206. this.resolveBuildDependenciesSnapshot = undefined;
  1207. /** @type {ResolveResults | undefined} */
  1208. this.resolveResults = undefined;
  1209. /** @type {InstanceType<Snapshot> | undefined} */
  1210. this.buildSnapshot = undefined;
  1211. /** @type {Promise<Pack> | undefined} */
  1212. this.packPromise = this._openPack();
  1213. /** @type {Promise<void>} */
  1214. this.storePromise = Promise.resolve();
  1215. }
  1216. /**
  1217. * Returns pack.
  1218. * @returns {Promise<Pack>} pack
  1219. */
  1220. _getPack() {
  1221. if (this.packPromise === undefined) {
  1222. this.packPromise = this.storePromise.then(() => this._openPack());
  1223. }
  1224. return this.packPromise;
  1225. }
  1226. /**
  1227. * Returns the pack.
  1228. * @returns {Promise<Pack>} the pack
  1229. */
  1230. _openPack() {
  1231. const { logger, profile, cacheLocation, version } = this;
  1232. /** @type {InstanceType<Snapshot>} */
  1233. let buildSnapshot;
  1234. /** @type {BuildDependencies} */
  1235. let buildDependencies;
  1236. /** @type {BuildDependencies} */
  1237. let newBuildDependencies;
  1238. /** @type {InstanceType<Snapshot>} */
  1239. let resolveBuildDependenciesSnapshot;
  1240. /** @type {ResolveResults | undefined} */
  1241. let resolveResults;
  1242. logger.time("restore cache container");
  1243. return this.fileSerializer
  1244. .deserialize(null, {
  1245. filename: `${cacheLocation}/index${this._extension}`,
  1246. extension: `${this._extension}`,
  1247. logger,
  1248. profile,
  1249. retainedBuffer: this.allowCollectingMemory
  1250. ? allowCollectingMemory
  1251. : undefined
  1252. })
  1253. .catch((err) => {
  1254. if (err.code !== "ENOENT") {
  1255. logger.warn(
  1256. `Restoring pack failed from ${cacheLocation}${this._extension}: ${err}`
  1257. );
  1258. logger.debug(err.stack);
  1259. } else {
  1260. logger.debug(
  1261. `No pack exists at ${cacheLocation}${this._extension}: ${err}`
  1262. );
  1263. }
  1264. return undefined;
  1265. })
  1266. .then((packContainer) => {
  1267. logger.timeEnd("restore cache container");
  1268. if (!packContainer) return;
  1269. if (!(packContainer instanceof PackContainer)) {
  1270. logger.warn(
  1271. `Restored pack from ${cacheLocation}${this._extension}, but contained content is unexpected.`,
  1272. packContainer
  1273. );
  1274. return;
  1275. }
  1276. if (packContainer.version !== version) {
  1277. logger.log(
  1278. `Restored pack from ${cacheLocation}${this._extension}, but version doesn't match.`
  1279. );
  1280. return;
  1281. }
  1282. logger.time("check build dependencies");
  1283. return Promise.all([
  1284. new Promise((resolve, _reject) => {
  1285. this.fileSystemInfo.checkSnapshotValid(
  1286. packContainer.buildSnapshot,
  1287. (err, valid) => {
  1288. if (err) {
  1289. logger.log(
  1290. `Restored pack from ${cacheLocation}${this._extension}, but checking snapshot of build dependencies errored: ${err}.`
  1291. );
  1292. logger.debug(err.stack);
  1293. return resolve(false);
  1294. }
  1295. if (!valid) {
  1296. logger.log(
  1297. `Restored pack from ${cacheLocation}${this._extension}, but build dependencies have changed.`
  1298. );
  1299. return resolve(false);
  1300. }
  1301. buildSnapshot = packContainer.buildSnapshot;
  1302. return resolve(true);
  1303. }
  1304. );
  1305. }),
  1306. new Promise((resolve, _reject) => {
  1307. this.fileSystemInfo.checkSnapshotValid(
  1308. packContainer.resolveBuildDependenciesSnapshot,
  1309. (err, valid) => {
  1310. if (err) {
  1311. logger.log(
  1312. `Restored pack from ${cacheLocation}${this._extension}, but checking snapshot of resolving of build dependencies errored: ${err}.`
  1313. );
  1314. logger.debug(err.stack);
  1315. return resolve(false);
  1316. }
  1317. if (valid) {
  1318. resolveBuildDependenciesSnapshot =
  1319. packContainer.resolveBuildDependenciesSnapshot;
  1320. buildDependencies = packContainer.buildDependencies;
  1321. resolveResults = packContainer.resolveResults;
  1322. return resolve(true);
  1323. }
  1324. logger.log(
  1325. "resolving of build dependencies is invalid, will re-resolve build dependencies"
  1326. );
  1327. this.fileSystemInfo.checkResolveResultsValid(
  1328. packContainer.resolveResults,
  1329. (err, valid) => {
  1330. if (err) {
  1331. logger.log(
  1332. `Restored pack from ${cacheLocation}${this._extension}, but resolving of build dependencies errored: ${err}.`
  1333. );
  1334. logger.debug(err.stack);
  1335. return resolve(false);
  1336. }
  1337. if (valid) {
  1338. newBuildDependencies = packContainer.buildDependencies;
  1339. resolveResults = packContainer.resolveResults;
  1340. return resolve(true);
  1341. }
  1342. logger.log(
  1343. `Restored pack from ${cacheLocation}${this._extension}, but build dependencies resolve to different locations.`
  1344. );
  1345. return resolve(false);
  1346. }
  1347. );
  1348. }
  1349. );
  1350. })
  1351. ])
  1352. .catch((err) => {
  1353. logger.timeEnd("check build dependencies");
  1354. throw err;
  1355. })
  1356. .then(([buildSnapshotValid, resolveValid]) => {
  1357. logger.timeEnd("check build dependencies");
  1358. if (buildSnapshotValid && resolveValid) {
  1359. logger.time("restore cache content metadata");
  1360. const d =
  1361. /** @type {() => Pack} */
  1362. (packContainer.data)();
  1363. logger.timeEnd("restore cache content metadata");
  1364. return d;
  1365. }
  1366. return undefined;
  1367. });
  1368. })
  1369. .then((pack) => {
  1370. if (pack) {
  1371. pack.maxAge = this.maxAge;
  1372. this.buildSnapshot = buildSnapshot;
  1373. if (buildDependencies) this.buildDependencies = buildDependencies;
  1374. if (newBuildDependencies) {
  1375. this.newBuildDependencies.addAll(newBuildDependencies);
  1376. }
  1377. this.resolveResults = resolveResults;
  1378. this.resolveBuildDependenciesSnapshot =
  1379. resolveBuildDependenciesSnapshot;
  1380. return pack;
  1381. }
  1382. return new Pack(logger, this.maxAge);
  1383. })
  1384. .catch((err) => {
  1385. this.logger.warn(
  1386. `Restoring pack from ${cacheLocation}${this._extension} failed: ${err}`
  1387. );
  1388. this.logger.debug(err.stack);
  1389. return new Pack(logger, this.maxAge);
  1390. });
  1391. }
  1392. /**
  1393. * Returns promise.
  1394. * @param {string} identifier unique name for the resource
  1395. * @param {Etag | null} etag etag of the resource
  1396. * @param {Data} data cached content
  1397. * @returns {Promise<void>} promise
  1398. */
  1399. store(identifier, etag, data) {
  1400. if (this.readonly) return Promise.resolve();
  1401. return this._getPack().then((pack) => {
  1402. pack.set(identifier, etag === null ? null : etag.toString(), data);
  1403. });
  1404. }
  1405. /**
  1406. * Returns promise to the cached content.
  1407. * @param {string} identifier unique name for the resource
  1408. * @param {Etag | null} etag etag of the resource
  1409. * @returns {Promise<Data>} promise to the cached content
  1410. */
  1411. restore(identifier, etag) {
  1412. return this._getPack()
  1413. .then((pack) =>
  1414. pack.get(identifier, etag === null ? null : etag.toString())
  1415. )
  1416. .catch((err) => {
  1417. if (err && err.code !== "ENOENT") {
  1418. this.logger.warn(
  1419. `Restoring failed for ${identifier} from pack: ${err}`
  1420. );
  1421. this.logger.debug(err.stack);
  1422. }
  1423. });
  1424. }
  1425. /**
  1426. * Stores build dependencies.
  1427. * @param {FileSystemDependencies | Iterable<string>} dependencies dependencies to store
  1428. */
  1429. storeBuildDependencies(dependencies) {
  1430. if (this.readonly) return;
  1431. this.newBuildDependencies.addAll(dependencies);
  1432. }
  1433. afterAllStored() {
  1434. const packPromise = this.packPromise;
  1435. if (packPromise === undefined) return Promise.resolve();
  1436. const reportProgress = ProgressPlugin.getReporter(this.compiler);
  1437. return (this.storePromise = packPromise
  1438. .then((pack) => {
  1439. pack.stopCapturingRequests();
  1440. if (!pack.invalid) return;
  1441. this.packPromise = undefined;
  1442. this.logger.log("Storing pack...");
  1443. /** @type {undefined | Promise<void>} */
  1444. let promise;
  1445. /** @type {Set<string>} */
  1446. const newBuildDependencies = new Set();
  1447. for (const dep of this.newBuildDependencies) {
  1448. if (!this.buildDependencies.has(dep)) {
  1449. newBuildDependencies.add(dep);
  1450. }
  1451. }
  1452. if (newBuildDependencies.size > 0 || !this.buildSnapshot) {
  1453. if (reportProgress) reportProgress(0.5, "resolve build dependencies");
  1454. this.logger.debug(
  1455. `Capturing build dependencies... (${[...newBuildDependencies].join(", ")})`
  1456. );
  1457. promise = new Promise(
  1458. /**
  1459. * Handles the callback logic for this hook.
  1460. * @param {(value?: undefined) => void} resolve resolve
  1461. * @param {(reason?: Error) => void} reject reject
  1462. */
  1463. (resolve, reject) => {
  1464. this.logger.time("resolve build dependencies");
  1465. this.fileSystemInfo.resolveBuildDependencies(
  1466. this.context,
  1467. newBuildDependencies,
  1468. (err, result) => {
  1469. this.logger.timeEnd("resolve build dependencies");
  1470. if (err) return reject(err);
  1471. this.logger.time("snapshot build dependencies");
  1472. const {
  1473. files,
  1474. directories,
  1475. missing,
  1476. resolveResults,
  1477. resolveDependencies
  1478. } = /** @type {ResolveBuildDependenciesResult} */ (result);
  1479. if (this.resolveResults) {
  1480. for (const [key, value] of resolveResults) {
  1481. this.resolveResults.set(key, value);
  1482. }
  1483. } else {
  1484. this.resolveResults = resolveResults;
  1485. }
  1486. if (reportProgress) {
  1487. reportProgress(
  1488. 0.6,
  1489. "snapshot build dependencies",
  1490. "resolving"
  1491. );
  1492. }
  1493. this.fileSystemInfo.createSnapshot(
  1494. undefined,
  1495. resolveDependencies.files,
  1496. resolveDependencies.directories,
  1497. resolveDependencies.missing,
  1498. this.snapshot.resolveBuildDependencies,
  1499. (err, snapshot) => {
  1500. if (err) {
  1501. this.logger.timeEnd("snapshot build dependencies");
  1502. return reject(err);
  1503. }
  1504. if (!snapshot) {
  1505. this.logger.timeEnd("snapshot build dependencies");
  1506. return reject(
  1507. new Error("Unable to snapshot resolve dependencies")
  1508. );
  1509. }
  1510. if (this.resolveBuildDependenciesSnapshot) {
  1511. this.resolveBuildDependenciesSnapshot =
  1512. this.fileSystemInfo.mergeSnapshots(
  1513. this.resolveBuildDependenciesSnapshot,
  1514. snapshot
  1515. );
  1516. } else {
  1517. this.resolveBuildDependenciesSnapshot = snapshot;
  1518. }
  1519. if (reportProgress) {
  1520. reportProgress(
  1521. 0.7,
  1522. "snapshot build dependencies",
  1523. "modules"
  1524. );
  1525. }
  1526. this.fileSystemInfo.createSnapshot(
  1527. undefined,
  1528. files,
  1529. directories,
  1530. missing,
  1531. this.snapshot.buildDependencies,
  1532. (err, snapshot) => {
  1533. this.logger.timeEnd("snapshot build dependencies");
  1534. if (err) return reject(err);
  1535. if (!snapshot) {
  1536. return reject(
  1537. new Error("Unable to snapshot build dependencies")
  1538. );
  1539. }
  1540. this.logger.debug("Captured build dependencies");
  1541. if (this.buildSnapshot) {
  1542. this.buildSnapshot =
  1543. this.fileSystemInfo.mergeSnapshots(
  1544. this.buildSnapshot,
  1545. snapshot
  1546. );
  1547. } else {
  1548. this.buildSnapshot = snapshot;
  1549. }
  1550. resolve();
  1551. }
  1552. );
  1553. }
  1554. );
  1555. }
  1556. );
  1557. }
  1558. );
  1559. } else {
  1560. promise = Promise.resolve();
  1561. }
  1562. return promise.then(() => {
  1563. if (reportProgress) reportProgress(0.8, "serialize pack");
  1564. this.logger.time("store pack");
  1565. const updatedBuildDependencies = new Set(this.buildDependencies);
  1566. for (const dep of newBuildDependencies) {
  1567. updatedBuildDependencies.add(dep);
  1568. }
  1569. const content = new PackContainer(
  1570. pack,
  1571. this.version,
  1572. /** @type {InstanceType<Snapshot>} */
  1573. (this.buildSnapshot),
  1574. updatedBuildDependencies,
  1575. /** @type {ResolveResults} */
  1576. (this.resolveResults),
  1577. /** @type {InstanceType<Snapshot>} */
  1578. (this.resolveBuildDependenciesSnapshot)
  1579. );
  1580. const cleanup = this.fs.unlink !== undefined;
  1581. /** @type {Set<string> | undefined} */
  1582. const writtenFiles = cleanup ? new Set() : undefined;
  1583. /** @type {Set<string> | undefined} */
  1584. const retainedFiles = cleanup ? new Set() : undefined;
  1585. return this.fileSerializer
  1586. .serialize(content, {
  1587. filename: `${this.cacheLocation}/index${this._extension}`,
  1588. extension: `${this._extension}`,
  1589. writtenFiles,
  1590. retainedFiles,
  1591. logger: this.logger,
  1592. profile: this.profile
  1593. })
  1594. .then(() => {
  1595. for (const dep of newBuildDependencies) {
  1596. this.buildDependencies.add(dep);
  1597. }
  1598. this.newBuildDependencies.clear();
  1599. this.logger.timeEnd("store pack");
  1600. const stats = pack.getContentStats();
  1601. this.logger.log(
  1602. "Stored pack (%d items, %d files, %d MiB)",
  1603. pack.itemInfo.size,
  1604. stats.count,
  1605. Math.round(stats.size / 1024 / 1024)
  1606. );
  1607. if (writtenFiles !== undefined) {
  1608. return this._cleanupUnusedFiles(
  1609. writtenFiles,
  1610. /** @type {Set<string>} */ (retainedFiles)
  1611. );
  1612. }
  1613. })
  1614. .catch((err) => {
  1615. this.logger.timeEnd("store pack");
  1616. // files may be in an unknown state after a failed store
  1617. this._referencedFilesCache.clear();
  1618. this.logger.warn(`Caching failed for pack: ${err}`);
  1619. this.logger.debug(err.stack);
  1620. });
  1621. });
  1622. })
  1623. .catch((err) => {
  1624. this.logger.warn(`Caching failed for pack: ${err}`);
  1625. this.logger.debug(err.stack);
  1626. }));
  1627. }
  1628. /**
  1629. * Reads when the currently unreferenced files were first seen. A missing or
  1630. * unreadable file just restarts the grace period for every orphan.
  1631. * @returns {Promise<UnreferencedFiles>} first seen time and size per file name
  1632. */
  1633. _readUnreferencedFiles() {
  1634. return new Promise((resolve) => {
  1635. this.fs.readFile(
  1636. `${this.cacheLocation}/${UNREFERENCED_FILE}`,
  1637. (err, content) => {
  1638. /** @type {UnreferencedFiles} */
  1639. const result = new Map();
  1640. if (err) return resolve(result);
  1641. try {
  1642. const data = JSON.parse(
  1643. /** @type {Buffer} */ (content).toString("utf8")
  1644. );
  1645. for (const [file, entry] of Object.entries(data)) {
  1646. const { firstSeen, size } = /** @type {UnreferencedFile} */ (
  1647. entry
  1648. );
  1649. if (typeof firstSeen === "number" && typeof size === "number") {
  1650. result.set(file, { firstSeen, size });
  1651. }
  1652. }
  1653. } catch (_err) {
  1654. result.clear();
  1655. }
  1656. resolve(result);
  1657. }
  1658. );
  1659. });
  1660. }
  1661. /**
  1662. * Persists when the still unreferenced files were first seen. Failing to write
  1663. * only costs the orphans another grace period, so errors are ignored.
  1664. * @param {UnreferencedFiles} unreferenced first seen time and size per file name
  1665. * @param {boolean} hadEntries whether a previous state exists that must be replaced
  1666. * @returns {Promise<void>} promise
  1667. */
  1668. _writeUnreferencedFiles(unreferenced, hadEntries) {
  1669. if (unreferenced.size === 0 && !hadEntries) return Promise.resolve();
  1670. /** @type {Record<string, UnreferencedFile>} */
  1671. const data = {};
  1672. for (const [file, entry] of unreferenced) data[file] = entry;
  1673. return new Promise((resolve) => {
  1674. this.fs.writeFile(
  1675. `${this.cacheLocation}/${UNREFERENCED_FILE}`,
  1676. JSON.stringify(data),
  1677. () => resolve()
  1678. );
  1679. });
  1680. }
  1681. /**
  1682. * Deletes files from the cache directory that are no longer referenced by the
  1683. * stored pack. Retained files are walked on disk since nested lazy segments
  1684. * reference files not visible during serialization. Errors only log a warning.
  1685. * @param {Set<string>} writtenNames names (without extension) written by this store
  1686. * @param {Set<string>} retainedNames names (without extension) referenced but not rewritten
  1687. * @returns {Promise<void>} promise
  1688. */
  1689. async _cleanupUnusedFiles(writtenNames, retainedNames) {
  1690. this.logger.time("cleanup unused cache files");
  1691. const fs = this.fs;
  1692. const extension = this._extension;
  1693. const cacheLocation = this.cacheLocation;
  1694. const referencedFilesCache = this._referencedFilesCache;
  1695. try {
  1696. // rewritten files may reference different names now
  1697. for (const name of writtenNames) referencedFilesCache.delete(name);
  1698. /** @type {Set<string>} */
  1699. const liveFiles = new Set([`index${extension}`, UNREFERENCED_FILE]);
  1700. for (const name of writtenNames) liveFiles.add(`${name}${extension}`);
  1701. /** @type {string[]} */
  1702. const queue = [];
  1703. /**
  1704. * Marks a file live and queues it for walking its references.
  1705. * @param {string} name file name without extension
  1706. */
  1707. const enqueue = (name) => {
  1708. const file = `${name}${extension}`;
  1709. if (liveFiles.has(file)) return;
  1710. liveFiles.add(file);
  1711. queue.push(name);
  1712. };
  1713. for (const name of retainedNames) enqueue(name);
  1714. while (queue.length > 0) {
  1715. const name = /** @type {string} */ (queue.pop());
  1716. const file = `${cacheLocation}/${name}${extension}`;
  1717. // an unchanged mtime proves the memo entry still matches the disk
  1718. const mtimeMs = await new Promise((resolve, reject) => {
  1719. fs.stat(file, (err, stats) => {
  1720. if (err) return reject(err);
  1721. resolve(
  1722. /** @type {number} */ (
  1723. /** @type {import("../util/fs").IStats} */ (stats).mtimeMs
  1724. )
  1725. );
  1726. });
  1727. });
  1728. const entry = referencedFilesCache.get(name);
  1729. let referenced;
  1730. if (entry !== undefined && entry.mtimeMs === mtimeMs) {
  1731. referenced = entry.referenced;
  1732. } else {
  1733. referenced = await getReferencedFilenames(fs, file);
  1734. referencedFilesCache.set(name, { mtimeMs, referenced });
  1735. }
  1736. for (const referencedName of referenced) enqueue(referencedName);
  1737. }
  1738. const files = await new Promise((resolve, reject) => {
  1739. fs.readdir(cacheLocation, (err, files) => {
  1740. if (err) return reject(err);
  1741. resolve(/** @type {string[]} */ (files));
  1742. });
  1743. });
  1744. const seenFiles = await this._readUnreferencedFiles();
  1745. const now = Date.now();
  1746. // every store rewrites the index backup, so a recorded time would age a file
  1747. // that is in fact new; renaming carries the previous index mtime onto it
  1748. const indexBackup = `index${extension}.old`;
  1749. /** @type {UnreferencedFiles} */
  1750. const stillUnreferenced = new Map();
  1751. let deletedCount = 0;
  1752. for (const file of files) {
  1753. if (typeof file !== "string" || liveFiles.has(file)) continue;
  1754. const path = `${cacheLocation}/${file}`;
  1755. const stats = await new Promise((resolve) => {
  1756. fs.stat(path, (err, stats) => {
  1757. resolve(
  1758. err
  1759. ? undefined
  1760. : /** @type {import("../util/fs").IStats} */ (stats)
  1761. );
  1762. });
  1763. });
  1764. if (stats === undefined || !stats.isFile()) continue;
  1765. const size = /** @type {number} */ (stats.size);
  1766. const seen = seenFiles.get(file);
  1767. // a differing size means the name was rewritten, so it is a new orphan
  1768. const firstSeen =
  1769. seen !== undefined && seen.size === size ? seen.firstSeen : now;
  1770. const expireTime = now - CLEANUP_GRACE_PERIOD;
  1771. const mtimeMs = /** @type {number} */ (stats.mtimeMs);
  1772. // either signal is enough: modification times are lost when a cache is
  1773. // restored, and recorded times are lost when the cache directory is new
  1774. const expired =
  1775. mtimeMs <= expireTime ||
  1776. (file !== indexBackup &&
  1777. firstSeen <= expireTime &&
  1778. mtimeMs <= now - CLEANUP_RECENT_WRITE_PERIOD);
  1779. if (expired) {
  1780. const deleted = await new Promise((resolve) => {
  1781. /** @type {NonNullable<IntermediateFileSystem["unlink"]>} */
  1782. (fs.unlink)(path, (err) => resolve(!err));
  1783. });
  1784. if (deleted) {
  1785. deletedCount++;
  1786. continue;
  1787. }
  1788. }
  1789. if (file !== indexBackup) {
  1790. stillUnreferenced.set(file, { firstSeen, size });
  1791. }
  1792. }
  1793. await this._writeUnreferencedFiles(stillUnreferenced, seenFiles.size > 0);
  1794. // drop entries of files that are no longer alive
  1795. for (const name of referencedFilesCache.keys()) {
  1796. if (!liveFiles.has(`${name}${extension}`)) {
  1797. referencedFilesCache.delete(name);
  1798. }
  1799. }
  1800. if (deletedCount > 0) {
  1801. this.logger.log("Deleted %d unused cache files", deletedCount);
  1802. }
  1803. } catch (err) {
  1804. this.logger.warn(
  1805. `Cleanup of unused cache files failed: ${/** @type {Error} */ (err)}`
  1806. );
  1807. this.logger.debug(/** @type {Error} */ (err).stack);
  1808. }
  1809. this.logger.timeEnd("cleanup unused cache files");
  1810. }
  1811. clear() {
  1812. this.fileSystemInfo.clear();
  1813. this.buildDependencies.clear();
  1814. this.newBuildDependencies.clear();
  1815. this.resolveBuildDependenciesSnapshot = undefined;
  1816. this.resolveResults = undefined;
  1817. this.buildSnapshot = undefined;
  1818. this.packPromise = undefined;
  1819. }
  1820. }
  1821. module.exports = PackFileCacheStrategy;