// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. import type { Http2SecureServer } from 'node:http2'; import type { Server as HTTPSecureServer } from 'node:https'; import os from 'node:os'; import { type WebSocket, WebSocketServer, type MessageEvent } from 'ws'; import { Sort } from '@rushstack/node-core-library/lib/Sort'; import { type Operation, type IOperationExecutionResult, OperationStatus, type ILogFilePaths, type RushConfiguration, type IOperationGraph, type IOperationGraphIterationOptions } from '@rushstack/rush-sdk'; import { type ITerminalChunk, TerminalChunkKind, TerminalWritable } from '@rushstack/terminal'; import type { ReadableOperationStatus, ILogFileURLs, IOperationInfo, IOperationExecutionState, IWebSocketEventMessage, IRushSessionInfo, IWebSocketSyncEventMessage, IWebSocketBeforeExecuteEventMessage, IWebSocketAfterExecuteEventMessage, IWebSocketBatchStatusChangeEventMessage, IWebSocketCommandMessage, IWebSocketPassQueuedEventMessage, IWebSocketSyncOperationsEventMessage, IWebSocketTerminalChunkEventMessage, IWebSocketSyncGraphStateEventMessage } from './api.types'; import { PLUGIN_NAME } from './constants'; import type { IPhasedCommandHandlerOptions } from './types'; export type WebSocketServerUpgrader = (server: Http2SecureServer) => void; /** * Returns a string that identifies the repository, based on the Rush configuration and environment. * @param rushConfiguration - The Rush configuration object. * @returns A string identifier for the repository. */ export function getRepositoryIdentifier(rushConfiguration: RushConfiguration): string { const { env } = process; const { CODESPACE_NAME: codespaceName, GITHUB_USER: githubUserName } = env; if (codespaceName) { const usernamePrefix: string | undefined = githubUserName?.replace(/_|$/g, '-'); const startIndex: number = usernamePrefix && codespaceName.startsWith(usernamePrefix) ? usernamePrefix.length : 0; const endIndex: number = codespaceName.lastIndexOf('-'); const normalizedName: string = codespaceName.slice(startIndex, endIndex).replace(/-/g, ' '); return `Codespace "${normalizedName}"`; } return `${os.hostname()} - ${rushConfiguration.rushJsonFolder}`; } /** * @param logServePath - The base URL path where logs are being served. * @param packageName - The npm package name of the project. * @returns The base URL path for serving logs of the specified project. */ export function getLogServePathForProject(logServePath: string, packageName: string): string { return `${logServePath}/${packageName}`; } export class WebSocketTerminalWritable extends TerminalWritable { #webSockets: ReadonlySet; public constructor(webSockets: ReadonlySet) { super(); this.#webSockets = webSockets; } protected override onWriteChunk(chunk: ITerminalChunk): void { const message: IWebSocketTerminalChunkEventMessage = { event: 'terminal-chunk', kind: chunk.kind === TerminalChunkKind.Stderr ? 'stderr' : 'stdout', text: chunk.text }; const stringifiedMessage: string = JSON.stringify(message); for (const ws of this.#webSockets) { ws.send(stringifiedMessage); } } } /** * If the `buildStatusWebSocketPath` option is configured, this function returns a `WebSocketServerUpgrader` callback * that can be used to add a WebSocket server to the HTTPS server. The WebSocket server sends messages * about operation status changes to connected clients. * */ export function tryEnableBuildStatusWebSocketServer( options: IPhasedCommandHandlerOptions ): WebSocketServerUpgrader | undefined { const { buildStatusWebSocketPath } = options; if (!buildStatusWebSocketPath) { return; } const operationStates: Map = new Map(); let buildStatus: ReadableOperationStatus = 'Ready'; const webSockets: Set = new Set(); // Map from OperationStatus enum values back to the names of the constants const readableStatusFromStatus: { [K in OperationStatus]: ReadableOperationStatus; } = { [OperationStatus.Waiting]: 'Waiting', [OperationStatus.Ready]: 'Ready', [OperationStatus.Queued]: 'Queued', [OperationStatus.Executing]: 'Executing', [OperationStatus.Success]: 'Success', [OperationStatus.SuccessWithWarning]: 'SuccessWithWarning', [OperationStatus.Skipped]: 'Skipped', [OperationStatus.FromCache]: 'FromCache', [OperationStatus.Failure]: 'Failure', [OperationStatus.Blocked]: 'Blocked', [OperationStatus.NoOp]: 'NoOp', [OperationStatus.Aborted]: 'Aborted' }; const { logServePath } = options; function convertToLogFileUrls( logFilePaths: ILogFilePaths | undefined, packageName: string ): ILogFileURLs | undefined { if (!logFilePaths || !logServePath) { return; } const projectLogServePath: string = getLogServePathForProject(logServePath, packageName); const logFileUrls: ILogFileURLs = { text: `${projectLogServePath}${logFilePaths.text.slice(logFilePaths.textFolder.length)}`, error: `${projectLogServePath}${logFilePaths.error.slice(logFilePaths.textFolder.length)}`, jsonl: `${projectLogServePath}${logFilePaths.jsonl.slice(logFilePaths.jsonlFolder.length)}` }; return logFileUrls; } /** * Maps the internal Rush record down to a subset that is JSON-friendly and human readable. */ function convertToOperationInfo(operation: Operation): IOperationInfo | undefined { const { name, associatedPhase, associatedProject, runner, enabled } = operation; if (!name || !runner) { return; } const { packageName } = associatedProject; return { name, dependencies: Array.from(operation.dependencies, (dep) => dep.name), packageName, phaseName: associatedPhase.name, enabled: enabled === false ? 'never' : enabled === 'ignore-dependency-changes' ? 'ignore-dependency-changes' : 'affected', silent: runner.silent, noop: !!runner.isNoOp }; } function convertToExecutionState(record: IOperationExecutionResult): IOperationExecutionState | undefined { const { operation } = record; const { name, associatedProject, runner } = operation; if (!name || !runner) return; const { packageName } = associatedProject; return { name, runInThisIteration: record.enabled, isActive: !!runner.isActive, status: readableStatusFromStatus[record.status], startTime: record.stopwatch.startTime, endTime: record.stopwatch.endTime, logFileURLs: convertToLogFileUrls(record.logFilePaths, packageName) }; } function convertToOperationInfoArray(operations: Iterable): IOperationInfo[] { const infos: IOperationInfo[] = []; for (const operation of operations) { const info: IOperationInfo | undefined = convertToOperationInfo(operation); if (info) { infos.push(info); } } Sort.sortBy(infos, (x) => x.name); return infos; } function convertToExecutionStateArray( records: Iterable ): IOperationExecutionState[] { const states: IOperationExecutionState[] = []; for (const record of records) { const state: IOperationExecutionState | undefined = convertToExecutionState(record); if (state) states.push(state); } Sort.sortBy(states, (x) => x.name); return states; } function sendWebSocketMessage(message: IWebSocketEventMessage): void { const stringifiedMessage: string = JSON.stringify(message); for (const socket of webSockets) { socket.send(stringifiedMessage); } } const { command } = options; const sessionInfo: IRushSessionInfo = { actionName: command.actionName, repositoryIdentifier: getRepositoryIdentifier(options.rushConfiguration) }; let lastGraph: IOperationGraph | undefined; // Operations that have been queued for an upcoming execution iteration (captured at queue time) let queuedStates: IOperationExecutionResult[] | undefined; function getGraphStateSnapshot(): IWebSocketSyncEventMessage['graphState'] | undefined { if (!lastGraph) return; return { parallelism: lastGraph.parallelism, debugMode: lastGraph.debugMode, verbose: !lastGraph.quietMode, pauseNextIteration: lastGraph.pauseNextIteration, status: buildStatus, hasScheduledIteration: lastGraph.hasScheduledIteration }; } function sendSyncMessage(webSocket: WebSocket): void { const records: Set = new Set(operationStates?.values() ?? []); const syncMessage: IWebSocketSyncEventMessage = { event: 'sync', operations: convertToOperationInfoArray(lastGraph?.operations ?? []), currentExecutionStates: convertToExecutionStateArray(records), queuedStates: queuedStates ? convertToExecutionStateArray(queuedStates) : undefined, sessionInfo, status: buildStatus, graphState: getGraphStateSnapshot() ?? { parallelism: 1, debugMode: false, verbose: true, pauseNextIteration: false, status: buildStatus, hasScheduledIteration: false }, resultByOperation: lastGraph ? convertToExecutionStateArray(lastGraph.resultByOperation.values()) : undefined }; webSocket.send(JSON.stringify(syncMessage)); } command.hooks.onGraphCreatedAsync.tap(PLUGIN_NAME, (graph, context) => { lastGraph = graph; const { hooks } = graph; graph.addTerminalDestination(new WebSocketTerminalWritable(webSockets)); hooks.beforeExecuteIterationAsync.tap( PLUGIN_NAME, ( operationsToExecute: ReadonlyMap, iterationOptions: IOperationGraphIterationOptions ): void => { // Clear queuedStates when the iteration begins executing queuedStates = undefined; for (const [operation, result] of operationsToExecute) { operationStates.set(operation.name, result); } const beforeExecuteMessage: IWebSocketBeforeExecuteEventMessage = { event: 'before-execute', executionStates: convertToExecutionStateArray(operationsToExecute.values()) }; buildStatus = 'Executing'; sendWebSocketMessage(beforeExecuteMessage); } ); hooks.afterExecuteIterationAsync.tap( PLUGIN_NAME, ( status: OperationStatus, operationResults: ReadonlyMap ): OperationStatus => { buildStatus = readableStatusFromStatus[status]; const states: IOperationExecutionState[] = convertToExecutionStateArray( operationResults.values() ?? [] ); const afterExecuteMessage: IWebSocketAfterExecuteEventMessage = { event: 'after-execute', executionStates: states, status: buildStatus, resultByOperation: lastGraph ? convertToExecutionStateArray(lastGraph.resultByOperation.values()) : undefined }; sendWebSocketMessage(afterExecuteMessage); return status; } ); // Batched operation state updates hooks.onExecutionStatesUpdated.tap( PLUGIN_NAME, (records: ReadonlySet): void => { const states: IOperationExecutionState[] = convertToExecutionStateArray(records.values()); const message: IWebSocketBatchStatusChangeEventMessage = { event: 'status-change', executionStates: states }; sendWebSocketMessage(message); } ); // Capture queued operations for next iteration hooks.onIterationScheduled.tap( PLUGIN_NAME, (queuedMap: ReadonlyMap): void => { queuedStates = Array.from(queuedMap.values()); const message: IWebSocketPassQueuedEventMessage = { event: 'iteration-scheduled', queuedStates: convertToExecutionStateArray(queuedStates) }; sendWebSocketMessage(message); } ); // Broadcast graph state changes hooks.onGraphStateChanged.tap(PLUGIN_NAME, () => { const graphState: IWebSocketSyncEventMessage['graphState'] | undefined = getGraphStateSnapshot(); if (graphState) { const message: IWebSocketSyncGraphStateEventMessage = { event: 'sync-graph-state', graphState }; sendWebSocketMessage(message); // Execution state may depend on graph properties, so broadcast states. } }); // Broadcast enabled state changes (full operations sync for simplicity) // When enable states change, emit a lightweight sync-operations message conveying the static graph changes. // The client will preserve existing dynamic state arrays. hooks.onEnableStatesChanged.tap(PLUGIN_NAME, () => { const operationsMessage: IWebSocketSyncOperationsEventMessage = { event: 'sync-operations', operations: convertToOperationInfoArray(lastGraph?.operations ?? []) }; sendWebSocketMessage(operationsMessage); }); }); const connector: WebSocketServerUpgrader = (server: Http2SecureServer) => { const wss: WebSocketServer = new WebSocketServer({ server: server as unknown as HTTPSecureServer, path: buildStatusWebSocketPath }); command.sessionAbortController.signal.addEventListener( 'abort', () => { wss.close(); webSockets.forEach((ws) => ws.close()); }, { once: true } ); function namesToOperations(operationNames?: string[]): Operation[] | undefined { if (!operationNames || !lastGraph) { return; } const operationNameSet: Set = new Set(operationNames); const namedOperations: Operation[] = []; for (const operation of lastGraph.operations) { if (operationNameSet.has(operation.name)) { namedOperations.push(operation); } } return namedOperations; } wss.addListener('connection', (webSocket: WebSocket): void => { webSockets.add(webSocket); sendSyncMessage(webSocket); // includes settings webSocket.addEventListener('message', (ev: MessageEvent) => { const parsedMessage: IWebSocketCommandMessage = JSON.parse(ev.data.toString()); switch (parsedMessage.command) { case 'sync': { sendSyncMessage(webSocket); break; } case 'set-enabled-states': { if (lastGraph) { const { operationNames, targetState, mode } = parsedMessage; const operations: Operation[] | undefined = namesToOperations(operationNames); if (operations && operations.length) { lastGraph.setEnabledStates( operations, targetState === 'ignore-dependency-changes' ? targetState : targetState !== 'never', mode ); } } break; } case 'invalidate': { const { operationNames } = parsedMessage; if (lastGraph) { const operations: Iterable | undefined = namesToOperations(operationNames); lastGraph.invalidateOperations(operations, 'manual-invalidation'); } break; } case 'abort-execution': { void lastGraph?.abortCurrentIterationAsync(); break; } case 'close-runners': { const { operationNames } = parsedMessage; if (lastGraph) { const operations: Operation[] | undefined = namesToOperations(operationNames); void lastGraph.closeRunnersAsync(operations); } break; } case 'execute': { if (lastGraph) { const definedExecutionManager: IOperationGraph = lastGraph; void definedExecutionManager.scheduleIterationAsync({}).then(() => { return definedExecutionManager.executeScheduledIterationAsync(); }); } break; } case 'set-debug': { if (lastGraph) lastGraph.debugMode = !!parsedMessage.value; break; } case 'set-verbose': { if (lastGraph) lastGraph.quietMode = !parsedMessage.value; // invert break; } case 'set-pause-next-iteration': { if (lastGraph && typeof parsedMessage.value === 'boolean') { lastGraph.pauseNextIteration = parsedMessage.value; } break; } case 'set-parallelism': { if (lastGraph && typeof parsedMessage.parallelism === 'number') { lastGraph.parallelism = parsedMessage.parallelism; } break; } case 'abort-session': { command.sessionAbortController.abort(); break; } default: { // Unknown message. Ignore. } } }); webSocket.addEventListener( 'close', () => { webSockets.delete(webSocket); }, { once: true } ); }); }; return connector; }