-
Notifications
You must be signed in to change notification settings - Fork 11.9k
refactor(@angular/build): implement generic persistent load result cache infrastructure for build pipeline #33651
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
clydin
wants to merge
1
commit into
angular:main
Choose a base branch
from
clydin:feat/persistent-load-result-cache
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
271 changes: 271 additions & 0 deletions
271
packages/angular/build/src/tools/esbuild/persistent-load-result-cache.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,271 @@ | ||
| /** | ||
| * @license | ||
| * Copyright Google LLC All Rights Reserved. | ||
| * | ||
| * Use of this source code is governed by an MIT-style license that can be | ||
| * found in the LICENSE file at https://angular.dev/license | ||
| */ | ||
|
|
||
| import type { Loader, OnLoadResult, PartialMessage } from 'esbuild'; | ||
| import { createHash } from 'node:crypto'; | ||
| import { readFile, stat } from 'node:fs/promises'; | ||
| import type { Cache as PersistentCacheStore } from './cache'; | ||
| import { LoadResultCache, MemoryLoadResultCache } from './load-result-cache'; | ||
|
|
||
| /** | ||
| * Metadata for a single watch file dependency. | ||
| */ | ||
| export interface CachedDependencyMetadata { | ||
| hash: string; | ||
| mtimeMs: number; | ||
| size: number; | ||
| } | ||
|
|
||
| /** | ||
| * Serialized representation of any esbuild load result stored in persistent cache. | ||
| */ | ||
| export interface CachedLoadResultEntry { | ||
| /** Compiled output string or binary data */ | ||
| contents: string | Uint8Array; | ||
|
|
||
| /** esbuild loader type */ | ||
| loader?: Loader; | ||
|
|
||
| /** Absolute paths of all imported/watched dependency files */ | ||
| watchFiles: string[]; | ||
|
|
||
| /** Map of watchFile absolute paths to dependency metadata */ | ||
| watchFilesMetadata: Record<string, CachedDependencyMetadata>; | ||
|
|
||
| /** Warnings emitted during load processing */ | ||
| warnings?: PartialMessage[]; | ||
|
|
||
| /** Errors emitted during load processing */ | ||
| errors?: PartialMessage[]; | ||
| } | ||
|
|
||
| function hashContent(content: string | Uint8Array): string { | ||
| return createHash('sha256').update(content).digest('hex'); | ||
| } | ||
|
|
||
| /** | ||
| * Calculates a unique cache key by updating the hash incrementally. | ||
| * This prevents implicit string coercion of large binary content buffers. | ||
| */ | ||
| function calculateCacheKey( | ||
| globalConfigHash: string, | ||
| path: string, | ||
| content: string | Uint8Array, | ||
| ): string { | ||
| return createHash('sha256') | ||
| .update(globalConfigHash) | ||
| .update('\0') | ||
| .update(path) | ||
| .update('\0') | ||
| .update(content) | ||
| .digest('hex'); | ||
| } | ||
|
|
||
| /** | ||
| * Validates that all imported watch files exist on disk and their contents match. | ||
| * Performs a fast-path metadata check (mtime + size) first, falling back to content hashing. | ||
| * Heals/updates the cached metadata on disk if the content hash was valid but the metadata changed. | ||
| */ | ||
| async function validateAndHealCacheEntry( | ||
| watchFilesMetadata: Record<string, CachedDependencyMetadata>, | ||
| store: PersistentCacheStore<CachedLoadResultEntry>, | ||
| cacheKey: string, | ||
| cached: CachedLoadResultEntry, | ||
| ): Promise<boolean> { | ||
| const watchFiles = Object.keys(watchFilesMetadata); | ||
| const concurrencyLimit = 8; | ||
| let healed = false; | ||
|
|
||
| for (let i = 0; i < watchFiles.length; i += concurrencyLimit) { | ||
| const chunk = watchFiles.slice(i, i + concurrencyLimit); | ||
| const results = await Promise.all( | ||
| chunk.map(async (filePath) => { | ||
| try { | ||
| const stats = await stat(filePath); | ||
| const expected = watchFilesMetadata[filePath]; | ||
|
|
||
| // 1. Fast Path: size and mtime match | ||
| if (stats.size === expected.size && stats.mtimeMs === expected.mtimeMs) { | ||
| return true; | ||
| } | ||
|
|
||
| // 2. Slow Path: content hash fallback | ||
| const currentContent = await readFile(filePath); | ||
| const currentHash = hashContent(currentContent); | ||
| if (currentHash === expected.hash) { | ||
| // Heal cache entry with new metadata | ||
| watchFilesMetadata[filePath] = { | ||
| ...expected, | ||
| mtimeMs: stats.mtimeMs, | ||
| size: stats.size, | ||
| }; | ||
| healed = true; | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| return false; | ||
| } catch { | ||
| return false; | ||
| } | ||
| }), | ||
| ); | ||
|
|
||
| if (results.some((isValid) => !isValid)) { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| if (healed) { | ||
| try { | ||
| await store.put(cacheKey, cached); | ||
| } catch { | ||
| // Ignore errors writing healed entries | ||
| } | ||
| } | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| /** | ||
| * Computes metadata (content hashes, mtime, size) for an array of watch file paths. | ||
| * Processes files in parallel chunks of 8 to avoid exhausting file descriptors. | ||
| */ | ||
| async function computeMetadataForWatchFiles( | ||
| watchFiles: string[], | ||
| ): Promise<Record<string, CachedDependencyMetadata>> { | ||
| const watchFilesMetadata: Record<string, CachedDependencyMetadata> = {}; | ||
| const concurrencyLimit = 8; | ||
|
|
||
| for (let i = 0; i < watchFiles.length; i += concurrencyLimit) { | ||
| const chunk = watchFiles.slice(i, i + concurrencyLimit); | ||
| await Promise.all( | ||
| chunk.map(async (filePath) => { | ||
| try { | ||
| const [content, stats] = await Promise.all([readFile(filePath), stat(filePath)]); | ||
| watchFilesMetadata[filePath] = { | ||
| hash: hashContent(content), | ||
| mtimeMs: stats.mtimeMs, | ||
| size: stats.size, | ||
| }; | ||
| } catch { | ||
| // Ignore unreadable files | ||
| } | ||
| }), | ||
| ); | ||
| } | ||
|
|
||
| return watchFilesMetadata; | ||
| } | ||
|
|
||
| export class PersistentLoadResultCache implements LoadResultCache { | ||
| private readonly memoryCache = new MemoryLoadResultCache(); | ||
|
|
||
| constructor( | ||
| private readonly persistentStore?: PersistentCacheStore<CachedLoadResultEntry>, | ||
| private readonly globalConfigHash: string = '', | ||
| ) {} | ||
|
|
||
| /** | ||
| * Retrieves a load result from cache. | ||
| * Checks L1 memory cache first for immediate watch-mode speed, falling back to L2 persistent disk | ||
| * store on L1 cache miss. L2 persistent cache entries are validated against dependency metadata. | ||
| */ | ||
| async get(path: string): Promise<OnLoadResult | undefined> { | ||
| // 1. Check L1 Memory Cache | ||
| const memoryResult = this.memoryCache.get(path); | ||
| if (memoryResult) { | ||
| return memoryResult; | ||
| } | ||
|
|
||
| if (!this.persistentStore) { | ||
| return undefined; | ||
| } | ||
|
|
||
| // 2. Check L2 Persistent Disk Cache | ||
| let content: string | Uint8Array; | ||
| const filePath = path.startsWith('file:') ? path.slice(5) : path; | ||
| try { | ||
| content = await readFile(filePath); | ||
| } catch { | ||
| return undefined; | ||
| } | ||
|
|
||
| const cacheKey = calculateCacheKey(this.globalConfigHash, path, content); | ||
| const cached = await this.persistentStore.get(cacheKey); | ||
|
|
||
| if ( | ||
| cached && | ||
| (await validateAndHealCacheEntry( | ||
| cached.watchFilesMetadata, | ||
| this.persistentStore, | ||
| cacheKey, | ||
| cached, | ||
| )) | ||
| ) { | ||
| const result: OnLoadResult = { | ||
| contents: cached.contents, | ||
| loader: cached.loader, | ||
| watchFiles: cached.watchFiles, | ||
| warnings: cached.warnings, | ||
| errors: cached.errors, | ||
| }; | ||
|
|
||
| // Populate L1 Memory Cache for subsequent lookups | ||
| await this.memoryCache.put(path, result); | ||
|
|
||
| return result; | ||
| } | ||
|
|
||
| return undefined; | ||
| } | ||
|
|
||
| /** | ||
| * Stores a load result in both L1 memory cache and L2 persistent disk store. | ||
| */ | ||
| async put(path: string, result: OnLoadResult): Promise<void> { | ||
| await this.memoryCache.put(path, result); | ||
|
|
||
| if (this.persistentStore && result.contents !== undefined) { | ||
| let content: string | Uint8Array; | ||
| const filePath = path.startsWith('file:') ? path.slice(5) : path; | ||
| try { | ||
| content = await readFile(filePath); | ||
| } catch { | ||
| content = ''; | ||
| } | ||
|
|
||
| const cacheKey = calculateCacheKey(this.globalConfigHash, path, content); | ||
| const watchFilesMetadata = await computeMetadataForWatchFiles(result.watchFiles ?? []); | ||
|
|
||
| await this.persistentStore.put(cacheKey, { | ||
| contents: result.contents, | ||
| loader: result.loader, | ||
| watchFiles: result.watchFiles ?? [], | ||
| watchFilesMetadata, | ||
| warnings: result.warnings, | ||
| errors: result.errors, | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Invalidates cached entries affected by a modified dependency file during watch mode. | ||
| * | ||
| * Note: Invalidation of L1 memory cache is sufficient for active watch mode. | ||
| * Cross-process/cold start stale entries in L2 persistent store are automatically handled | ||
| * during `get()` via dependency metadata verification (`validateAndHealCacheEntry`). | ||
| */ | ||
| invalidate(path: string): boolean { | ||
| return this.memoryCache.invalidate(path); | ||
| } | ||
|
|
||
| get watchFiles(): ReadonlyArray<string> { | ||
| return this.memoryCache.watchFiles; | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.