-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathrun-benchmark-watch.ts
130 lines (117 loc) · 4.06 KB
/
run-benchmark-watch.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
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { BaseException, logging } from '@angular-devkit/core';
import { spawnSync } from 'child_process';
import { Observable, combineLatest, forkJoin, of, throwError } from 'rxjs';
import {
concatMap,
filter,
first,
reduce,
repeat,
retryWhen,
startWith,
take,
takeUntil,
tap,
throwIfEmpty,
timeout,
} from 'rxjs/operators';
import { Command } from './command';
import { MetricGroup } from './interfaces';
import { LocalMonitoredProcess } from './monitored-process';
import { MaximumRetriesExceeded, RunBenchmarkOptions } from './run-benchmark';
import { aggregateMetricGroups } from './utils';
export interface RunBenchmarkWatchOptions extends RunBenchmarkOptions {
watchMatcher: string;
watchTimeout?: number;
watchCommand: Command;
}
export function runBenchmarkWatch({
command, captures, reporters = [], iterations = 5, retries = 5, logger = new logging.NullLogger(),
watchMatcher, watchTimeout = 10000, watchCommand,
}: RunBenchmarkWatchOptions): Observable<MetricGroup[]> {
let successfulRuns = 0;
let failedRuns = 0;
const debugPrefix = () => `Run #${successfulRuns + 1}:`;
// Run the process and captures, wait for both to finish, and average out the metrics.
const monitoredProcess = new LocalMonitoredProcess(command, false);
const processFailed = new BaseException('Wrong exit code.');
// Gather stats until the stdout contains the matched text.
const stats$ = monitoredProcess.stats$.pipe(
takeUntil(monitoredProcess.stdout$.pipe(
first(stdout => stdout.toString().includes(watchMatcher)),
timeout(watchTimeout),
)),
);
return combineLatest([
monitoredProcess.run().pipe(
startWith(undefined),
tap(processExitCode => {
if (processExitCode !== undefined && processExitCode != command.expectedExitCode) {
logger.debug(`${debugPrefix()} exited with ${processExitCode} but `
+ `${command.expectedExitCode} was expected`);
throw processFailed;
}
}),
),
monitoredProcess.stdout$.pipe(
filter(stdout => stdout.toString().includes(watchMatcher)),
take(1),
),
]).pipe(
timeout(watchTimeout),
concatMap(() => {
const { cmd, cwd, args } = watchCommand;
failedRuns = 0;
return of(null)
.pipe(
tap(() => {
const { status, error } = spawnSync(cmd, args, { cwd });
monitoredProcess.resetElapsedTimer();
if (status != command.expectedExitCode) {
logger.debug(`${debugPrefix()} exited with ${status}\n${error?.message}`);
throw processFailed;
}
// Reset fail counter for this iteration.
failedRuns = 0;
}),
tap(() => logger.debug(`${debugPrefix()} starting`)),
concatMap(() => forkJoin(captures.map(capture => capture(stats$)))),
throwIfEmpty(() => new Error('Nothing was captured')),
tap(() => logger.debug(`${debugPrefix()} finished successfully`)),
tap(() => successfulRuns++),
repeat(iterations),
retryWhen(errors => errors
.pipe(concatMap(val => {
// Check if we're still within the retry threshold.
failedRuns++;
return failedRuns < retries ? of(val) : throwError(val);
})),
),
);
}),
retryWhen(errors => errors
.pipe(concatMap(val => {
// Check if we're still within the retry threshold.
failedRuns++;
if (failedRuns < retries) {
return of(val);
}
return throwError(
val === processFailed ?
new MaximumRetriesExceeded(retries) :
val,
);
})),
),
take(iterations),
reduce((acc, val) => acc.map((_, idx) => aggregateMetricGroups(acc[idx], val[idx]))),
tap(groups => reporters.forEach(reporter => reporter(command, groups))),
);
}