|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright Google LLC All Rights Reserved. |
| 4 | + * |
| 5 | + * Use of this source code is governed by an MIT-style license that can be |
| 6 | + * found in the LICENSE file at https://angular.dev/license |
| 7 | + */ |
| 8 | + |
| 9 | +import type { Loader, OnLoadResult, PartialMessage } from 'esbuild'; |
| 10 | +import { createHash } from 'node:crypto'; |
| 11 | +import { existsSync } from 'node:fs'; |
| 12 | +import { readFile } from 'node:fs/promises'; |
| 13 | +import type { Cache as PersistentCacheStore } from './cache'; |
| 14 | +import { LoadResultCache, MemoryLoadResultCache } from './load-result-cache'; |
| 15 | + |
| 16 | +/** |
| 17 | + * Serialized representation of any esbuild load result stored in persistent cache. |
| 18 | + */ |
| 19 | +export interface CachedLoadResultEntry { |
| 20 | + /** Compiled output string or binary data */ |
| 21 | + contents: string | Uint8Array; |
| 22 | + |
| 23 | + /** esbuild loader type */ |
| 24 | + loader?: Loader; |
| 25 | + |
| 26 | + /** Absolute paths of all imported/watched dependency files */ |
| 27 | + watchFiles: string[]; |
| 28 | + |
| 29 | + /** Map of watchFile absolute paths to content hashes */ |
| 30 | + watchFilesHashes: Record<string, string>; |
| 31 | + |
| 32 | + /** Warnings emitted during load processing */ |
| 33 | + warnings?: PartialMessage[]; |
| 34 | + |
| 35 | + /** Errors emitted during load processing */ |
| 36 | + errors?: PartialMessage[]; |
| 37 | +} |
| 38 | + |
| 39 | +function hashContent(content: string | Uint8Array): string { |
| 40 | + return createHash('sha256').update(content).digest('hex'); |
| 41 | +} |
| 42 | + |
| 43 | +/** |
| 44 | + * Calculates a unique cache key by updating the hash incrementally. |
| 45 | + * This prevents implicit string coercion of large binary content buffers. |
| 46 | + */ |
| 47 | +function calculateCacheKey( |
| 48 | + globalConfigHash: string, |
| 49 | + path: string, |
| 50 | + content: string | Uint8Array, |
| 51 | +): string { |
| 52 | + return createHash('sha256').update(globalConfigHash).update(path).update(content).digest('hex'); |
| 53 | +} |
| 54 | + |
| 55 | +/** |
| 56 | + * Validates that all imported watch files exist on disk and their content hashes match. |
| 57 | + * Processes files in parallel chunks of 8 to avoid exhausting file descriptors. |
| 58 | + */ |
| 59 | +async function isCacheEntryValid(watchFilesHashes: Record<string, string>): Promise<boolean> { |
| 60 | + const watchFiles = Object.keys(watchFilesHashes); |
| 61 | + const concurrencyLimit = 8; |
| 62 | + |
| 63 | + for (let i = 0; i < watchFiles.length; i += concurrencyLimit) { |
| 64 | + const chunk = watchFiles.slice(i, i + concurrencyLimit); |
| 65 | + const results = await Promise.all( |
| 66 | + chunk.map(async (filePath) => { |
| 67 | + if (!existsSync(filePath)) { |
| 68 | + return false; |
| 69 | + } |
| 70 | + try { |
| 71 | + const currentContent = await readFile(filePath); |
| 72 | + |
| 73 | + return hashContent(currentContent) === watchFilesHashes[filePath]; |
| 74 | + } catch { |
| 75 | + return false; |
| 76 | + } |
| 77 | + }), |
| 78 | + ); |
| 79 | + |
| 80 | + if (results.some((isValid) => !isValid)) { |
| 81 | + return false; |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + return true; |
| 86 | +} |
| 87 | + |
| 88 | +/** |
| 89 | + * Computes hashes for an array of watch file paths. |
| 90 | + * Processes files in parallel chunks of 8 to avoid exhausting file descriptors. |
| 91 | + */ |
| 92 | +async function computeHashesForWatchFiles(watchFiles: string[]): Promise<Record<string, string>> { |
| 93 | + const watchFilesHashes: Record<string, string> = {}; |
| 94 | + const concurrencyLimit = 8; |
| 95 | + |
| 96 | + for (let i = 0; i < watchFiles.length; i += concurrencyLimit) { |
| 97 | + const chunk = watchFiles.slice(i, i + concurrencyLimit); |
| 98 | + await Promise.all( |
| 99 | + chunk.map(async (filePath) => { |
| 100 | + if (existsSync(filePath)) { |
| 101 | + try { |
| 102 | + const content = await readFile(filePath); |
| 103 | + watchFilesHashes[filePath] = hashContent(content); |
| 104 | + } catch { |
| 105 | + // Ignore unreadable files |
| 106 | + } |
| 107 | + } |
| 108 | + }), |
| 109 | + ); |
| 110 | + } |
| 111 | + |
| 112 | + return watchFilesHashes; |
| 113 | +} |
| 114 | + |
| 115 | +export class PersistentLoadResultCache implements LoadResultCache { |
| 116 | + private readonly memoryCache = new MemoryLoadResultCache(); |
| 117 | + |
| 118 | + constructor( |
| 119 | + private readonly persistentStore?: PersistentCacheStore<CachedLoadResultEntry>, |
| 120 | + private readonly globalConfigHash: string = '', |
| 121 | + ) {} |
| 122 | + |
| 123 | + /** |
| 124 | + * Retrieves a load result from cache. |
| 125 | + * Checks L1 memory cache first for immediate watch-mode speed, falling back to L2 persistent disk |
| 126 | + * store on L1 cache miss. L2 persistent cache entries are validated against dependency content hashes. |
| 127 | + */ |
| 128 | + async get(path: string): Promise<OnLoadResult | undefined> { |
| 129 | + // 1. Check L1 Memory Cache |
| 130 | + const memoryResult = this.memoryCache.get(path); |
| 131 | + if (memoryResult) { |
| 132 | + return memoryResult; |
| 133 | + } |
| 134 | + |
| 135 | + if (!this.persistentStore) { |
| 136 | + return undefined; |
| 137 | + } |
| 138 | + |
| 139 | + // 2. Check L2 Persistent Disk Cache |
| 140 | + let content: string | Uint8Array = ''; |
| 141 | + const filePath = path.startsWith('file:') ? path.slice(5) : path; |
| 142 | + if (existsSync(filePath)) { |
| 143 | + try { |
| 144 | + content = await readFile(filePath); |
| 145 | + } catch { |
| 146 | + return undefined; |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + const cacheKey = calculateCacheKey(this.globalConfigHash, path, content); |
| 151 | + const cached = await this.persistentStore.get(cacheKey); |
| 152 | + |
| 153 | + if (cached && (await isCacheEntryValid(cached.watchFilesHashes))) { |
| 154 | + const result: OnLoadResult = { |
| 155 | + contents: cached.contents, |
| 156 | + loader: cached.loader, |
| 157 | + watchFiles: cached.watchFiles, |
| 158 | + warnings: cached.warnings, |
| 159 | + errors: cached.errors, |
| 160 | + }; |
| 161 | + |
| 162 | + // Populate L1 Memory Cache for subsequent lookups |
| 163 | + await this.memoryCache.put(path, result); |
| 164 | + |
| 165 | + return result; |
| 166 | + } |
| 167 | + |
| 168 | + return undefined; |
| 169 | + } |
| 170 | + |
| 171 | + /** |
| 172 | + * Stores a load result in both L1 memory cache and L2 persistent disk store. |
| 173 | + */ |
| 174 | + async put(path: string, result: OnLoadResult): Promise<void> { |
| 175 | + await this.memoryCache.put(path, result); |
| 176 | + |
| 177 | + if (this.persistentStore && result.contents) { |
| 178 | + let content: string | Uint8Array = ''; |
| 179 | + const filePath = path.startsWith('file:') ? path.slice(5) : path; |
| 180 | + if (existsSync(filePath)) { |
| 181 | + try { |
| 182 | + content = await readFile(filePath); |
| 183 | + } catch { |
| 184 | + // ignore |
| 185 | + } |
| 186 | + } |
| 187 | + |
| 188 | + const cacheKey = calculateCacheKey(this.globalConfigHash, path, content); |
| 189 | + const watchFilesHashes = await computeHashesForWatchFiles(result.watchFiles ?? []); |
| 190 | + |
| 191 | + await this.persistentStore.put(cacheKey, { |
| 192 | + contents: result.contents, |
| 193 | + loader: result.loader, |
| 194 | + watchFiles: result.watchFiles ?? [], |
| 195 | + watchFilesHashes, |
| 196 | + warnings: result.warnings, |
| 197 | + errors: result.errors, |
| 198 | + }); |
| 199 | + } |
| 200 | + } |
| 201 | + |
| 202 | + /** |
| 203 | + * Invalidates cached entries affected by a modified dependency file during watch mode. |
| 204 | + * |
| 205 | + * Note: Invalidation of L1 memory cache is sufficient for active watch mode. |
| 206 | + * Cross-process/cold start stale entries in L2 persistent store are automatically handled |
| 207 | + * during `get()` via dependency content hash verification (`isCacheEntryValid`). |
| 208 | + */ |
| 209 | + invalidate(path: string): boolean { |
| 210 | + return this.memoryCache.invalidate(path); |
| 211 | + } |
| 212 | + |
| 213 | + get watchFiles(): ReadonlyArray<string> { |
| 214 | + return this.memoryCache.watchFiles; |
| 215 | + } |
| 216 | +} |
0 commit comments