// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. import * as path from 'node:path'; import * as crypto from 'node:crypto'; import { FileSystem, type FolderItem, InternalError, Async, LockFile } from '@rushstack/node-core-library'; import type { ITerminal } from '@rushstack/terminal'; import type { RushConfigurationProject } from '../../api/RushConfigurationProject'; import type { BuildCacheConfiguration } from '../../api/BuildCacheConfiguration'; import type { ICloudBuildCacheProvider } from './ICloudBuildCacheProvider'; import type { FileSystemBuildCacheProvider } from './FileSystemBuildCacheProvider'; import { TarExecutable } from '../../utilities/TarExecutable'; import { EnvironmentVariableNames } from '../../api/EnvironmentConfiguration'; import type { IBaseOperationExecutionResult } from '../operations/IOperationExecutionResult'; import { OutputFolderReceipt, type PendingOutputFolderReceipt } from './OutputFolderReceipt'; import { tryRestoreThroughStagingFolderAsync } from './StagedRestore'; import { type DeferredCacheEntryWrites, type ISealedOutputs, formatMegabytes } from './DeferredCacheEntryWrites'; /** * How long to wait to acquire the per-cache-entry download lock (see * {@link OperationBuildCache._getDirectFileTransferLockResourceName}) before giving up and * downloading independently. This is strictly a best-effort optimization to avoid redundant * downloads when multiple local Rush processes race to restore the same cache entry; it is not * required for correctness, since downloads always land in a uniquely-named temp file that is * atomically renamed into place. */ const DIRECT_FILE_TRANSFER_LOCK_MAX_WAIT_MS: number = 5 * 60 * 1000; // Five minutes /** * @internal */ export interface IOperationBuildCacheOptions { /** * The repo-wide configuration for the build cache. */ buildCacheConfiguration: BuildCacheConfiguration; /** * The terminal to use for logging. */ terminal: ITerminal; /** * If true, omit AppleDouble (`._*`) files from cache archives when running on macOS * and a companion file exists in the same directory. */ excludeAppleDoubleFiles: boolean; /** * If true, use file-based APIs (when available) to transfer cache entries to and from the * cloud provider, avoiding buffering the entire entry in memory. */ useDirectFileTransfersForBuildCache: boolean; } /** * @internal */ export type IProjectBuildCacheOptions = IOperationBuildCacheOptions & { /** * Value from rush-project.json */ projectOutputFolderNames: ReadonlyArray; /** * The project to be cached. */ project: RushConfigurationProject; /** * The hash of all relevant inputs and configuration that uniquely identifies this execution. */ operationStateHash: string; /** * The name of the phase that is being cached. */ phaseName: string; }; interface IPathsToCache { filteredOutputFolderNames: string[]; outputFilePaths: string[]; } let _tryCollectPathsToCacheForTestingAsync: | ((subject: OperationBuildCache, terminal: ITerminal) => Promise) | undefined; /** * Exercises output path collection through a unit-test-only module export. * @internal */ export async function _tryCollectPathsToCacheAsyncForTesting( subject: OperationBuildCache, terminal: ITerminal ): Promise { if (!_tryCollectPathsToCacheForTestingAsync) { throw new InternalError('OperationBuildCache test accessor was not initialized.'); } return await _tryCollectPathsToCacheForTestingAsync(subject, terminal); } function _getDirectFileTransferLockResourceName(cacheId: string): string { // LockFile resource names must match /^[a-zA-Z0-9][a-zA-Z0-9-.]+[a-zA-Z0-9]$/, but cacheId may // contain other characters (e.g. "/") depending on the configured cacheEntryNamePattern, so hash // it into a fixed-length, lock-file-safe token. return crypto.createHash('sha1').update(cacheId).digest('hex'); } let _tarUtilityPromise: Promise | undefined; function _getTempLocalCacheEntryPath(finalLocalCacheEntryPath: string): string { // Derive the temp file from the destination path to ensure they are on the same volume. // In the case of a shared network drive containing the build cache, we also need to make // sure the temp path won't be shared by two parallel rush builds. const randomSuffix: string = crypto.randomBytes(8).toString('hex'); return `${finalLocalCacheEntryPath}-${randomSuffix}.temp`; } function _tryGetTarUtility(terminal: ITerminal): Promise { if (!_tarUtilityPromise) { _tarUtilityPromise = TarExecutable.tryInitializeAsync(terminal); } return _tarUtilityPromise; } function _getCacheId(options: IProjectBuildCacheOptions): string | undefined { const { buildCacheConfiguration, project: { packageName }, operationStateHash, phaseName } = options; return buildCacheConfiguration.getCacheEntryId({ projectName: packageName, projectStateHash: operationStateHash, phaseName }); } /** * Overrides the cached `TarExecutable` promise. Exposed for unit testing only. * @internal */ export function _setTarUtilityPromiseForTesting( promise: Promise | undefined ): void { _tarUtilityPromise = promise; } /** * @internal */ export class OperationBuildCache { static { _tryCollectPathsToCacheForTestingAsync = async ( subject: OperationBuildCache, terminal: ITerminal ): Promise => await subject.#tryCollectPathsToCacheAsync(terminal); } readonly #project: RushConfigurationProject; readonly #localBuildCacheProvider: FileSystemBuildCacheProvider; readonly #cloudBuildCacheProvider: ICloudBuildCacheProvider | undefined; readonly #buildCacheEnabled: boolean; readonly #cacheWriteEnabled: boolean; readonly #projectOutputFolderNames: ReadonlyArray; readonly #cacheId: string | undefined; readonly #excludeAppleDoubleFiles: boolean; readonly #useDirectFileTransfersForBuildCache: boolean; readonly #receipt: OutputFolderReceipt | undefined; readonly #phaseName: string; private constructor( cacheId: string | undefined, options: IProjectBuildCacheOptions, receipt?: OutputFolderReceipt ) { const { buildCacheConfiguration: { localCacheProvider, cloudCacheProvider, buildCacheEnabled, cacheWriteEnabled }, project, projectOutputFolderNames, excludeAppleDoubleFiles, useDirectFileTransfersForBuildCache, phaseName } = options; this.#project = project; this.#localBuildCacheProvider = localCacheProvider; this.#cloudBuildCacheProvider = cloudCacheProvider; this.#buildCacheEnabled = buildCacheEnabled; this.#cacheWriteEnabled = cacheWriteEnabled; this.#projectOutputFolderNames = projectOutputFolderNames || []; this.#cacheId = cacheId; this.#excludeAppleDoubleFiles = excludeAppleDoubleFiles && process.platform === 'darwin'; this.#useDirectFileTransfersForBuildCache = useDirectFileTransfersForBuildCache; this.#receipt = receipt; this.#phaseName = phaseName; } public get cacheId(): string | undefined { return this.#cacheId; } public static getOperationBuildCache(options: IProjectBuildCacheOptions): OperationBuildCache { const cacheId: string | undefined = _getCacheId(options); return new OperationBuildCache(cacheId, options); } public static forOperation( executionResult: IBaseOperationExecutionResult, options: IOperationBuildCacheOptions ): OperationBuildCache { const { buildCacheConfiguration, terminal, excludeAppleDoubleFiles, useDirectFileTransfersForBuildCache } = options; const outputFolders: string[] = [...(executionResult.operation.settings?.outputFolderNames ?? [])]; if (executionResult.metadataFolderPath) { outputFolders.push(executionResult.metadataFolderPath); } const buildCacheOptions: IProjectBuildCacheOptions = { buildCacheConfiguration, terminal, project: executionResult.operation.associatedProject, phaseName: executionResult.operation.associatedPhase.name, projectOutputFolderNames: outputFolders, operationStateHash: executionResult.getStateHash(), excludeAppleDoubleFiles, useDirectFileTransfersForBuildCache }; const cacheId: string | undefined = _getCacheId(buildCacheOptions); // Only an operation's own build cache has a receipt, because the receipt is kept per operation. const receipt: OutputFolderReceipt | undefined = OutputFolderReceipt.tryCreate({ projectFolder: buildCacheOptions.project.projectFolder, projectRushTempFolder: buildCacheOptions.project.projectRushTempFolder, logFilenameIdentifier: executionResult.operation.logFilenameIdentifier, outputFolderNames: outputFolders }); return new OperationBuildCache(cacheId, buildCacheOptions, receipt); } public async tryRestoreFromCacheAsync(terminal: ITerminal, specifiedCacheId?: string): Promise { const cacheId: string | undefined = specifiedCacheId || this.#cacheId; if (!cacheId) { terminal.writeWarningLine('Unable to get cache ID. Ensure Git is installed.'); return false; } if (!this.#buildCacheEnabled) { // Skip reading local and cloud build caches, without any noise return false; } let localCacheEntryPath: string | undefined = await this.#localBuildCacheProvider.tryGetCacheEntryPathByIdAsync(terminal, cacheId); if ( localCacheEntryPath && (await this.#tryReceiptActionAsync(terminal, 'read', (receipt: OutputFolderReceipt) => receipt.isMatchAsync(cacheId) )) ) { terminal.writeLine('Build cache hit.'); terminal.writeVerboseLine(`Cache key: ${cacheId}`); terminal.writeLine('The output folders already match this cache entry; nothing to restore.'); return true; } let cloudCacheHit: boolean = false; let updateLocalCacheSuccess: boolean | undefined; if (!localCacheEntryPath && this.#cloudBuildCacheProvider) { terminal.writeVerboseLine( 'This project was not found in the local build cache. Querying the cloud build cache.' ); if ( this.#useDirectFileTransfersForBuildCache && this.#cloudBuildCacheProvider.tryDownloadCacheEntryToFileAsync ) { // Use file-based path to avoid loading the entire cache entry into memory. // The provider downloads directly to a temp file that is atomically moved into place. const targetPath: string = this.#localBuildCacheProvider.getCacheEntryPath(cacheId); // If multiple local Rush processes race to restore the same cache entry (e.g. parallel // "rush build" invocations on the same machine or CI agent), avoid redundant downloads by // having later processes wait for the first one to finish, mirroring the pattern used for // installing the package manager (see InstallHelpers.ensureLocalPackageManagerAsync). This // is strictly a best-effort optimization: if the lock cannot be acquired (for example, // because it is held by a process on a different machine sharing a network cache folder, // where the lock's stale-holder detection cannot see across machines) we simply fall back // to downloading independently below. Correctness never depends on the lock, because // downloads always land in a uniquely-named temp file that is atomically renamed into // place. let downloadLock: LockFile | undefined; try { downloadLock = await LockFile.acquireAsync( path.dirname(targetPath), _getDirectFileTransferLockResourceName(cacheId), DIRECT_FILE_TRANSFER_LOCK_MAX_WAIT_MS ); } catch (e) { terminal.writeVerboseLine( `Unable to acquire the local download lock for cache entry "${cacheId}"; downloading independently: ${e}` ); } try { // Another process may have finished populating the cache entry while we were waiting // for the lock (or the lock may not have been acquired at all). if (await FileSystem.existsAsync(targetPath)) { cloudCacheHit = true; localCacheEntryPath = targetPath; updateLocalCacheSuccess = true; } else { const tempTargetPath: string = _getTempLocalCacheEntryPath(targetPath); try { const downloadedToTempFile: boolean = await this.#cloudBuildCacheProvider.tryDownloadCacheEntryToFileAsync( terminal, cacheId, tempTargetPath ); if (downloadedToTempFile) { await Async.runWithRetriesAsync({ action: () => FileSystem.moveAsync({ sourcePath: tempTargetPath, destinationPath: targetPath, overwrite: true }), maxRetries: 2, retryDelayMs: 500 }); cloudCacheHit = true; localCacheEntryPath = targetPath; updateLocalCacheSuccess = true; } } catch (e) { terminal.writeVerboseLine(`Failed to download cache entry to local cache: ${e}`); updateLocalCacheSuccess = false; } if (!cloudCacheHit) { // Clean up any partial file left by the failed or missed download so it isn't // mistaken for a valid cache entry on the next build. Providers may catch errors // internally and return false instead of throwing, leaving a partially written file. try { await FileSystem.deleteFileAsync(tempTargetPath); } catch { // Ignore cleanup errors (file may not have been created) } } } } finally { downloadLock?.release(); } } else { const cacheEntryBuffer: Buffer | undefined = await this.#cloudBuildCacheProvider.tryGetCacheEntryBufferByIdAsync(terminal, cacheId); if (cacheEntryBuffer) { cloudCacheHit = true; try { localCacheEntryPath = await this.#localBuildCacheProvider.trySetCacheEntryBufferAsync( terminal, cacheId, cacheEntryBuffer ); updateLocalCacheSuccess = true; } catch (e) { terminal.writeVerboseLine(`Failed to update local cache: ${e}`); updateLocalCacheSuccess = false; } } } } if (!localCacheEntryPath && !cloudCacheHit) { terminal.writeVerboseLine('This project was not found in the build cache.'); return false; } terminal.writeLine('Build cache hit.'); terminal.writeVerboseLine(`Cache key: ${cacheId}`); const projectFolderPath: string = this.#project.projectFolder; // The receipt describes the output folders, so it must not outlive them, even if the restore fails. await this.#tryReceiptActionAsync(terminal, 'delete', (receipt: OutputFolderReceipt) => receipt.deleteAsync() ); const tarUtility: TarExecutable | undefined = await _tryGetTarUtility(terminal); const logFilePath: string = this.#getTarLogFilePath(cacheId, 'untar'); let tarExitCode: number | undefined; if (tarUtility && localCacheEntryPath) { // Restoring through a staging folder never leaves a file that is in both the old outputs and the entry // missing, so a process that reads the outputs during the restore finds them. const archivePath: string = localCacheEntryPath; tarExitCode = await tryRestoreThroughStagingFolderAsync(terminal, { projectFolder: projectFolderPath, projectRushTempFolder: this.#project.projectRushTempFolder, outputFolderNames: this.#projectOutputFolderNames, untarAsync: (outputFolderPath: string) => tarUtility.tryUntarAsync({ archivePath, outputFolderPath, logFilePath }) }); } if (tarExitCode !== 0) { // Purge output folders terminal.writeVerboseLine(`Clearing cached folders: ${this.#projectOutputFolderNames.join(', ')}`); for (const outputFolderName of this.#projectOutputFolderNames) { await FileSystem.deleteFolderAsync(path.join(projectFolderPath, outputFolderName)); } if (tarUtility && localCacheEntryPath && tarExitCode === undefined) { tarExitCode = await tarUtility.tryUntarAsync({ archivePath: localCacheEntryPath, outputFolderPath: projectFolderPath, logFilePath }); } } let restoreSuccess: boolean = false; if (tarExitCode === 0) { restoreSuccess = true; terminal.writeLine('Successfully restored output from the build cache.'); await this.#tryWriteRestoredReceiptAsync(terminal, cacheId); } else if (tarExitCode !== undefined) { terminal.writeWarningLine( 'Unable to restore output from the build cache. ' + `See "${logFilePath}" for logs from the tar process.` ); } if (updateLocalCacheSuccess === false) { terminal.writeWarningLine('Unable to update the local build cache with data from the cloud cache.'); } return restoreSuccess; } /** * Writes the build cache entry for the output files of the operation. * * @param deferredCacheEntryWrites - If specified, the output files are sealed, and the entry is written from them * in the background, so that this resolves as soon as they are sealed. If they can't be sealed, the entry is * written before this resolves, as it is without this parameter. */ public async trySetCacheEntryAsync( terminal: ITerminal, specifiedCacheId?: string, deferredCacheEntryWrites?: DeferredCacheEntryWrites ): Promise { if (!this.#cacheWriteEnabled) { // Skip writing local and cloud build caches, without any noise return true; } const cacheId: string | undefined = specifiedCacheId || this.#cacheId; if (!cacheId) { terminal.writeWarningLine('Unable to get cache ID. Ensure Git is installed.'); return false; } // The stamp comes before the output folders are read, so a change to them while they are archived keeps the // receipt from being written. No receipt is written while an older write of this entry is pending: that write // would replace the entry that is written now, and the receipt would then describe outputs that the entry doesn't // hold. const isOlderWritePending: boolean = !!deferredCacheEntryWrites?.hasPendingWrite(cacheId); const pendingReceipt: PendingOutputFolderReceipt | undefined = isOlderWritePending ? undefined : await this.#tryBeginReceiptAsync(terminal); try { return await this.#trySetCacheEntryWithReceiptAsync( terminal, cacheId, pendingReceipt, deferredCacheEntryWrites ); } finally { await this.#tryDisposeReceiptAsync(terminal, pendingReceipt); } } async #trySetCacheEntryWithReceiptAsync( terminal: ITerminal, cacheId: string, pendingReceipt: PendingOutputFolderReceipt | undefined, deferredCacheEntryWrites: DeferredCacheEntryWrites | undefined ): Promise { const filesToCache: IPathsToCache | undefined = await this.#tryCollectPathsToCacheAsync(terminal); if (!filesToCache) { return false; } terminal.writeVerboseLine( `Caching build output folders: ${filesToCache.filteredOutputFolderNames.join(', ')}` ); // If tar can't be found, the write below fails at once, so that the operation reports it. if (deferredCacheEntryWrites && (await _tryGetTarUtility(terminal))) { // A restore consults the receipt only if the local cache has the entry, so a receipt for an entry that is not // written yet is never consulted if the write is dropped or fails. But an older entry for the same cache ID, // such as one that "rush rebuild" wrote, would be paired with these outputs until the write replaces it, or for // good if it doesn't. So if there is one, no receipt is written, and the next restore writes one. const canWriteReceipt: boolean = !!pendingReceipt && !(await this.#localBuildCacheProvider.tryGetCacheEntryPathByIdAsync(terminal, cacheId)); const sealStartTimeMs: number = performance.now(); const sealedOutputs: ISealedOutputs | undefined = await deferredCacheEntryWrites.trySealAsync({ commonTempFolder: this.#project.rushConfiguration.commonTempFolder, sourceFolderPath: this.#project.projectFolder, relativePaths: filesToCache.outputFilePaths, terminal }); if (sealedOutputs) { deferredCacheEntryWrites.enqueue({ cacheId, operationName: `${this.#project.packageName} (${this.#phaseName})`, sealedOutputs, writeAsync: async (writeTerminal: ITerminal, abortSignal: AbortSignal) => { const written: boolean = await this.#tryWriteCacheEntryAsync( writeTerminal, cacheId, filesToCache, undefined, { baseFolderPath: sealedOutputs.folderPath, abortSignal } ); if (!written) { return undefined; } const cacheEntryPath: string = this.#localBuildCacheProvider.getCacheEntryPath(cacheId); return (await FileSystem.getStatisticsAsync(cacheEntryPath)).size; } }); const { fileCount, byteCount, isSealing } = sealedOutputs; const files: string = `${fileCount} output ${fileCount === 1 ? 'file' : 'files'}`; const size: string = formatMegabytes(byteCount); const sealDurationMs: number = Math.round(performance.now() - sealStartTimeMs); if (isSealing) { terminal.writeLine( `Sealing ${files} (${size}) in the background after ${sealDurationMs} ms; the build cache entry ` + `is written once they're sealed.` ); } else { terminal.writeLine( `Sealed ${files} (${size}) in ${sealDurationMs} ms; writing the build cache entry in the background.` ); } terminal.writeVerboseLine(`Cache key: ${cacheId}`); if (canWriteReceipt) { // The receipt is written only if no output changed after the stamp, which was taken before the files were // sealed, so it describes the sealed files that the entry is written from. await this.#tryCommitReceiptAsync(terminal, pendingReceipt, cacheId, filesToCache.outputFilePaths); } return true; } } return await this.#tryWriteCacheEntryAsync(terminal, cacheId, filesToCache, pendingReceipt, undefined); } async #tryWriteCacheEntryAsync( terminal: ITerminal, cacheId: string, filesToCache: IPathsToCache, pendingReceipt: PendingOutputFolderReceipt | undefined, deferredWrite: { baseFolderPath: string; abortSignal: AbortSignal } | undefined ): Promise { let localCacheEntryPath: string | undefined; const tarUtility: TarExecutable | undefined = await _tryGetTarUtility(terminal); if (tarUtility) { const finalLocalCacheEntryPath: string = this.#localBuildCacheProvider.getCacheEntryPath(cacheId); const tempLocalCacheEntryPath: string = _getTempLocalCacheEntryPath(finalLocalCacheEntryPath); const logFilePath: string = this.#getTarLogFilePath(cacheId, 'tar'); const tarExitCode: number = await tarUtility.tryCreateArchiveFromProjectPathsAsync({ archivePath: tempLocalCacheEntryPath, paths: filesToCache.outputFilePaths, project: this.#project, logFilePath, baseFolderPath: deferredWrite?.baseFolderPath, abortSignal: deferredWrite?.abortSignal }); if (tarExitCode === 0) { // Move after the archive is finished so that if the process is interrupted we aren't left with an invalid file try { await Async.runWithRetriesAsync({ action: () => FileSystem.moveAsync({ sourcePath: tempLocalCacheEntryPath, destinationPath: finalLocalCacheEntryPath, overwrite: true }), maxRetries: 2, retryDelayMs: 500 }); } catch (moveError) { try { await FileSystem.deleteFileAsync(tempLocalCacheEntryPath); } catch (deleteError) { // Ignored } throw moveError; } localCacheEntryPath = finalLocalCacheEntryPath; await this.#tryCommitReceiptAsync(terminal, pendingReceipt, cacheId, filesToCache.outputFilePaths); } else { if (deferredWrite) { // A write in the background can be cut short, so it deletes its partial archive. await FileSystem.deleteFileAsync(tempLocalCacheEntryPath); } terminal.writeWarningLine( `"tar" exited with code ${tarExitCode} while attempting to create the cache entry. ` + `See "${logFilePath}" for logs from the tar process.` ); return false; } } else { terminal.writeWarningLine( `Unable to locate "tar". Please ensure that "tar" is on your PATH environment variable, or set the ` + `${EnvironmentVariableNames.RUSH_TAR_BINARY_PATH} environment variable to the full path to the "tar" binary.` ); return false; } let setCloudCacheEntryPromise: Promise | undefined; // Note that "writeAllowed" settings (whether in config or environment) always apply to // the configured CLOUD cache. If the cache is enabled, rush is always allowed to read from and // write to the local build cache. if (this.#cloudBuildCacheProvider?.isCacheWriteAllowed) { if (!localCacheEntryPath) { throw new InternalError('Expected the local cache entry path to be set.'); } if ( this.#useDirectFileTransfersForBuildCache && this.#cloudBuildCacheProvider.tryUploadCacheEntryFromFileAsync ) { // Use file-based upload to avoid loading the entire cache entry into memory. // The provider reads from the local cache file directly. setCloudCacheEntryPromise = this.#cloudBuildCacheProvider.tryUploadCacheEntryFromFileAsync( terminal, cacheId, localCacheEntryPath ); } else { const cacheEntryBuffer: Buffer = await FileSystem.readFileToBufferAsync(localCacheEntryPath); setCloudCacheEntryPromise = this.#cloudBuildCacheProvider.trySetCacheEntryBufferAsync( terminal, cacheId, cacheEntryBuffer ); } } const updateCloudCacheSuccess: boolean | undefined = (await setCloudCacheEntryPromise) ?? true; const success: boolean = updateCloudCacheSuccess && !!localCacheEntryPath; if (success) { terminal.writeLine('Successfully set cache entry.'); terminal.writeVerboseLine(`Cache key: ${cacheId}`); } else if (!localCacheEntryPath && updateCloudCacheSuccess) { terminal.writeWarningLine('Unable to set local cache entry.'); } else if (localCacheEntryPath && !updateCloudCacheSuccess) { terminal.writeWarningLine('Unable to set cloud cache entry.'); } else { terminal.writeWarningLine('Unable to set both cloud and local cache entries.'); } return success; } /** * Walks the declared output folders of the project and collects a list of files. * @returns The list of output files as project-relative paths, or `undefined` if a * symbolic link was encountered. */ async #tryCollectPathsToCacheAsync(terminal: ITerminal): Promise { const projectFolderPath: string = this.#project.projectFolder; const outputFilePaths: string[] = []; const queue: [string, string][] = []; const filteredOutputFolderNames: string[] = []; let hasSymbolicLinks: boolean = false; const excludeAppleDoubleFiles: boolean = this.#excludeAppleDoubleFiles; // Adds child directories to the queue, files to the path list, and bails on symlinks function processChildren(relativePath: string, diskPath: string, children: FolderItem[]): void { // When excluding AppleDouble files, build a set of sibling names so we can check // whether a companion file exists for each ._X file. let childNameSet: Set | undefined; if (excludeAppleDoubleFiles) { childNameSet = new Set(children.map(({ name }) => name)); } for (const child of children) { const childName: string = child.name; const childRelativePath: string = `${relativePath}/${childName}`; if (child.isSymbolicLink()) { terminal.writeError( `Unable to include "${childRelativePath}" in build cache. It is a symbolic link.` ); hasSymbolicLinks = true; } else if (child.isDirectory()) { queue.push([childRelativePath, `${diskPath}/${child.name}`]); } else { // Check for macOS AppleDouble files (._X pattern) that have a companion file if (childNameSet && childName.length > 2 && childName.startsWith('._')) { const companionName: string = childName.substring(2); if (childNameSet.has(companionName)) { terminal.writeVerboseLine(`Omitting AppleDouble file "${childRelativePath}" from build cache.`); continue; } } outputFilePaths.push(childRelativePath); } } } // Handle declared output folders. for (const outputFolder of this.#projectOutputFolderNames) { const diskPath: string = `${projectFolderPath}/${outputFolder}`; try { const children: FolderItem[] = await FileSystem.readFolderItemsAsync(diskPath); processChildren(outputFolder, diskPath, children); // The folder exists, record it filteredOutputFolderNames.push(outputFolder); } catch (error) { if (!FileSystem.isNotExistError(error as Error)) { throw error; } // If the folder does not exist, ignore it. } } for (const [relativePath, diskPath] of queue) { const children: FolderItem[] = await FileSystem.readFolderItemsAsync(diskPath); processChildren(relativePath, diskPath, children); } if (hasSymbolicLinks) { // Symbolic links do not round-trip safely. return undefined; } // Ensure stable output path order. outputFilePaths.sort(); return { outputFilePaths, filteredOutputFolderNames }; } #getTarLogFilePath(cacheId: string, mode: 'tar' | 'untar'): string { return path.join(this.#project.projectRushTempFolder, `${cacheId}.${mode}.log`); } // The stamp comes after the untar, so a change to the output folders after it keeps the receipt from being // written, or from matching later. async #tryWriteRestoredReceiptAsync(terminal: ITerminal, cacheId: string): Promise { const pendingReceipt: PendingOutputFolderReceipt | undefined = await this.#tryBeginReceiptAsync(terminal); try { await this.#tryCommitReceiptAsync(terminal, pendingReceipt, cacheId); } finally { await this.#tryDisposeReceiptAsync(terminal, pendingReceipt); } } async #tryBeginReceiptAsync(terminal: ITerminal): Promise { return await this.#tryReceiptActionAsync(terminal, 'write', (receipt: OutputFolderReceipt) => receipt.beginAsync() ); } async #tryCommitReceiptAsync( terminal: ITerminal, pendingReceipt: PendingOutputFolderReceipt | undefined, cacheId: string, archivedFilePaths?: ReadonlyArray ): Promise { if (pendingReceipt) { const reason: string | undefined = await this.#tryReceiptActionAsync(terminal, 'write', () => pendingReceipt.tryCommitAsync(cacheId, archivedFilePaths) ); if (reason) { terminal.writeVerboseLine(`Not writing a build cache receipt: ${reason}.`); } } } async #tryDisposeReceiptAsync( terminal: ITerminal, pendingReceipt: PendingOutputFolderReceipt | undefined ): Promise { await this.#tryReceiptActionAsync(terminal, 'clean up', async () => await pendingReceipt?.disposeAsync()); } // A receipt only saves work, so if it can't be read or written, the build cache works as it would without one. async #tryReceiptActionAsync( terminal: ITerminal, verb: 'read' | 'write' | 'delete' | 'clean up', action: (receipt: OutputFolderReceipt) => Promise ): Promise { const receipt: OutputFolderReceipt | undefined = this.#receipt; if (!receipt) { return undefined; } try { return await action(receipt); } catch (error) { terminal.writeVerboseLine(`Unable to ${verb} the build cache receipt "${receipt.filePath}": ${error}`); return undefined; } } }