-
Notifications
You must be signed in to change notification settings - Fork 11.9k
Expand file tree
/
Copy pathparallel-executor.mjs
More file actions
184 lines (162 loc) · 5.13 KB
/
parallel-executor.mjs
File metadata and controls
184 lines (162 loc) · 5.13 KB
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
/**
* @license
* Copyright Google LLC 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.dev/license
*/
import * as child_process from 'node:child_process';
import path from 'node:path';
import { stripVTControlCharacters } from 'node:util';
const initialStatusRegex = /Running (\d+) tests/;
async function main() {
const [runfilesDir, targetName, ...testArgs] = process.argv.slice(2);
const testEntrypoint = path.resolve(runfilesDir, '../', targetName);
const testWorkingDir = path.resolve(runfilesDir, '_main');
const tasks = [];
const progress = {};
tasks.push(
spawnTest(
'bash',
[testEntrypoint, ...testArgs],
{
cwd: testWorkingDir,
env: {
// Try to construct a pretty hermetic environment, as within Bazel.
PATH: process.env.PATH,
E2E_SHARD_TOTAL: process.env.E2E_SHARD_TOTAL,
E2E_SHARD_INDEX: process.env.E2E_SHARD_INDEX,
FORCE_COLOR: '0',
// Needed by `rules_js`
BAZEL_BINDIR: '.',
// Needed to run the E2E in a different temp path.
E2E_TEMP: process.env.E2E_TEMP,
// Using the `--glob` causes a bunch of issues due to path expansion in nested bash scripts.
TESTBRIDGE_TEST_ONLY: process.env.TESTBRIDGE_TEST_ONLY,
},
},
(s) => (progress[0] = s),
),
);
const printUpdate = () => {
console.error(`----`);
for (const [taskId, status] of Object.entries(progress)) {
const durationInMin = (Date.now() - status.startTime) / 1000 / 60;
console.error(
`Shard #${taskId}: stage ${status.state} | ` +
`${status.current}/${status.max} tests completed (${durationInMin.toFixed(2)}min)`,
);
}
};
const progressInterval = setInterval(printUpdate, 4000);
try {
const outputs = await Promise.all(tasks);
printUpdate();
for (const [idx, text] of outputs.entries()) {
console.log(`---------- ${idx} -----------`);
console.log(text);
}
console.error('');
console.error('Done! Passing');
} catch (e) {
if (e instanceof TestSpawnError) {
console.error(e.output);
console.error(e.message);
} else if (e instanceof Error) {
console.error(e.message, e.stack);
} else {
console.error(e);
}
console.error('Tests failed!');
process.exitCode = 1;
} finally {
clearInterval(progressInterval);
}
}
function spawnTest(cmd, args, options, reportStatus, startTime = Date.now(), testAttempts = 2) {
testAttempts -= 1;
const testProgressRegex = /Running test[^\(]+\((\d+) of/g;
return new Promise((resolve, reject) => {
let output = '';
let state = 'setup';
let current = 0;
let max = 0;
const proc = child_process.spawn(cmd, args, { ...options, stdio: 'pipe' });
const syncStatus = () => reportStatus({ current, max, state, startTime });
const restartTest = () => {
console.error(output);
console.error(`Test restarted due to failure.`);
resolve(spawnTest(cmd, args, options, reportStatus, startTime, testAttempts));
};
const onOutputChange = () => {
// Extract initial status (i.e. how many tests there are in this shard)
if (initialStatusRegex.test(output) && state === 'setup') {
max = Number(output.match(initialStatusRegex)[1]);
}
if (/Running initializer/.test(output) && state === 'setup') {
state = 'initializing';
}
if (/Running test/.test(output) && state === 'initializing') {
state = 'testing';
}
if (state === 'testing') {
const oldLastIndex = testProgressRegex.lastIndex;
const newMatch = testProgressRegex.exec(stripVTControlCharacters(output))?.[1];
// Do not advance the Regex, or more precisely, reset to index `0`.
if (newMatch === undefined) {
testProgressRegex.lastIndex = oldLastIndex;
} else {
current = Number(newMatch);
}
}
syncStatus();
};
proc.stdout.on('data', (data) => {
output += data;
onOutputChange();
});
proc.stderr.on('data', (data) => {
output += data;
onOutputChange();
});
proc.on('error', (err) => {
syncStatus();
// If this test failed and there are test attempts remaining, re-run.
if (testAttempts > 0) {
restartTest();
return;
}
reject(new TestSpawnError(err.message, output));
});
proc.on('close', (code, signal) => {
syncStatus();
if (code === 0 && signal === null) {
resolve(output);
} else {
if (testAttempts > 0) {
restartTest();
return;
}
reject(
new TestSpawnError(`Command failed with code: ${code} and signal ${signal}`, output),
);
}
});
// Report initial status, without knowing anything.
syncStatus();
});
}
class TestSpawnError extends Error {
/** @type {string} */
output;
constructor(message, output) {
super(message);
this.output = output;
}
}
try {
main();
} catch (e) {
console.error(e);
process.exitCode = 1;
}