// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. import * as crypto from 'node:crypto'; import * as path from 'node:path'; import { InternalError, NewlineKind, Sort, Executable } from '@rushstack/node-core-library'; import { CollatedTerminal, type CollatedWriter } from '@rushstack/stream-collator'; import { DiscardStdoutTransform, TextRewriterTransform, SplitterTransform, type TerminalWritable, type ITerminal, Terminal } from '@rushstack/terminal'; import { CollatedTerminalProvider } from '../../utilities/CollatedTerminalProvider'; import { OperationStatus, SUCCESS_STATUSES } from './OperationStatus'; import { CobuildLock, type ICobuildCompletedState } from '../cobuild/CobuildLock'; import { OperationBuildCache } from '../buildCache/OperationBuildCache'; import { type DeferredCacheEntryWrites, type IDeferredCacheEntryWritesReport, formatMegabytes } from '../buildCache/DeferredCacheEntryWrites'; import { RushConstants } from '../RushConstants'; import { RushProjectConfiguration } from '../../api/RushProjectConfiguration'; import { initializeProjectLogFilesAsync, getProjectLogFilePaths, type ILogFilePaths } from './ProjectLogWritable'; import type { CobuildConfiguration } from '../../api/CobuildConfiguration'; import { DisjointSet } from '../cobuild/DisjointSet'; import { PeriodicCallback } from './PeriodicCallback'; import { captureInputFilesState, hasUntrackedGitFiles, type IInputFilesState } from './InputFilesStatSignature'; import { getInputFilesChangeKindSinceSnapshotAsync, type InputFilesChangeKind } from './OperationInputFilesCheck'; import { EnvironmentConfiguration } from '../../api/EnvironmentConfiguration'; import { NullTerminalProvider } from '../../utilities/NullTerminalProvider'; import type { Operation } from './Operation'; import type { IOperationRunnerContext } from './IOperationRunner'; import type { RushConfigurationProject } from '../../api/RushConfigurationProject'; import type { IOperationGraphContext, IPhasedCommandPlugin, PhasedCommandHooks } from '../../pluginFramework/PhasedCommandHooks'; import type { IOperationGraph, IOperationGraphIterationOptions, IOperationGraphRequestResult } from './IOperationGraph'; import type { BuildCacheConfiguration } from '../../api/BuildCacheConfiguration'; import type { IConfigurableOperation, IOperationExecutionResult } from './IOperationExecutionResult'; import type { OperationExecutionRecord } from './OperationExecutionRecord'; import { CAPTURE_INPUT_FILES_STAGE, enableUnverifiedRetainedOperations, getVerifiedSkipStateHash, markInputFilesChecked, markResultUnverifiable, setTrustedStateHash } from './RetainedResultVerification'; import { getSnapshotStartTimeMs } from './OperationInputFilesCheck'; import type { IInputsSnapshot } from '../incremental/InputsSnapshot'; import { isBuildCacheReadSkipped, wasExecutedIncrementally } from './IncrementalExecutionState'; const PLUGIN_NAME: 'CacheablePhasedOperationPlugin' = 'CacheablePhasedOperationPlugin'; const PERIODIC_CALLBACK_INTERVAL_IN_SECONDS: number = 10; // Runs after the default-stage taps (e.g. PhasedOperationPlugin) have decided which operations to enable. const RE_ENABLE_UNTRUSTED_RESULTS_STAGE: number = 1; export interface IProjectDeps { files: { [filePath: string]: string }; arguments: string; } export interface IOperationBuildCacheContext { isCacheWriteAllowed: boolean; isCacheReadAllowed: boolean; operationBuildCache: OperationBuildCache | undefined; // Computed when first read, by getCacheDisabledReason. See the beforeExecuteIterationAsync tap. readonly cacheDisabledReason: string | undefined; // Replaced, like inputsSnapshot, snapshotStartTimeMs and inputFileHashes, when a request joins the iteration (see // the extendIteration tap), since it depends on the inputs snapshot getCacheDisabledReason: () => string | undefined; outputFolderNames: ReadonlyArray; cobuildLock: CobuildLock | undefined; // The id of the cluster contains the operation, used when acquiring cobuild lock cobuildClusterId: string | undefined; // Controls the log for the cache subsystem buildCacheTerminal: ITerminal | undefined; buildCacheTerminalWritable: TerminalWritable | undefined; periodicCallback: PeriodicCallback; cacheRestored: boolean; isCacheReadAttempted: boolean; // True if the outputs of this operation were produced by its incremental command in this iteration (see // IncrementalExecutionGuardPlugin), or if it executed against outputs of a dependency that were. Such outputs // can differ from those of the initial command, so neither they nor the outputs of their consumers are written // to the build cache. Unlike a blocked cache write, this does not stop a long-lived graph from trusting them. isIncrementalResult: boolean; // True if a dependency of this operation, or one of theirs, was skipped by an iteration of a long-lived graph (e.g. // the Rush daemon) that did not select it, while its retained result was trusted. The iteration did not verify its // outputs, which may have been edited in place, so neither the outputs of this operation nor those of its consumers // are written to the build cache, as in a run that does not select that dependency. If this operation executes, its // result is not trusted. If it is skipped, it keeps its trust, since its outputs were not built in this iteration. hasUnverifiedDependency: boolean; // The inputs snapshot that the state hash of the operation was computed from (the iteration's, or that of a request // that joined the iteration before the operation was dispatched), and the start of the window in which the tracked // input files may have changed after it read them (see getSnapshotStartTimeMs) inputsSnapshot: IInputsSnapshot; snapshotStartTimeMs: number; // The hashes of the tracked input files in that inputs snapshot inputFileHashes: ReadonlyMap; // The on-disk state of the tracked input files whose hashes produced the cache key, captured right before the // operation executes. Used to refuse cache writes, and to keep a long-lived graph from skipping the operation // later, if the inputs changed after the snapshot read them, until the operation has executed. inputFilesState?: IInputFilesState; } export interface ICacheableOperationPluginOptions { allowWarningsInSuccessfulBuild: boolean; buildCacheConfiguration: BuildCacheConfiguration; cobuildConfiguration: CobuildConfiguration | undefined; terminal: ITerminal; excludeAppleDoubleFiles: boolean; useDirectFileTransfersForBuildCache: boolean; /** * If specified, an operation completes once its output files are sealed, and its build cache entry is written * from them in the background. Ignored for cobuilds. */ deferredCacheEntryWrites?: DeferredCacheEntryWrites; } interface ITryGetOperationBuildCacheOptionsBase { buildCacheContext: IOperationBuildCacheContext; buildCacheConfiguration: BuildCacheConfiguration | undefined; terminal: ITerminal; excludeAppleDoubleFiles: boolean; useDirectFileTransfersForBuildCache: boolean; record: TRecord; } type ITryGetOperationBuildCacheOptions = ITryGetOperationBuildCacheOptionsBase; interface ITryGetLogOnlyOperationBuildCacheOptions extends ITryGetOperationBuildCacheOptionsBase { cobuildConfiguration: CobuildConfiguration; } export class CacheableOperationPlugin implements IPhasedCommandPlugin { #buildCacheContextByOperation: Map = new Map(); readonly #options: ICacheableOperationPluginOptions; #gitPathResolved: boolean = false; #gitPath: string | undefined; public constructor(options: ICacheableOperationPluginOptions) { this.#options = options; } #getGitPath(): string | undefined { if (!this.#gitPathResolved) { this.#gitPath = EnvironmentConfiguration.gitBinaryPath || Executable.tryResolve('git'); this.#gitPathResolved = true; } return this.#gitPath; } #isNewInput( newEntryPaths: ReadonlyArray, rootDirectory: string, projectFolder: string, outputFolderNames: ReadonlyArray, snapshotHashes: ReadonlyMap ): boolean { const gitPath: string | undefined = this.#getGitPath(); if (!gitPath) { // Without Git we cannot tell whether the new entries are ignored, so assume they are inputs. return true; } const outputFolderPaths: string[] = outputFolderNames.map((folderName: string) => path.resolve(projectFolder, folderName) ); return hasUntrackedGitFiles(gitPath, rootDirectory, newEntryPaths, outputFolderPaths, snapshotHashes); } public apply(hooks: PhasedCommandHooks): void { const { allowWarningsInSuccessfulBuild, buildCacheConfiguration, cobuildConfiguration, excludeAppleDoubleFiles, useDirectFileTransfersForBuildCache } = this.#options; // Other cobuild agents wait for an entry once its operation completes, so it must be written by then. const deferredCacheEntryWrites: DeferredCacheEntryWrites | undefined = cobuildConfiguration?.cobuildFeatureEnabled ? undefined : this.#options.deferredCacheEntryWrites; hooks.onGraphCreatedAsync.tap(PLUGIN_NAME, (graph: IOperationGraph, context: IOperationGraphContext) => { // The state hash at which each operation last completed successfully in an iteration of this graph // in which cache writes were allowed for it (i.e. no dependency had an unknown state). const trustedStateHashByOperation: Map = new Map(); // The trusted state hash of each operation whose trusted outputs are an incremental result, which must not // be written to the build cache, nor may the outputs of its consumers. const incrementalStateHashByOperation: Map = new Map(); graph.hooks.beforeDeleteResults.tap(PLUGIN_NAME, (operations: ReadonlySet) => { for (const operation of operations) { trustedStateHashByOperation.delete(operation); incrementalStateHashByOperation.delete(operation); } // Terminals and cobuild callbacks can retain the entire completed iteration, including other // projects' records. All of this scratch state is rebuilt by beforeExecuteIterationAsync. for (const cacheContext of this.#buildCacheContextByOperation.values()) { cacheContext.periodicCallback.stop(); cacheContext.buildCacheTerminalWritable?.close(); } this.#buildCacheContextByOperation.clear(); }); graph.hooks.configureIteration.tap( { name: PLUGIN_NAME, stage: RE_ENABLE_UNTRUSTED_RESULTS_STAGE }, ( currentStates: ReadonlyMap, lastStates: ReadonlyMap, iterationOptions: IOperationGraphIterationOptions ) => { // PhasedOperationPlugin re-verifies results that were built against unverified dependency outputs. // This also re-verifies results that are not trusted for other reasons, e.g. because their input files // changed while they were executing. Without cache writes, nothing is ever trusted. if (buildCacheConfiguration.cacheWriteEnabled && iterationOptions.inputsSnapshot) { // An operation that this iteration does not select blocks the cache writes of its consumers (see the // afterExecuteOperationAsync tap below), so running them again would not make them trusted either. const trustedStateHashBySelectedOperation: Map = new Map(); for (const [operation, stateHash] of trustedStateHashByOperation) { if (operation.enabled !== false) { trustedStateHashBySelectedOperation.set(operation, stateHash); } } enableUnverifiedRetainedOperations( currentStates, lastStates, trustedStateHashBySelectedOperation ); } } ); graph.hooks.beforeExecuteIterationAsync.tap( PLUGIN_NAME, ( recordByOperation: ReadonlyMap, iterationOptions: IOperationGraphIterationOptions ): undefined => { const { inputsSnapshot } = iterationOptions; if (!inputsSnapshot) { throw new Error( `Build cache is only supported if running in a Git repository. Either disable the build cache or run Rush in a Git repository.` ); } const { isIncrementalBuildAllowed, projectConfigurations } = context; const { cacheWriteEnabled } = buildCacheConfiguration; const snapshotStartTimeMs: number = getSnapshotStartTimeMs(inputsSnapshot); const disjointSet: DisjointSet | undefined = cobuildConfiguration?.cobuildFeatureEnabled ? new DisjointSet() : undefined; for (const [operation, record] of recordByOperation) { const { associatedProject, runner, settings: operationSettings } = operation; if (!runner) { return; } const outputFolderNames: string[] = [record.metadataFolderPath]; const configuredOutputFolderNames: string[] | undefined = operationSettings?.outputFolderNames; if (configuredOutputFolderNames) { for (const folderName of configuredOutputFolderNames) { outputFolderNames.push(folderName); } } disjointSet?.add(operation); const buildCacheContext: IOperationBuildCacheContext = { // Supports cache writes by default for initial operations. // Don't write during watch runs for performance reasons (and to avoid flooding the cache) isCacheWriteAllowed: cacheWriteEnabled, isCacheReadAllowed: isIncrementalBuildAllowed && iterationOptions.isIncrementalBuildAllowed !== false, operationBuildCache: undefined, outputFolderNames, get cacheDisabledReason(): string | undefined { return buildCacheContext.getCacheDisabledReason(); }, cobuildLock: undefined, cobuildClusterId: undefined, buildCacheTerminal: undefined, buildCacheTerminalWritable: undefined, periodicCallback: new PeriodicCallback({ interval: PERIODIC_CALLBACK_INTERVAL_IN_SECONDS * 1000 }), cacheRestored: false, isCacheReadAttempted: false, isIncrementalResult: false, hasUnverifiedDependency: false, ...readCacheInputs( operation, inputsSnapshot, snapshotStartTimeMs, projectConfigurations.get(associatedProject) ) }; // Upstream runners may mutate the property of build cache context for downstream runners this.#buildCacheContextByOperation.set(operation, buildCacheContext); } if (disjointSet) { clusterOperations(disjointSet, this.#buildCacheContextByOperation); for (const operationSet of disjointSet.getAllSets()) { if (cobuildConfiguration?.cobuildFeatureEnabled && cobuildConfiguration.cobuildContextId) { // Get a deterministic ordered array of operations, which is important to get a deterministic cluster id. const groupedOperations: Operation[] = Array.from(operationSet); Sort.sortBy(groupedOperations, (operation: Operation) => { return operation.name; }); // Generates cluster id, cluster id comes from the project folder and operation name of all operations in the same cluster. const hash: crypto.Hash = crypto.createHash('sha1'); for (const operation of groupedOperations) { const { associatedPhase: phase, associatedProject: project } = operation; hash.update(project.projectRelativeFolder); hash.update(RushConstants.hashDelimiter); hash.update(operation.name ?? phase.name); hash.update(RushConstants.hashDelimiter); } const cobuildClusterId: string = hash.digest('hex'); // Assign same cluster id to all operations in the same cluster. for (const record of groupedOperations) { const buildCacheContext: IOperationBuildCacheContext = this.#getBuildCacheContextByOperationOrThrow(record); buildCacheContext.cobuildClusterId = cobuildClusterId; } } } } } ); graph.hooks.extendIteration.tap( PLUGIN_NAME, ( changedRecords: ReadonlyMap, iterationOptions: IOperationGraphIterationOptions ): void => { const { inputsSnapshot } = iterationOptions; if (!inputsSnapshot) { return; } const snapshotStartTimeMs: number = getSnapshotStartTimeMs(inputsSnapshot); for (const operation of changedRecords.keys()) { const buildCacheContext: IOperationBuildCacheContext | undefined = this.#buildCacheContextByOperation.get(operation); if (buildCacheContext) { // Updated in place, since upstream operations may have updated other properties of the context. // The operation was not dispatched yet, so the tap at CAPTURE_INPUT_FILES_STAGE captures its input // files later, for the newer snapshot. Object.assign( buildCacheContext, readCacheInputs( operation, inputsSnapshot, snapshotStartTimeMs, context.projectConfigurations.get(operation.associatedProject) ) ); } } } ); graph.hooks.beforeExecuteOperationAsync.tapPromise( PLUGIN_NAME, async ( runnerContext: IOperationRunnerContext & IOperationExecutionResult ): Promise => { if (this.#buildCacheContextByOperation.size === 0) { return; } const buildCacheContext: IOperationBuildCacheContext | undefined = this.#getBuildCacheContextByOperation(runnerContext.operation); if (!buildCacheContext) { return; } const record: OperationExecutionRecord = runnerContext as OperationExecutionRecord; const { associatedProject: project, associatedPhase: phase, runner, _operationMetadataManager: operationMetadataManager, operation } = record; if (!record.enabled || !runner?.cacheable) { return; } const runBeforeExecute = async (): Promise => { if ( !buildCacheContext.buildCacheTerminal || buildCacheContext.buildCacheTerminalWritable?.isOpen === false ) { // The writable does not exist or has been closed, re-create one // eslint-disable-next-line require-atomic-updates buildCacheContext.buildCacheTerminal = await this.#createBuildCacheTerminalAsync({ record, buildCacheContext, buildCacheEnabled: buildCacheConfiguration?.buildCacheEnabled, rushProject: project, logFilenameIdentifier: operation.logFilenameIdentifier, quietMode: record.quietMode, debugMode: record.debugMode }); } const buildCacheTerminal: ITerminal = buildCacheContext.buildCacheTerminal; let operationBuildCache: OperationBuildCache | undefined = this.#tryGetOperationBuildCache({ buildCacheContext, buildCacheConfiguration, terminal: buildCacheTerminal, record, excludeAppleDoubleFiles, useDirectFileTransfersForBuildCache }); // Try to acquire the cobuild lock let cobuildLock: CobuildLock | undefined; if (cobuildConfiguration?.cobuildFeatureEnabled) { if ( cobuildConfiguration?.cobuildLeafProjectLogOnlyAllowed && operation.consumers.size === 0 && !operationBuildCache ) { // When the leaf project log only is allowed and the leaf project is build cache "disabled", try to get // a log files only project build cache operationBuildCache = await this.#tryGetLogOnlyOperationBuildCacheAsync({ buildCacheConfiguration, cobuildConfiguration, buildCacheContext, record, terminal: buildCacheTerminal, excludeAppleDoubleFiles, useDirectFileTransfersForBuildCache }); if (operationBuildCache) { buildCacheTerminal.writeVerboseLine( `Log files only build cache is enabled for the project "${project.packageName}" because the cobuild leaf project log only is allowed` ); } else { buildCacheTerminal.writeWarningLine( `Failed to get log files only build cache for the project "${project.packageName}"` ); } } cobuildLock = await this.#tryGetCobuildLockAsync({ buildCacheContext, operationBuildCache, cobuildConfiguration, packageName: project.packageName, phaseName: phase.name }); } // eslint-disable-next-line require-atomic-updates -- we are mutating the build cache context intentionally buildCacheContext.cobuildLock = cobuildLock; // If possible, we want to skip this operation -- either by restoring it from the // cache, if caching is enabled, or determining that the project // is unchanged (using the older incremental execution logic). These two approaches, // "caching" and "skipping", are incompatible, so only one applies. // // Note that "caching" and "skipping" take two different approaches // to tracking dependents: // // - For caching, "isCacheReadAllowed" is set if a project supports // incremental builds, and determining whether this project or a dependent // has changed happens inside the hashing logic. // const { error: errorLogPath } = getProjectLogFilePaths({ project, logFilenameIdentifier: operation.logFilenameIdentifier }); const restoreCacheAsync = async ( // TODO: Investigate if `operationBuildCacheForRestore` is always the same instance as `operationBuildCache` // above, and if it is, remove this parameter operationBuildCacheForRestore: OperationBuildCache | undefined, specifiedCacheId?: string ): Promise => { buildCacheContext.isCacheReadAttempted = true; const restoreFromCacheSuccess: boolean | undefined = await operationBuildCacheForRestore?.tryRestoreFromCacheAsync( buildCacheTerminal, specifiedCacheId ); if (restoreFromCacheSuccess) { buildCacheContext.cacheRestored = true; await runnerContext.runWithTerminalAsync( async (taskTerminal, terminalProvider) => { // Restore the original state of the operation without cache await operationMetadataManager?.tryRestoreAsync({ terminalProvider, terminal: buildCacheTerminal, errorLogPath, cobuildContextId: cobuildConfiguration?.cobuildContextId, cobuildRunnerId: cobuildConfiguration?.cobuildRunnerId }); }, { createLogFile: false } ); } return !!restoreFromCacheSuccess; }; // A runner that reuses outputs that it keeps in memory, e.g. a warm worker, can skip the read. const isCacheReadAllowed: boolean = buildCacheContext.isCacheReadAllowed && !isBuildCacheReadSkipped(record); if (cobuildLock) { // handling rebuilds. "rush rebuild" or "rush retest" command will save operations to // the build cache once completed, but does not retrieve them (since the "incremental" // flag is disabled). However, we still need a cobuild to be able to retrieve a finished // build from another cobuild in this case. const cobuildCompletedState: ICobuildCompletedState | undefined = await cobuildLock.getCompletedStateAsync(); if (cobuildCompletedState) { const { status, cacheId } = cobuildCompletedState; if (record.operation.settings?.allowCobuildWithoutCache) { // This should only be enabled if the experiment for cobuild orchestration is enabled. return status; } const restoreFromCacheSuccess: boolean = await restoreCacheAsync( cobuildLock.operationBuildCache, cacheId ); if (restoreFromCacheSuccess) { return status; } } else if (!buildCacheContext.isCacheReadAttempted && isCacheReadAllowed) { const restoreFromCacheSuccess: boolean = await restoreCacheAsync(operationBuildCache); if (restoreFromCacheSuccess) { return OperationStatus.FromCache; } } } else if (isCacheReadAllowed) { const restoreFromCacheSuccess: boolean = await restoreCacheAsync(operationBuildCache); if (restoreFromCacheSuccess) { return OperationStatus.FromCache; } } if ( buildCacheContext.isCacheWriteAllowed && !buildCacheContext.hasUnverifiedDependency && cobuildLock ) { const acquireSuccess: boolean = await cobuildLock.tryAcquireLockAsync(); if (acquireSuccess) { const { periodicCallback } = buildCacheContext; periodicCallback.addCallback(async () => { await cobuildLock?.renewLockAsync(); }); periodicCallback.start(); } else { setTimeout(() => { record.status = OperationStatus.Ready; }, 500); return OperationStatus.Executing; } } }; return await runBeforeExecute(); } ); // Captured in a late tap, after the taps that can skip the operation or restore it from the build cache, // so that the input files of an operation that does not execute are not read. graph.hooks.beforeExecuteOperationAsync.tap( { name: PLUGIN_NAME, stage: CAPTURE_INPUT_FILES_STAGE }, (record: IOperationRunnerContext & IOperationExecutionResult): undefined => { const buildCacheContext: IOperationBuildCacheContext | undefined = this.#buildCacheContextByOperation.get(record.operation); if ( !buildCacheContext || !record.enabled || !record.operation.runner?.cacheable || buildCacheContext.cacheDisabledReason ) { return; } const { inputsSnapshot, inputFileHashes, snapshotStartTimeMs } = buildCacheContext; // Captured even if cache writes are disabled, since a long-lived graph (e.g. the Rush daemon) must not // retain outputs that were built from input files that changed after the inputs snapshot read them. buildCacheContext.inputFilesState = captureInputFilesState( inputsSnapshot.rootDirectory, inputFileHashes.keys(), snapshotStartTimeMs ); // The input files are checked after the operation executes, so IncrementalExecutionGuardPlugin need not. markInputFilesChecked(record); } ); graph.hooks.afterExecuteOperationAsync.tapPromise( PLUGIN_NAME, async (runnerContext: IOperationRunnerContext): Promise => { const record: OperationExecutionRecord = runnerContext as OperationExecutionRecord; const { status, stopwatch, _operationMetadataManager: operationMetadataManager, operation } = record; const { associatedProject: project, runner } = operation; if (!record.enabled || !runner?.cacheable) { return; } const buildCacheContext: IOperationBuildCacheContext | undefined = this.#getBuildCacheContextByOperation(operation); if (!buildCacheContext) { return; } // No need to run for the following operation status if (!record.isTerminal || record.status === OperationStatus.NoOp) { return; } const ranIncrementalCommand: boolean = !buildCacheContext.cacheRestored && wasExecutedIncrementally(record); if (ranIncrementalCommand) { buildCacheContext.isIncrementalResult = true; } const { cobuildLock, operationBuildCache, isCacheWriteAllowed: isCacheWriteAllowedForOperation, isIncrementalResult, hasUnverifiedDependency, buildCacheTerminal, cacheRestored } = buildCacheContext; const isCacheWriteAllowed: boolean = isCacheWriteAllowedForOperation && !isIncrementalResult && !hasUnverifiedDependency; try { if (!cacheRestored) { // Save the metadata to disk const { logFilenameIdentifier } = operationMetadataManager; const { duration: durationInSeconds } = stopwatch; const { text: logPath, error: errorLogPath, jsonl: logChunksPath } = getProjectLogFilePaths({ project, logFilenameIdentifier }); await operationMetadataManager.saveAsync({ durationInSeconds, cobuildContextId: cobuildLock?.cobuildConfiguration.cobuildContextId, cobuildRunnerId: cobuildLock?.cobuildConfiguration.cobuildRunnerId, logPath, errorLogPath, logChunksPath }); } if (!buildCacheTerminal) { // This should not happen throw new InternalError(`Build Cache Terminal is not created`); } if (ranIncrementalCommand && isCacheWriteAllowedForOperation) { buildCacheTerminal.writeLine( 'This operation ran its incremental command; not writing a build cache entry.' ); } let setCompletedStatePromiseFunction: (() => Promise | undefined) | undefined; let setCacheEntryPromise: (() => Promise | undefined) | undefined; if (cobuildLock && isCacheWriteAllowed) { const { cacheId, contextId } = cobuildLock.cobuildContext; let finalCacheId: string = cacheId; if (status === OperationStatus.Failure) { finalCacheId = `${cacheId}-${contextId}-failed`; } else if (status === OperationStatus.SuccessWithWarning && !record.runner.warningsAreAllowed) { finalCacheId = `${cacheId}-${contextId}-warnings`; } switch (status) { case OperationStatus.SuccessWithWarning: case OperationStatus.Success: case OperationStatus.Failure: { const currentStatus: ICobuildCompletedState['status'] = status; setCompletedStatePromiseFunction = () => { return cobuildLock?.setCompletedStateAsync({ status: currentStatus, cacheId: finalCacheId }); }; setCacheEntryPromise = () => cobuildLock.operationBuildCache.trySetCacheEntryAsync(buildCacheTerminal, finalCacheId); } } } const taskIsSuccessful: boolean = status === OperationStatus.Success || (status === OperationStatus.SuccessWithWarning && record.runner.warningsAreAllowed && allowWarningsInSuccessfulBuild); // If the command is successful, we can calculate project hash, and no dependencies were skipped, // write a new cache entry. if (!setCacheEntryPromise && taskIsSuccessful && isCacheWriteAllowed && operationBuildCache) { setCacheEntryPromise = () => operationBuildCache.trySetCacheEntryAsync( buildCacheTerminal, undefined, deferredCacheEntryWrites ); } const { inputFilesState, inputFileHashes, inputsSnapshot } = buildCacheContext; let inputFilesChangedMessage: string | undefined; if (!cacheRestored && inputFilesState) { const { outputFolderNames } = buildCacheContext; const inputFilesChangeKind: InputFilesChangeKind = await getInputFilesChangeKindSinceSnapshotAsync({ inputFilesState, snapshotHashes: inputFileHashes, getGitPath: () => this.#getGitPath(), isNewInput: (newEntryPaths: ReadonlyArray) => this.#isNewInput( newEntryPaths, inputFilesState.rootDirectory, project.projectFolder, outputFolderNames, inputsSnapshot.hashes ) }); if (inputFilesChangeKind === 'file-state') { inputFilesChangedMessage = 'Input files changed after the inputs snapshot was taken; not writing a build cache entry.'; } else if (inputFilesChangeKind === 'snapshot-hashes') { inputFilesChangedMessage = 'Input files changed after Git hashed them for the inputs snapshot; not writing a build cache entry.'; } } if (inputFilesChangedMessage) { // The cache key was derived from the iteration's inputs snapshot. Storing outputs produced from // edited inputs under that key would poison the cache for every consumer of the entry. // Consumers' cache keys also embed this operation's pre-edit state, so block their writes too. if (isCacheWriteAllowed) { buildCacheTerminal.writeLine(inputFilesChangedMessage); } buildCacheContext.isCacheWriteAllowed = false; setCacheEntryPromise = undefined; // For the same reason, a long-lived graph must not skip this operation, or the consumers built against // its outputs, while the state hash is unchanged, whether or not cache writes are enabled. markResultUnverifiable(record); } if (!cacheRestored) { const cacheWriteSuccess: boolean | undefined = await setCacheEntryPromise?.(); await setCompletedStatePromiseFunction?.(); if (cacheWriteSuccess === false && status === OperationStatus.Success) { record.status = OperationStatus.SuccessWithWarning; } } } finally { buildCacheContext.buildCacheTerminalWritable?.close(); buildCacheContext.periodicCallback.stop(); } } ); graph.hooks.afterExecuteOperationAsync.tap( PLUGIN_NAME, (record: IOperationRunnerContext & IOperationExecutionResult): void => { const { operation } = record; const buildCacheContext: IOperationBuildCacheContext | undefined = this.#buildCacheContextByOperation.get(operation); // Status changes to direct dependents let blockCacheWrite: boolean = !buildCacheContext?.isCacheWriteAllowed; // Whether the outputs that consumers execute against are an incremental result let isIncrementalResult: boolean = false; // Whether consumers execute against outputs that this iteration did not verify let hasUnverifiedOutputs: boolean = !!buildCacheContext?.hasUnverifiedDependency; switch (record.status) { case OperationStatus.Skipped: { // Skipping generally means we cannot guarantee integrity, so prevent cache writes in dependents. // The exceptions are an operation that was not re-run because a previous iteration of this graph // produced a trusted result at exactly the same state hash (e.g. a result retained by a // long-lived graph such as the Rush daemon), and an operation that a plugin skipped because it // verified that the outputs are those of the build cache entry at exactly this state hash (see // markSkipVerified). Since the state hash of an operation covers the state hashes of all of its // dependencies, a consumer's cache key fully describes this input. if (!blockCacheWrite && getVerifiedSkipStateHash(record) === record.getStateHash()) { // Trusted as if the outputs were restored from that build cache entry. trustedStateHashByOperation.set(operation, record.getStateHash()); incrementalStateHashByOperation.delete(operation); setTrustedStateHash(record, record.getStateHash()); } else if ( blockCacheWrite || trustedStateHashByOperation.get(operation) !== record.getStateHash() ) { blockCacheWrite = true; trustedStateHashByOperation.delete(operation); incrementalStateHashByOperation.delete(operation); } else { isIncrementalResult = incrementalStateHashByOperation.get(operation) === record.getStateHash(); // Output files are not part of the state hash, and only the outputs of selected operations are // checked (e.g. by the Rush daemon), so those of an operation that this iteration did not select // may have been edited in place since. As in a run that does not select it, its consumers do not // write to the build cache, but it keeps its trust for later iterations that select it. if (operation.enabled === false && !operation.isNoOp) { hasUnverifiedOutputs = true; } } break; } default: { // Outputs restored from the build cache are those of the initial command. isIncrementalResult = record.status !== OperationStatus.FromCache && (!!buildCacheContext?.isIncrementalResult || wasExecutedIncrementally(record)); if (hasUnverifiedOutputs && record.status !== OperationStatus.FromCache && !operation.isNoOp) { // The outputs of this operation may embed unverified outputs of its dependencies. blockCacheWrite = true; } if (!blockCacheWrite && buildCacheContext && SUCCESS_STATUSES.has(record.status)) { // The outputs of this operation were produced (or restored) in an iteration where cache // writes were allowed, so they can be trusted by consumers in later iterations as long as // the state hash is unchanged. An incremental result is trusted too, but it still blocks the // cache writes of consumers. trustedStateHashByOperation.set(operation, record.getStateHash()); if (isIncrementalResult) { incrementalStateHashByOperation.set(operation, record.getStateHash()); } else { incrementalStateHashByOperation.delete(operation); setTrustedStateHash(record, record.getStateHash()); } } else { trustedStateHashByOperation.delete(operation); incrementalStateHashByOperation.delete(operation); } break; } } // Apply status changes to direct dependents if (blockCacheWrite || isIncrementalResult || hasUnverifiedOutputs) { for (const consumer of operation.consumers) { const consumerBuildCacheContext: IOperationBuildCacheContext | undefined = this.#getBuildCacheContextByOperation(consumer); if (consumerBuildCacheContext) { if (blockCacheWrite) { consumerBuildCacheContext.isCacheWriteAllowed = false; } if (isIncrementalResult) { consumerBuildCacheContext.isIncrementalResult = true; } if (hasUnverifiedOutputs) { consumerBuildCacheContext.hasUnverifiedDependency = true; } } } } } ); graph.hooks.afterExecuteIterationAsync.tap(PLUGIN_NAME, (status: OperationStatus) => { this.#buildCacheContextByOperation.clear(); return status; }); if (deferredCacheEntryWrites) { graph.hooks.afterExecuteRequestAsync.tap( PLUGIN_NAME, ({ terminal }: IOperationGraphRequestResult): void => { const report: IDeferredCacheEntryWritesReport = deferredCacheEntryWrites.takeReport(); const { queuedCount, writtenCount, writtenByteCount, failedCount, droppedCount, pendingCount } = report; if (queuedCount || writtenCount || failedCount || droppedCount || pendingCount) { // An entry is dropped only if an output file changed before it was sealed, or if the daemon stopped. const dropped: string = droppedCount ? `, ${droppedCount} dropped` : ''; const line: string = `Build cache entries written in the background since the previous command: ` + `${queuedCount} queued, ${writtenCount} written (${formatMegabytes(writtenByteCount)}), ` + `${failedCount} failed${dropped}; ${pendingCount} pending.`; if (failedCount) { // A failed write before the operation completes is a warning too. Output that shows only a // summary, such as the daemon client's agent output, still shows warnings. terminal.writeWarningLine(line); } else { terminal.writeLine(line); } } } ); } }); } #getBuildCacheContextByOperation(operation: Operation): IOperationBuildCacheContext | undefined { const buildCacheContext: IOperationBuildCacheContext | undefined = this.#buildCacheContextByOperation.get(operation); return buildCacheContext; } #getBuildCacheContextByOperationOrThrow(operation: Operation): IOperationBuildCacheContext { const buildCacheContext: IOperationBuildCacheContext | undefined = this.#getBuildCacheContextByOperation(operation); if (!buildCacheContext) { // This should not happen throw new InternalError(`Build cache context for operation ${operation.name} should be defined`); } return buildCacheContext; } #tryGetOperationBuildCache(options: ITryGetOperationBuildCacheOptions): OperationBuildCache | undefined { const { buildCacheConfiguration, buildCacheContext, terminal, record, excludeAppleDoubleFiles, useDirectFileTransfersForBuildCache } = options; if (!buildCacheContext.operationBuildCache) { const { cacheDisabledReason } = buildCacheContext; if (cacheDisabledReason && !record.operation.settings?.allowCobuildWithoutCache) { terminal.writeVerboseLine(cacheDisabledReason); return; } if (!buildCacheConfiguration) { // Unreachable, since this will have set `cacheDisabledReason`. return; } buildCacheContext.operationBuildCache = OperationBuildCache.forOperation(record, { buildCacheConfiguration, terminal, excludeAppleDoubleFiles, useDirectFileTransfersForBuildCache }); } return buildCacheContext.operationBuildCache; } // Get an OperationBuildCache only cache/restore log files async #tryGetLogOnlyOperationBuildCacheAsync( options: ITryGetLogOnlyOperationBuildCacheOptions ): Promise { const { buildCacheContext, buildCacheConfiguration, cobuildConfiguration, record, terminal, excludeAppleDoubleFiles, useDirectFileTransfersForBuildCache } = options; if (!buildCacheConfiguration?.buildCacheEnabled) { return; } const { outputFolderNames } = buildCacheContext; const hasher: crypto.Hash = crypto.createHash('sha1'); hasher.update(record.getStateHash()); if (cobuildConfiguration.cobuildContextId) { hasher.update( `${RushConstants.hashDelimiter}cobuildContextId=${cobuildConfiguration.cobuildContextId}` ); } hasher.update(`${RushConstants.hashDelimiter}logFilesOnly=1`); const operationStateHash: string = hasher.digest('hex'); const { associatedPhase, associatedProject } = record.operation; const operationBuildCache: OperationBuildCache = OperationBuildCache.getOperationBuildCache({ project: associatedProject, projectOutputFolderNames: outputFolderNames, buildCacheConfiguration, terminal, operationStateHash, phaseName: associatedPhase.name, excludeAppleDoubleFiles, useDirectFileTransfersForBuildCache }); buildCacheContext.operationBuildCache = operationBuildCache; return operationBuildCache; } async #tryGetCobuildLockAsync({ cobuildConfiguration, buildCacheContext, operationBuildCache, packageName, phaseName }: { cobuildConfiguration: CobuildConfiguration | undefined; buildCacheContext: IOperationBuildCacheContext; operationBuildCache: OperationBuildCache | undefined; packageName: string; phaseName: string; }): Promise { if (!buildCacheContext.cobuildLock) { if (operationBuildCache && cobuildConfiguration?.cobuildFeatureEnabled) { if (!buildCacheContext.cobuildClusterId) { // This should not happen throw new InternalError('Cobuild cluster id is not defined'); } buildCacheContext.cobuildLock = new CobuildLock({ cobuildConfiguration, operationBuildCache, cobuildClusterId: buildCacheContext.cobuildClusterId, lockExpireTimeInSeconds: PERIODIC_CALLBACK_INTERVAL_IN_SECONDS * 3, packageName, phaseName }); } } return buildCacheContext.cobuildLock; } async #createBuildCacheTerminalAsync({ record, buildCacheContext, buildCacheEnabled, rushProject, logFilenameIdentifier, quietMode, debugMode }: { record: OperationExecutionRecord; buildCacheContext: IOperationBuildCacheContext; buildCacheEnabled: boolean | undefined; rushProject: RushConfigurationProject; logFilenameIdentifier: string; quietMode: boolean; debugMode: boolean; }): Promise { const silent: boolean = record.silent; if (silent) { const nullTerminalProvider: NullTerminalProvider = new NullTerminalProvider(); return new Terminal(nullTerminalProvider); } let cacheConsoleWritable: TerminalWritable; // This creates the writer, only do this if necessary. const collatedWriter: CollatedWriter = record.collatedWriter; const cacheProjectLogWritable: TerminalWritable | undefined = await this.#tryGetBuildCacheTerminalWritableAsync({ buildCacheContext, buildCacheEnabled, rushProject, logFilenameIdentifier }); if (quietMode) { const discardTransform: DiscardStdoutTransform = new DiscardStdoutTransform({ destination: collatedWriter }); const normalizeNewlineTransform: TextRewriterTransform = new TextRewriterTransform({ destination: discardTransform, normalizeNewlines: NewlineKind.Lf, ensureNewlineAtEnd: true }); cacheConsoleWritable = normalizeNewlineTransform; } else { cacheConsoleWritable = collatedWriter; } let cacheDestination: TerminalWritable; if (cacheProjectLogWritable) { cacheDestination = new SplitterTransform({ destinations: [cacheConsoleWritable, cacheProjectLogWritable] }); } else { cacheDestination = cacheConsoleWritable; } const cacheCollatedTerminal: CollatedTerminal = new CollatedTerminal( record.addOperationChunkTap(cacheDestination) ); const buildCacheTerminalProvider: CollatedTerminalProvider = new CollatedTerminalProvider( cacheCollatedTerminal, { debugEnabled: debugMode } ); return new Terminal(buildCacheTerminalProvider); } async #tryGetBuildCacheTerminalWritableAsync({ buildCacheEnabled, rushProject, buildCacheContext, logFilenameIdentifier }: { buildCacheEnabled: boolean | undefined; rushProject: RushConfigurationProject; buildCacheContext: IOperationBuildCacheContext; logFilenameIdentifier: string; }): Promise { // Only open the *.cache.log file(s) if the cache is enabled. if (!buildCacheEnabled) { return; } const logFilePaths: ILogFilePaths = getProjectLogFilePaths({ project: rushProject, logFilenameIdentifier: `${logFilenameIdentifier}.cache` }); buildCacheContext.buildCacheTerminalWritable = await initializeProjectLogFilesAsync({ logFilePaths }); return buildCacheContext.buildCacheTerminalWritable; } } export function clusterOperations( initialClusters: DisjointSet, operationBuildCacheMap: Map ): void { // If disjoint set exists, connect build cache disabled project with its consumers for (const [operation, { cacheDisabledReason }] of operationBuildCacheMap) { if (cacheDisabledReason && !operation.settings?.allowCobuildWithoutCache) { /** * Group the project build cache disabled with its consumers. This won't affect too much in * a monorepo with high build cache coverage. * * The mental model is that if X disables the cache, and Y depends on X, then: * 1. Y must be built by the same VM that build X; * 2. OR, Y must be rebuilt on each VM that needs it. * Approach 1 is probably the better choice. */ for (const consumer of operation.consumers) { initialClusters?.union(operation, consumer); } } } } /** * Reads the parts of the build cache context of an operation that depend on the inputs snapshot. */ function readCacheInputs( operation: Operation, inputsSnapshot: IInputsSnapshot, snapshotStartTimeMs: number, projectConfiguration: RushProjectConfiguration | undefined ): Pick< IOperationBuildCacheContext, 'getCacheDisabledReason' | 'inputsSnapshot' | 'snapshotStartTimeMs' | 'inputFileHashes' > { const { name: phaseName } = operation.associatedPhase; // This value can *currently* be cached per-project, but in the future the list of files will vary // depending on the selected phase. const fileHashes: ReadonlyMap = inputsSnapshot.getTrackedFileHashesForOperation( operation.associatedProject, phaseName ); // Computing the reason checks each tracked file of the project, and an iteration of a long-lived graph // (e.g. the Rush daemon) holds every operation of the workspace. It is only read for the operations // that execute and for cobuild clustering, so it is computed once, when it is first read. let cacheDisabledReason: string | undefined; let isCacheDisabledReasonComputed: boolean = false; const getCacheDisabledReason = (): string | undefined => { if (!isCacheDisabledReasonComputed) { cacheDisabledReason = RushProjectConfiguration.getCacheDisabledReasonForProject({ projectConfiguration, trackedFileNames: fileHashes.keys(), phaseName, isNoOp: operation.isNoOp, project: operation.associatedProject, operationSettings: operation.settings }); isCacheDisabledReasonComputed = true; } return cacheDisabledReason; }; return { getCacheDisabledReason, inputsSnapshot, snapshotStartTimeMs, inputFileHashes: fileHashes }; }