// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. import { execFileSync } from 'node:child_process'; import * as fs from 'node:fs'; import { Rush } from '@microsoft/rush-lib'; import { FileSystem } from '@rushstack/node-core-library'; import { DaemonFrameType, decodeDaemonEventFrame, RUSHD_GRAPH_SNAPSHOT, type IDaemonFrame, type IDaemonGraphSnapshotPayload, type IDaemonRequestEnvelope } from '@rushstack/rush-daemon-protocol'; import { ProductionDaemonRequestResolver } from '../ProductionDaemonRequestResolver'; import type { IDaemonRequestResolver } from '../DaemonRequestDispatcher'; import { RushDaemonHost } from '../RushDaemonHost'; import { RushDaemonRequestResolver } from '../RushDaemonRequestResolver'; import { WorkspaceSession } from '../WorkspaceSession'; import { getWorkspaceGenerationToken } from '../WorkspaceGeneration'; import type { GetWorkspaceSuccessorLaunchAsync } from '../WorkspaceProcessRestart'; import type { CheckDaemonInstallation } from '../DaemonInstallationMonitor'; import { createWireEnvelope, DaemonRequestWireClient, type ITerminalExchange } from './DaemonRequestWireTestUtilities'; import { assertSuccessfulNativeBuild } from './NativeBuildTestResult'; import { trackTestDaemonHostAsync } from './TestDaemonHostCleanup'; /** * How long a fixture script that waits for its test may run. Keep it longer than the timeout of every test that uses * it (60 s at most today). Each of these scripts runs in its own session (the daemon starts every operation that way), * so when a test never reaches the `finally` that releases its script (the test timed out, or its Jest worker exited * first), nothing else ends the script. */ export const FIXTURE_SCRIPT_DEADLINE_MS: number = 120_000; /** * Quotes `value` as a JavaScript string literal for fixture script source, escaping the characters that could end a * script or a string in the code around it. */ function stringifyForJavaScript(value: string): string { return JSON.stringify(value).replace(/[<>/\u2028\u2029]/g, (character: string) => { switch (character) { case '<': return '\\u003C'; case '>': return '\\u003E'; case '/': return '\\u002F'; case '\u2028': return '\\u2028'; case '\u2029': return '\\u2029'; } return character; }); } /** * Prefixes `script` with a timer that ends it with exit code 1 once `deadlineMs` has passed. Use it for every fixture * script that waits for a marker file its test writes or removes. The timer is unref'd, so a script that its test * released still exits as soon as it finishes. */ export function withScriptDeadline(script: string, deadlineMs: number = FIXTURE_SCRIPT_DEADLINE_MS): string { if (!Number.isSafeInteger(deadlineMs) || deadlineMs <= 0) { throw new RangeError(`Expected a positive whole number of milliseconds, not ${deadlineMs}.`); } const message: string = `fixture script: its test did not release it within ${deadlineMs} ms`; return `setTimeout(()=>{console.error(${stringifyForJavaScript(message)});process.exit(1);},${deadlineMs}).unref();${script}`; } export class DaemonGraphTestFixture implements AsyncDisposable { public session!: WorkspaceSession; public host!: RushDaemonHost; public getSuccessorLaunchAsync: GetWorkspaceSuccessorLaunchAsync | undefined; public checkInstallation: CheckDaemonInstallation | undefined; /** Every message the host wrote to its daemon log. */ public readonly logs: string[] = []; /** Awaited before each workspace session is created, including a request's graph load or reload. */ public beforeCreateSessionAsync: (() => Promise) | undefined; /** Awaited after each workspace session is created, before the host or the request that created it uses it. */ public afterCreateSessionAsync: (() => Promise) | undefined; /** Also serves rushx package scripts, like the production host. Set it in `createAsync`'s `configure`. */ public servesRushx: boolean = false; /** * Wraps the resolver that the host serves requests with. The wrapper also serves later generations if it keeps the * resolver's `workspaceLifecycle` (see `wrapWorkspaceResolverLifecycle`). Set it in `createAsync`'s `configure`. */ public wrapResolver: ((resolver: IDaemonRequestResolver) => IDaemonRequestResolver) | undefined; public readonly folder: string; public readonly environment: Record = { ...Object.fromEntries( Object.entries(process.env).filter((pair): pair is [string, string] => pair[1] !== undefined) ) }; #nextId: number = 0; #lifecycle: boolean = true; public constructor(root: string = `${__dirname}/../../temp/test/graph`) { FileSystem.ensureFolder(root); this.folder = FileSystem.getRealPath(fs.mkdtempSync(`${root}/case-`)); } public static async createAsync( configure?: (fixture: DaemonGraphTestFixture) => void, lifecycle: boolean = true, signal?: AbortSignal ): Promise { const fixture: DaemonGraphTestFixture = new DaemonGraphTestFixture(); fixture.#lifecycle = lifecycle; try { signal?.throwIfAborted(); FileSystem.copyFiles({ sourcePath: `${__dirname}/fixtures/graph`, destinationPath: fixture.folder }); FileSystem.move({ sourcePath: `${fixture.folder}/gitignore`, destinationPath: `${fixture.folder}/.gitignore` }); const rushJson: { rushVersion: string } = JSON.parse( FileSystem.readFile(`${fixture.folder}/rush.json`) ); rushJson.rushVersion = Rush.version; fixture.write('rush.json', JSON.stringify(rushJson)); fixture.write('common/temp/last-link.flag', '{}'); configure?.(fixture); signal?.throwIfAborted(); execFileSync('git', ['init', '--quiet'], { cwd: fixture.folder }); execFileSync('git', ['config', '--local', 'core.autocrlf', 'false'], { cwd: fixture.folder }); execFileSync('git', ['add', '.'], { cwd: fixture.folder }); execFileSync( 'git', [ // Don't start a detached `git maintenance` that could still be writing into .git during cleanup '-c', 'maintenance.auto=false', '-c', 'user.name=Graph Test', '-c', 'user.email=graph@example.invalid', 'commit', '--quiet', '-m', 'fixture' ], { cwd: fixture.folder } ); await fixture.#startAsync(); // Host startup owns its partial resources; join it before disposing a late result. signal?.throwIfAborted(); return fixture; } catch (error) { try { await fixture[Symbol.asyncDispose](); } catch (cleanupError) { throw new AggregateError( [error, cleanupError], 'Failed to initialize and dispose the graph fixture.' ); } throw error; } } async #startAsync(): Promise { const production: IDaemonRequestResolver = new ProductionDaemonRequestResolver(); const served: IDaemonRequestResolver = this.servesRushx ? new RushDaemonRequestResolver(production) : production; const resolver: IDaemonRequestResolver = this.wrapResolver?.(served) ?? served; this.host = await RushDaemonHost.startAsync({ repoRoot: this.folder, rushVersion: Rush.version, daemonVersion: 'graph-test', getSuccessorLaunchAsync: this.getSuccessorLaunchAsync, checkInstallation: this.checkInstallation, onLog: (message: string) => this.logs.push(message), requestResolver: this.#lifecycle ? resolver : { resolveRequestAsync: (options) => resolver.resolveRequestAsync(options), [Symbol.asyncDispose]: async () => { await resolver[Symbol.asyncDispose]?.(); } }, createWorkspaceSessionAsync: async (options) => { await this.beforeCreateSessionAsync?.(); this.session = await WorkspaceSession.createAsync(options); await this.afterCreateSessionAsync?.(); return this.session; } }); await trackTestDaemonHostAsync(this.host); } public async restartAsync(): Promise { await this.host.closeAsync(); await this.#startAsync(); } public write(name: string, text: string): void { FileSystem.writeFile(`${this.folder}/${name}`, text, { ensureFolderExists: true }); } public runs(): string[] { const filename: string = `${this.folder}/runs.txt`; return FileSystem.exists(filename) ? FileSystem.readFile(filename).trim().split('\n') : []; } public async connectAsync(): Promise { const client: DaemonRequestWireClient = await DaemonRequestWireClient.connectAsync( this.host.paths.socketPath ); await client.handshakeAsync(); return client; } public envelope(argv: string[], overrides: Partial = {}): IDaemonRequestEnvelope { return createWireEnvelope(`graph-${++this.#nextId}`, argv[0], this.folder, { argv, commandOrigin: 'built-in', expectedWorkspaceGeneration: argv[0] === 'daemon' ? getWorkspaceGenerationToken(this.session) : undefined, environment: argv[0] === 'daemon' ? { ...this.environment, RUSH_DAEMON_EXPERIMENTAL: '1' } : this.environment, terminal: { isTTY: false, supportsColor: false }, ...overrides }); } public async runAsync( argv: string[], overrides: Partial = {} ): Promise { const client: DaemonRequestWireClient = await this.connectAsync(); const payload: IDaemonRequestEnvelope = this.envelope(argv, overrides); try { await client.sendControlAsync({ kind: 'requestStart', payload }); return await client.readTerminalAsync(payload.requestId); } finally { await client.closeAsync(); } } public graphAsync(...argv: string[]): Promise { return this.runAsync(['daemon', 'graph', ...argv]); } public buildAsync(): Promise { return this.runAsync(['build', '--to', 'b', '--parallelism', '3']); } public async buildSuccessfullyAsync(): Promise { const exchange: ITerminalExchange = await this.buildAsync(); assertSuccessfulNativeBuild(exchange, this.session.operationGraph); return exchange; } public async [Symbol.asyncDispose](): Promise { await this.host?.closeAsync(); } } export function graphSnapshot(frame: IDaemonFrame): IDaemonGraphSnapshotPayload['snapshot'] { expect(frame.kind).toBe(DaemonFrameType.event); const event = decodeDaemonEventFrame(frame.payload); expect(event).toMatchObject({ type: 'extension', payload: { name: RUSHD_GRAPH_SNAPSHOT } }); const payload = event.payload as { data: IDaemonGraphSnapshotPayload }; return payload.data.snapshot; } export function responseSnapshot(exchange: ITerminalExchange): IDaemonGraphSnapshotPayload['snapshot'] { expect(exchange.terminal).toMatchObject({ kind: 'requestResult', payload: { exitCode: 0 } }); const events: IDaemonFrame[] = exchange.frames.filter((frame) => frame.kind === DaemonFrameType.event); expect(events).toHaveLength(1); expect( exchange.frames.some( (frame) => frame.kind === DaemonFrameType.logStdout || frame.kind === DaemonFrameType.logStderr ) ).toBe(false); return graphSnapshot(events[0]); }