forked from microsoft/rushstack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OperationExecutionManager.ts
408 lines (358 loc) · 14.8 KB
/
OperationExecutionManager.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import {
type TerminalWritable,
StdioWritable,
TextRewriterTransform,
Colorize,
ConsoleTerminalProvider
} from '@rushstack/terminal';
import { StreamCollator, type CollatedTerminal, type CollatedWriter } from '@rushstack/stream-collator';
import { NewlineKind, Async, InternalError } from '@rushstack/node-core-library';
import {
AsyncOperationQueue,
type IOperationIteratorResult,
type IOperationSortFunction,
UNASSIGNED_OPERATION
} from './AsyncOperationQueue';
import type { Operation } from './Operation';
import { OperationStatus } from './OperationStatus';
import { type IOperationExecutionRecordContext, OperationExecutionRecord } from './OperationExecutionRecord';
import type { IExecutionResult } from './IOperationExecutionResult';
export interface IOperationExecutionManagerOptions {
quietMode: boolean;
debugMode: boolean;
parallelism: number;
changedProjectsOnly: boolean;
destination?: TerminalWritable;
beforeExecuteOperation?: (operation: OperationExecutionRecord) => Promise<OperationStatus | undefined>;
afterExecuteOperation?: (operation: OperationExecutionRecord) => Promise<void>;
onOperationStatusChanged?: (record: OperationExecutionRecord) => void;
beforeExecuteOperations?: (records: Map<Operation, OperationExecutionRecord>) => Promise<void>;
}
/**
* Format "======" lines for a shell window with classic 80 columns
*/
const ASCII_HEADER_WIDTH: number = 79;
const prioritySort: IOperationSortFunction = (
a: OperationExecutionRecord,
b: OperationExecutionRecord
): number => {
return a.criticalPathLength! - b.criticalPathLength!;
};
/**
* A class which manages the execution of a set of tasks with interdependencies.
* Initially, and at the end of each task execution, all unblocked tasks
* are added to a ready queue which is then executed. This is done continually until all
* tasks are complete, or prematurely fails if any of the tasks fail.
*/
export class OperationExecutionManager {
private readonly _changedProjectsOnly: boolean;
private readonly _executionRecords: Map<Operation, OperationExecutionRecord>;
private readonly _quietMode: boolean;
private readonly _parallelism: number;
private readonly _totalOperations: number;
private readonly _outputWritable: TerminalWritable;
private readonly _colorsNewlinesTransform: TextRewriterTransform;
private readonly _streamCollator: StreamCollator;
private readonly _terminal: CollatedTerminal;
private readonly _beforeExecuteOperation?: (
operation: OperationExecutionRecord
) => Promise<OperationStatus | undefined>;
private readonly _afterExecuteOperation?: (operation: OperationExecutionRecord) => Promise<void>;
private readonly _onOperationStatusChanged?: (record: OperationExecutionRecord) => void;
private readonly _beforeExecuteOperations?: (
records: Map<Operation, OperationExecutionRecord>
) => Promise<void>;
// Variables for current status
private _hasAnyFailures: boolean;
private _hasAnyNonAllowedWarnings: boolean;
private _completedOperations: number;
private _executionQueue: AsyncOperationQueue;
public constructor(operations: Set<Operation>, options: IOperationExecutionManagerOptions) {
const {
quietMode,
debugMode,
parallelism,
changedProjectsOnly,
beforeExecuteOperation,
afterExecuteOperation,
onOperationStatusChanged,
beforeExecuteOperations
} = options;
this._completedOperations = 0;
this._quietMode = quietMode;
this._hasAnyFailures = false;
this._hasAnyNonAllowedWarnings = false;
this._changedProjectsOnly = changedProjectsOnly;
this._parallelism = parallelism;
this._beforeExecuteOperation = beforeExecuteOperation;
this._afterExecuteOperation = afterExecuteOperation;
this._beforeExecuteOperations = beforeExecuteOperations;
this._onOperationStatusChanged = onOperationStatusChanged;
// TERMINAL PIPELINE:
//
// streamCollator --> colorsNewlinesTransform --> StdioWritable
//
this._outputWritable = options.destination || StdioWritable.instance;
this._colorsNewlinesTransform = new TextRewriterTransform({
destination: this._outputWritable,
normalizeNewlines: NewlineKind.OsDefault,
removeColors: !ConsoleTerminalProvider.supportsColor
});
this._streamCollator = new StreamCollator({
destination: this._colorsNewlinesTransform,
onWriterActive: this._streamCollator_onWriterActive
});
this._terminal = this._streamCollator.terminal;
// Convert the developer graph to the mutable execution graph
const executionRecordContext: IOperationExecutionRecordContext = {
streamCollator: this._streamCollator,
onOperationStatusChanged,
debugMode,
quietMode
};
let totalOperations: number = 0;
const executionRecords: Map<Operation, OperationExecutionRecord> = (this._executionRecords = new Map());
for (const operation of operations) {
const executionRecord: OperationExecutionRecord = new OperationExecutionRecord(
operation,
executionRecordContext
);
executionRecords.set(operation, executionRecord);
if (!executionRecord.runner.silent) {
// Only count non-silent operations
totalOperations++;
}
}
this._totalOperations = totalOperations;
for (const [operation, consumer] of executionRecords) {
for (const dependency of operation.dependencies) {
const dependencyRecord: OperationExecutionRecord | undefined = executionRecords.get(dependency);
if (!dependencyRecord) {
throw new Error(
`Operation "${consumer.name}" declares a dependency on operation "${dependency.name}" that is not in the set of operations to execute.`
);
}
consumer.dependencies.add(dependencyRecord);
dependencyRecord.consumers.add(consumer);
}
}
const executionQueue: AsyncOperationQueue = new AsyncOperationQueue(
this._executionRecords.values(),
prioritySort
);
this._executionQueue = executionQueue;
}
private _streamCollator_onWriterActive = (writer: CollatedWriter | undefined): void => {
if (writer) {
this._completedOperations++;
// Format a header like this
//
// ==[ @rushstack/the-long-thing ]=================[ 1 of 1000 ]==
// leftPart: "==[ @rushstack/the-long-thing "
const leftPart: string = Colorize.gray('==[') + ' ' + Colorize.cyan(writer.taskName) + ' ';
const leftPartLength: number = 4 + writer.taskName.length + 1;
// rightPart: " 1 of 1000 ]=="
const completedOfTotal: string = `${this._completedOperations} of ${this._totalOperations}`;
const rightPart: string = ' ' + Colorize.white(completedOfTotal) + ' ' + Colorize.gray(']==');
const rightPartLength: number = 1 + completedOfTotal.length + 4;
// middlePart: "]=================["
const twoBracketsLength: number = 2;
const middlePartLengthMinusTwoBrackets: number = Math.max(
ASCII_HEADER_WIDTH - (leftPartLength + rightPartLength + twoBracketsLength),
0
);
const middlePart: string = Colorize.gray(']' + '='.repeat(middlePartLengthMinusTwoBrackets) + '[');
this._terminal.writeStdoutLine('\n' + leftPart + middlePart + rightPart);
if (!this._quietMode) {
this._terminal.writeStdoutLine('');
}
}
};
/**
* Executes all operations which have been registered, returning a promise which is resolved when all the
* operations are completed successfully, or rejects when any operation fails.
*/
public async executeAsync(): Promise<IExecutionResult> {
this._completedOperations = 0;
const totalOperations: number = this._totalOperations;
if (!this._quietMode) {
const plural: string = totalOperations === 1 ? '' : 's';
this._terminal.writeStdoutLine(`Selected ${totalOperations} operation${plural}:`);
const nonSilentOperations: string[] = [];
for (const record of this._executionRecords.values()) {
if (!record.runner.silent) {
nonSilentOperations.push(record.name);
}
}
nonSilentOperations.sort();
for (const name of nonSilentOperations) {
this._terminal.writeStdoutLine(` ${name}`);
}
this._terminal.writeStdoutLine('');
}
this._terminal.writeStdoutLine(`Executing a maximum of ${this._parallelism} simultaneous processes...`);
const maxParallelism: number = Math.min(totalOperations, this._parallelism);
await this._beforeExecuteOperations?.(this._executionRecords);
// This function is a callback because it may write to the collatedWriter before
// operation.executeAsync returns (and cleans up the writer)
const onOperationCompleteAsync: (record: OperationExecutionRecord) => Promise<void> = async (
record: OperationExecutionRecord
) => {
try {
await this._afterExecuteOperation?.(record);
} catch (e) {
// Failed operations get reported here
const message: string | undefined = record.error?.message;
if (message) {
this._terminal.writeStderrLine('Unhandled exception: ');
this._terminal.writeStderrLine(message);
}
throw e;
}
this._onOperationComplete(record);
};
const onOperationStartAsync: (
record: OperationExecutionRecord
) => Promise<OperationStatus | undefined> = async (record: OperationExecutionRecord) => {
return await this._beforeExecuteOperation?.(record);
};
await Async.forEachAsync(
this._executionQueue,
async (operation: IOperationIteratorResult) => {
let record: OperationExecutionRecord | undefined;
/**
* If the operation is UNASSIGNED_OPERATION, it means that the queue is not able to assign a operation.
* This happens when some operations run remotely. So, we should try to get a remote executing operation
* from the queue manually here.
*/
if (operation === UNASSIGNED_OPERATION) {
// Pause for a few time
await Async.sleep(5000);
record = this._executionQueue.tryGetRemoteExecutingOperation();
} else {
record = operation;
}
if (!record) {
// Fail to assign a operation, start over again
return;
} else {
await record.executeAsync({
onStart: onOperationStartAsync,
onResult: onOperationCompleteAsync
});
}
},
{
concurrency: maxParallelism
}
);
const status: OperationStatus = this._hasAnyFailures
? OperationStatus.Failure
: this._hasAnyNonAllowedWarnings
? OperationStatus.SuccessWithWarning
: OperationStatus.Success;
return {
operationResults: this._executionRecords,
status
};
}
/**
* Handles the result of the operation and propagates any relevant effects.
*/
private _onOperationComplete(record: OperationExecutionRecord): void {
const { runner, name, status } = record;
const silent: boolean = runner.silent;
switch (status) {
/**
* This operation failed. Mark it as such and all reachable dependents as blocked.
*/
case OperationStatus.Failure: {
// Failed operations get reported, even if silent.
// Generally speaking, silent operations shouldn't be able to fail, so this is a safety measure.
const message: string | undefined = record.error?.message;
// This creates the writer, so don't do this globally
const { terminal } = record.collatedWriter;
if (message) {
terminal.writeStderrLine(message);
}
terminal.writeStderrLine(Colorize.red(`"${name}" failed to build.`));
const blockedQueue: Set<OperationExecutionRecord> = new Set(record.consumers);
for (const blockedRecord of blockedQueue) {
if (blockedRecord.status === OperationStatus.Waiting) {
// Now that we have the concept of architectural no-ops, we could implement this by replacing
// {blockedRecord.runner} with a no-op that sets status to Blocked and logs the blocking
// operations. However, the existing behavior is a bit simpler, so keeping that for now.
if (!blockedRecord.runner.silent) {
terminal.writeStdoutLine(`"${blockedRecord.name}" is blocked by "${name}".`);
}
blockedRecord.status = OperationStatus.Blocked;
this._executionQueue.complete(blockedRecord);
this._completedOperations++;
for (const dependent of blockedRecord.consumers) {
blockedQueue.add(dependent);
}
} else if (blockedRecord.status !== OperationStatus.Blocked) {
// It shouldn't be possible for operations to be in any state other than Waiting or Blocked
throw new InternalError(
`Blocked operation ${blockedRecord.name} is in an unexpected state: ${blockedRecord.status}`
);
}
}
this._hasAnyFailures = true;
break;
}
/**
* This operation was restored from the build cache.
*/
case OperationStatus.FromCache: {
if (!silent) {
record.collatedWriter.terminal.writeStdoutLine(
Colorize.green(`"${name}" was restored from the build cache.`)
);
}
break;
}
/**
* This operation was skipped via legacy change detection.
*/
case OperationStatus.Skipped: {
if (!silent) {
record.collatedWriter.terminal.writeStdoutLine(Colorize.green(`"${name}" was skipped.`));
}
break;
}
/**
* This operation intentionally didn't do anything.
*/
case OperationStatus.NoOp: {
if (!silent) {
record.collatedWriter.terminal.writeStdoutLine(Colorize.gray(`"${name}" did not define any work.`));
}
break;
}
case OperationStatus.Success: {
if (!silent) {
record.collatedWriter.terminal.writeStdoutLine(
Colorize.green(`"${name}" completed successfully in ${record.stopwatch.toString()}.`)
);
}
break;
}
case OperationStatus.SuccessWithWarning: {
if (!silent) {
record.collatedWriter.terminal.writeStderrLine(
Colorize.yellow(`"${name}" completed with warnings in ${record.stopwatch.toString()}.`)
);
}
this._hasAnyNonAllowedWarnings = this._hasAnyNonAllowedWarnings || !runner.warningsAreAllowed;
break;
}
}
if (record.status !== OperationStatus.RemoteExecuting) {
// If the operation was not remote, then we can notify queue that it is complete
this._executionQueue.complete(record);
}
}
}