@smoothbricks/nx-plugin 0.5.5 → 0.5.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +59 -11
- package/dist/ensure-built-receipt.d.ts +2 -2
- package/dist/ensure-built-receipt.d.ts.map +1 -1
- package/dist/ensure-built-receipt.js +7 -2
- package/dist/ensure-built-witness.d.ts +12 -1
- package/dist/ensure-built-witness.d.ts.map +1 -1
- package/dist/ensure-built-witness.js +32 -0
- package/dist/ensure-built.d.ts +2 -2
- package/dist/ensure-built.d.ts.map +1 -1
- package/dist/ensure-built.js +27 -5
- package/dist/executors/all-verdicts/executor.d.ts +35 -0
- package/dist/executors/all-verdicts/executor.d.ts.map +1 -0
- package/dist/executors/all-verdicts/executor.js +133 -0
- package/dist/executors/all-verdicts/schema.d.ts +10 -0
- package/dist/executors/all-verdicts/schema.d.ts.map +1 -0
- package/dist/executors/all-verdicts/schema.js +2 -0
- package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
- package/dist/executors/bounded-exec/executor.js +48 -11
- package/dist/executors/bounded-exec/progress.d.ts +1 -3
- package/dist/executors/bounded-exec/progress.d.ts.map +1 -1
- package/dist/executors/bounded-exec/progress.js +1 -2
- package/dist/executors/bounded-exec/runner-hook.d.ts +2 -0
- package/dist/executors/bounded-exec/runner-hook.d.ts.map +1 -0
- package/dist/executors/bounded-exec/runner-hook.js +301 -0
- package/dist/executors/bounded-exec/runner-lifecycle.d.ts +18 -0
- package/dist/executors/bounded-exec/runner-lifecycle.d.ts.map +1 -0
- package/dist/executors/bounded-exec/runner-lifecycle.js +92 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1
- package/dist/producer-receipts.d.ts +24 -1
- package/dist/producer-receipts.d.ts.map +1 -1
- package/dist/producer-receipts.js +91 -60
- package/executors.json +5 -0
- package/managed/raw/git-format-staged.yml +16 -3
- package/managed/raw/patches/nx@23.2.1.patch +397 -33
- package/package.json +2 -2
- package/src/ensure-built-receipt.ts +8 -2
- package/src/ensure-built-witness.ts +29 -1
- package/src/ensure-built.ts +39 -7
- package/src/executors/all-verdicts/executor.test.ts +135 -0
- package/src/executors/all-verdicts/executor.ts +164 -0
- package/src/executors/all-verdicts/schema.json +22 -0
- package/src/executors/all-verdicts/schema.ts +10 -0
- package/src/executors/bounded-exec/cargo-progress-host.test.ts +332 -0
- package/src/executors/bounded-exec/executor.test.ts +89 -42
- package/src/executors/bounded-exec/executor.ts +45 -11
- package/src/executors/bounded-exec/progress.test.ts +1 -14
- package/src/executors/bounded-exec/progress.ts +2 -5
- package/src/executors/bounded-exec/runner-hook.test.ts +193 -0
- package/src/executors/bounded-exec/runner-hook.ts +292 -0
- package/src/executors/bounded-exec/runner-lifecycle.test.ts +82 -0
- package/src/executors/bounded-exec/runner-lifecycle.ts +102 -0
- package/src/index.test.ts +7 -5
- package/src/index.ts +4 -1
- package/src/nx-daemon-start-never.test.ts +137 -0
- package/src/producer-receipts.test.ts +99 -0
- package/src/producer-receipts.ts +111 -58
- package/test-timings.json +101 -96
|
@@ -23,15 +23,13 @@ import { BUN_TEST, GO_TEST, NEXTEST_RUN } from './verdict.js';
|
|
|
23
23
|
* `fail`, or `skip` ends that execution interval. Test terminals re-arm the bound, but `output` and
|
|
24
24
|
* `build-output` never do. Initial and inter-package builds are outside an active test interval.
|
|
25
25
|
*
|
|
26
|
-
*
|
|
26
|
+
* Execution phases are owned by the private supervisor channel in runner-lifecycle.ts, never these text reports.
|
|
27
27
|
*/
|
|
28
28
|
export interface RunProgress {
|
|
29
29
|
/** One chunk of one of the command's output streams; true when it reports a finished test or Go package. */
|
|
30
30
|
scan(stream: OutputStream, chunk: string): boolean;
|
|
31
31
|
/** The tests the runner reported running and has not reported finished, in the order it first named them. */
|
|
32
32
|
inFlight(): string[];
|
|
33
|
-
/** Whether test idle time is currently chargeable; unknown runner lifecycles stay chargeable. */
|
|
34
|
-
isTesting(): boolean;
|
|
35
33
|
}
|
|
36
34
|
|
|
37
35
|
export type OutputStream = 'stdout' | 'stderr';
|
|
@@ -68,7 +66,7 @@ function goTestEvent(text: string): GoTestEvent | null {
|
|
|
68
66
|
}
|
|
69
67
|
}
|
|
70
68
|
|
|
71
|
-
/**
|
|
69
|
+
/** A direct Go chain reports tests only through JSON; other commands may also carry text runner reports. */
|
|
72
70
|
function onlyGoTests(command: string): boolean {
|
|
73
71
|
let rest = command.trim();
|
|
74
72
|
while (rest.search(GO_TEST) === 0) {
|
|
@@ -170,7 +168,6 @@ export function createRunProgress(command = ''): RunProgress {
|
|
|
170
168
|
tests.size === 0 ? [name] : [...tests].map((test) => `${name} ${test}`),
|
|
171
169
|
),
|
|
172
170
|
],
|
|
173
|
-
isTesting: () => !goLifecycle || packages.size > 0,
|
|
174
171
|
};
|
|
175
172
|
}
|
|
176
173
|
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it } from 'bun:test';
|
|
2
|
+
import { type ChildProcess, spawn } from 'node:child_process';
|
|
3
|
+
import { createInterface } from 'node:readline';
|
|
4
|
+
import { Duplex, type Readable } from 'node:stream';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
|
|
7
|
+
const hook = fileURLToPath(new URL('./runner-hook.ts', import.meta.url));
|
|
8
|
+
const children = new Set<ChildProcess>();
|
|
9
|
+
|
|
10
|
+
afterEach(() => {
|
|
11
|
+
for (const child of children) child.kill('SIGKILL');
|
|
12
|
+
children.clear();
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
async function collect(stream: Readable): Promise<Buffer> {
|
|
16
|
+
const chunks: Buffer[] = [];
|
|
17
|
+
for await (const chunk of stream) {
|
|
18
|
+
const bytes: unknown = chunk;
|
|
19
|
+
if (!Buffer.isBuffer(bytes)) throw new Error('expected subprocess bytes');
|
|
20
|
+
chunks.push(bytes);
|
|
21
|
+
}
|
|
22
|
+
return Buffer.concat(chunks);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function runHook(
|
|
26
|
+
runner: 'cargo' | 'go',
|
|
27
|
+
executable: string,
|
|
28
|
+
args: string[],
|
|
29
|
+
acknowledge: (line: string) => string = (line) => `${line}\n`,
|
|
30
|
+
) {
|
|
31
|
+
// Node's standalone TypeScript loader needs no project preloader or validation transform.
|
|
32
|
+
const child = spawn('node', [hook, '7', runner, executable, ...args], {
|
|
33
|
+
stdio: ['ignore', 'pipe', 'pipe', 'pipe'],
|
|
34
|
+
});
|
|
35
|
+
children.add(child);
|
|
36
|
+
const closed = Promise.withResolvers<{ code: number | null; signal: NodeJS.Signals | null }>();
|
|
37
|
+
child.once('error', closed.reject);
|
|
38
|
+
child.once('close', (code, signal) => {
|
|
39
|
+
children.delete(child);
|
|
40
|
+
closed.resolve({ code, signal });
|
|
41
|
+
});
|
|
42
|
+
const control = child.stdio[3];
|
|
43
|
+
if (!(control instanceof Duplex) || child.stdout === null || child.stderr === null) {
|
|
44
|
+
throw new Error('runner-hook fixture needs stdout, stderr, and duplex descriptor 3');
|
|
45
|
+
}
|
|
46
|
+
const phases: unknown[] = [];
|
|
47
|
+
const protocol = async (): Promise<void> => {
|
|
48
|
+
try {
|
|
49
|
+
for await (const line of createInterface({ input: control })) {
|
|
50
|
+
const message: unknown = JSON.parse(line);
|
|
51
|
+
phases.push(message);
|
|
52
|
+
control.write(acknowledge(line));
|
|
53
|
+
}
|
|
54
|
+
} finally {
|
|
55
|
+
control.destroy();
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
const [status, stdout, stderr] = await Promise.all([
|
|
59
|
+
closed.promise,
|
|
60
|
+
collect(child.stdout),
|
|
61
|
+
collect(child.stderr),
|
|
62
|
+
protocol(),
|
|
63
|
+
]);
|
|
64
|
+
return { ...status, stdout, stderr, phases };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** A real process emitting exact protocol fragments, not a parser imported into the test process. */
|
|
68
|
+
function emit(stdout: readonly string[], stderr = '', ending = 'process.exitCode = 0;'): string {
|
|
69
|
+
return [
|
|
70
|
+
"const { writeSync } = require('node:fs');",
|
|
71
|
+
`writeSync(2, ${JSON.stringify(stderr)});`,
|
|
72
|
+
`for (const fragment of ${JSON.stringify(stdout)}) writeSync(1, fragment);`,
|
|
73
|
+
ending,
|
|
74
|
+
].join('\n');
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
describe('standalone native runner hook', () => {
|
|
78
|
+
it('accepts Cargo build-finished(false) once, ignores compiler/text/nested terminals, and preserves bytes and status', async () => {
|
|
79
|
+
const stdout = [
|
|
80
|
+
'{"reason":"compiler-artifact","fresh":true}\n',
|
|
81
|
+
'{"reason":"build-finished","success":"true"}\n',
|
|
82
|
+
'{not JSON}\n',
|
|
83
|
+
'{"reason":"build-fin',
|
|
84
|
+
'ished","success":false}\n',
|
|
85
|
+
'test result: ok. 1 passed; 0 failed\n',
|
|
86
|
+
'{"Action":"pass","Package":"nested"}\n',
|
|
87
|
+
'{"reason":"build-finished","success":true}\n',
|
|
88
|
+
'custom harness teardown without newline',
|
|
89
|
+
];
|
|
90
|
+
const stderr = '{"reason":"build-finished","success":true}\ncompiler diagnostic\n';
|
|
91
|
+
const program =
|
|
92
|
+
"require('node:fs').writeSync(1, Buffer.from([0, 255, 128, 10]));\n" +
|
|
93
|
+
emit(stdout, stderr, 'process.exitCode = 37;');
|
|
94
|
+
const result = await runHook('cargo', process.execPath, ['-e', program]);
|
|
95
|
+
expect(result.code).toBe(37);
|
|
96
|
+
expect(result.signal).toBeNull();
|
|
97
|
+
expect(result.stdout).toEqual(Buffer.concat([Buffer.from([0, 255, 128, 10]), Buffer.from(stdout.join(''))]));
|
|
98
|
+
expect(result.stderr).toEqual(Buffer.from(stderr));
|
|
99
|
+
expect(result.phases).toEqual([
|
|
100
|
+
{ id: 7, phase: 'build' },
|
|
101
|
+
{ id: 7, phase: 'active' },
|
|
102
|
+
{ id: 7, phase: 'terminal' },
|
|
103
|
+
]);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('tracks overlapping Go packages, not test terminals, stderr, build output, or nested output', async () => {
|
|
107
|
+
const stdout = [
|
|
108
|
+
'{"Action":"build-output","ImportPath":"one","Output":"linking\\n"}\n',
|
|
109
|
+
'{"Action":"sta',
|
|
110
|
+
'rt","Package":"one"}\n',
|
|
111
|
+
'{"Action":"start","Package":"two"}\n',
|
|
112
|
+
'{"Action":"pass","Package":"one","Test":"TestDone"}\n',
|
|
113
|
+
'{"Action":"output","Package":"one","Output":"{\\"Action\\":\\"pass\\",\\"Package\\":\\"two\\"}\\n"}\n',
|
|
114
|
+
'{"Action":"fail","Package":"one"}\n',
|
|
115
|
+
'{"Action":"skip","Package":"two"}\n',
|
|
116
|
+
'{"Action":"start","Package":"three"}\n',
|
|
117
|
+
'{"Action":"pass","Package":"three"}',
|
|
118
|
+
];
|
|
119
|
+
const stderr = '{"Action":"start","Package":"stderr-is-not-native"}\n';
|
|
120
|
+
const result = await runHook('go', process.execPath, ['-e', emit(stdout, stderr)]);
|
|
121
|
+
expect(result.code).toBe(0);
|
|
122
|
+
expect(result.stdout).toEqual(Buffer.from(stdout.join('')));
|
|
123
|
+
expect(result.stderr).toEqual(Buffer.from(stderr));
|
|
124
|
+
expect(result.phases).toEqual([
|
|
125
|
+
{ id: 7, phase: 'build' },
|
|
126
|
+
{ id: 7, phase: 'active' },
|
|
127
|
+
{ id: 7, phase: 'build' },
|
|
128
|
+
{ id: 7, phase: 'active' },
|
|
129
|
+
{ id: 7, phase: 'build' },
|
|
130
|
+
{ id: 7, phase: 'terminal' },
|
|
131
|
+
]);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
it('preserves a child termination signal after draining output and acknowledging terminal', async () => {
|
|
135
|
+
const stdout = ['{"reason":"build-finished","success":true}\n', 'last stdout\n'];
|
|
136
|
+
const result = await runHook('cargo', process.execPath, [
|
|
137
|
+
'-e',
|
|
138
|
+
emit(stdout, 'last stderr\n', "process.kill(process.pid, 'SIGTERM');"),
|
|
139
|
+
]);
|
|
140
|
+
expect(result.code).toBeNull();
|
|
141
|
+
expect(result.signal).toBe('SIGTERM');
|
|
142
|
+
expect(result.stdout).toEqual(Buffer.from(stdout.join('')));
|
|
143
|
+
expect(result.stderr.toString()).toBe('last stderr\n');
|
|
144
|
+
expect(result.phases).toEqual([
|
|
145
|
+
{ id: 7, phase: 'build' },
|
|
146
|
+
{ id: 7, phase: 'active' },
|
|
147
|
+
{ id: 7, phase: 'terminal' },
|
|
148
|
+
]);
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
it('reports spawn failure, acknowledges terminal, and exits nonzero', async () => {
|
|
152
|
+
const result = await runHook('cargo', `/runner-hook-missing-executable-${process.pid}`, []);
|
|
153
|
+
expect(result.code).toBe(1);
|
|
154
|
+
expect(result.signal).toBeNull();
|
|
155
|
+
expect(result.stdout.length).toBe(0);
|
|
156
|
+
expect(result.stderr.toString()).toContain('runner-hook:');
|
|
157
|
+
expect(result.stderr.toString()).toContain('runner-hook-missing-executable-');
|
|
158
|
+
expect(result.phases).toEqual([
|
|
159
|
+
{ id: 7, phase: 'build' },
|
|
160
|
+
{ id: 7, phase: 'terminal' },
|
|
161
|
+
]);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it('does not start the child until its initial build phase is acknowledged correctly', async () => {
|
|
165
|
+
const result = await runHook(
|
|
166
|
+
'cargo',
|
|
167
|
+
process.execPath,
|
|
168
|
+
['-e', emit(['child must not run\n'])],
|
|
169
|
+
() => '{"id":8,"phase":"build"}\n',
|
|
170
|
+
);
|
|
171
|
+
expect(result.code).toBe(1);
|
|
172
|
+
expect(result.stdout.length).toBe(0);
|
|
173
|
+
expect(result.stderr.toString()).toContain('unexpected lifecycle acknowledgement');
|
|
174
|
+
expect(result.phases).toEqual([{ id: 7, phase: 'build' }]);
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
it('withholds the active record and subsequent stdout when its acknowledgement is invalid', async () => {
|
|
178
|
+
const compiler = '{"reason":"compiler-artifact","fresh":true}\n';
|
|
179
|
+
const result = await runHook(
|
|
180
|
+
'cargo',
|
|
181
|
+
process.execPath,
|
|
182
|
+
['-e', emit([compiler, '{"reason":"build-finished","success":true}\n', 'fixture ready\n'])],
|
|
183
|
+
(line) => (line.includes('"phase":"active"') ? '{"id":8,"phase":"active"}\n' : `${line}\n`),
|
|
184
|
+
);
|
|
185
|
+
expect(result.code).toBe(1);
|
|
186
|
+
expect(result.stdout.toString()).toBe(compiler);
|
|
187
|
+
expect(result.stderr.toString()).toContain('unexpected lifecycle acknowledgement');
|
|
188
|
+
expect(result.phases).toEqual([
|
|
189
|
+
{ id: 7, phase: 'build' },
|
|
190
|
+
{ id: 7, phase: 'active' },
|
|
191
|
+
]);
|
|
192
|
+
});
|
|
193
|
+
});
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Standalone supervisor: <runtime> runner-hook.js <id> <go|cargo> <executable> [args...].
|
|
3
|
+
* The parent requests native JSON output and supplies a private duplex socket on fd 3.
|
|
4
|
+
* Each newline JSON {id,phase} must be echoed exactly after applying the watchdog state.
|
|
5
|
+
* Build is acknowledged before spawn; each native transition is acknowledged before its
|
|
6
|
+
* stdout record is forwarded. Terminal follows child close and drained output, then its
|
|
7
|
+
* acknowledgement closes the channel. The tool receives only descriptors 0, 1, and 2.
|
|
8
|
+
*/
|
|
9
|
+
import { type ChildProcess, spawn } from 'node:child_process';
|
|
10
|
+
import { Socket } from 'node:net';
|
|
11
|
+
import type { Readable, Writable } from 'node:stream';
|
|
12
|
+
|
|
13
|
+
type Runner = 'go' | 'cargo';
|
|
14
|
+
type Phase = 'build' | 'active' | 'terminal';
|
|
15
|
+
|
|
16
|
+
interface Lifecycle {
|
|
17
|
+
announce(phase: Phase): Promise<Error | null>;
|
|
18
|
+
close(): Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function failure(context: string, error: unknown): Error {
|
|
22
|
+
return new Error(`${context}: ${error instanceof Error ? error.message : String(error)}`);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// This executable inherits lib es2022; Promise.withResolvers requires es2024.
|
|
26
|
+
function write(stream: Writable, bytes: Buffer | string): Promise<Error | null> {
|
|
27
|
+
return new Promise((resolve) => {
|
|
28
|
+
stream.write(bytes, (error) => resolve(error ?? null));
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Only native stdout records change the lifecycle; arbitrary runner text never does. */
|
|
33
|
+
function nativePhase(runner: Runner): (line: Buffer) => Phase | null {
|
|
34
|
+
const packages = new Set<string>();
|
|
35
|
+
let cargoActive = false;
|
|
36
|
+
return (line) => {
|
|
37
|
+
if (cargoActive || line[0] !== 123) return null;
|
|
38
|
+
let event: unknown;
|
|
39
|
+
try {
|
|
40
|
+
event = JSON.parse(line.toString('utf8'));
|
|
41
|
+
} catch (error) {
|
|
42
|
+
if (error instanceof SyntaxError) return null;
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
if (typeof event !== 'object' || event === null) return null;
|
|
46
|
+
if (runner === 'cargo') {
|
|
47
|
+
if (
|
|
48
|
+
'reason' in event &&
|
|
49
|
+
event.reason === 'build-finished' &&
|
|
50
|
+
'success' in event &&
|
|
51
|
+
typeof event.success === 'boolean'
|
|
52
|
+
) {
|
|
53
|
+
// Even a failed build has left compilation. Nothing emitted by a test, doctest,
|
|
54
|
+
// or custom harness can put Cargo back into build or finish this invocation.
|
|
55
|
+
cargoActive = true;
|
|
56
|
+
return 'active';
|
|
57
|
+
}
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
if (!('Action' in event) || !('Package' in event) || typeof event.Package !== 'string' || 'Test' in event) {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
switch (event.Action) {
|
|
64
|
+
case 'start':
|
|
65
|
+
packages.add(event.Package);
|
|
66
|
+
break;
|
|
67
|
+
case 'pass':
|
|
68
|
+
case 'fail':
|
|
69
|
+
case 'skip':
|
|
70
|
+
packages.delete(event.Package);
|
|
71
|
+
break;
|
|
72
|
+
default:
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
return packages.size === 0 ? 'build' : 'active';
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** One outstanding phase, acknowledged only after the executor applies its watchdog state. */
|
|
80
|
+
function lifecycle(id: number, failed: (error: Error) => void): Lifecycle {
|
|
81
|
+
const socket = new Socket({ fd: 3, readable: true, writable: true });
|
|
82
|
+
let pending: { message: string; resolve: (error: Error | null) => void } | null = null;
|
|
83
|
+
let received = '';
|
|
84
|
+
let error: Error | null = null;
|
|
85
|
+
let closing = false;
|
|
86
|
+
let phase: Phase | null = null;
|
|
87
|
+
const fail = (cause: Error): void => {
|
|
88
|
+
if (error !== null) return;
|
|
89
|
+
error = cause;
|
|
90
|
+
const waiting = pending;
|
|
91
|
+
pending = null;
|
|
92
|
+
waiting?.resolve(cause);
|
|
93
|
+
failed(cause);
|
|
94
|
+
socket.destroy();
|
|
95
|
+
};
|
|
96
|
+
socket.on('error', (cause) => fail(failure('lifecycle channel failed', cause)));
|
|
97
|
+
socket.on('end', () => {
|
|
98
|
+
if (!closing) fail(new Error('lifecycle channel ended before terminal acknowledgement'));
|
|
99
|
+
});
|
|
100
|
+
socket.on('close', () => {
|
|
101
|
+
if (!closing && error === null) fail(new Error('lifecycle channel closed before terminal acknowledgement'));
|
|
102
|
+
});
|
|
103
|
+
socket.on('data', (chunk: Buffer) => {
|
|
104
|
+
received += chunk.toString('utf8');
|
|
105
|
+
if (pending === null || !pending.message.startsWith(received)) {
|
|
106
|
+
fail(new Error(`unexpected lifecycle acknowledgement: ${JSON.stringify(received)}`));
|
|
107
|
+
} else if (received === pending.message) {
|
|
108
|
+
const waiting = pending;
|
|
109
|
+
pending = null;
|
|
110
|
+
received = '';
|
|
111
|
+
waiting.resolve(null);
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
return {
|
|
115
|
+
async announce(next: Phase): Promise<Error | null> {
|
|
116
|
+
if (error !== null) return error;
|
|
117
|
+
if (phase === next) return null;
|
|
118
|
+
if (pending !== null) throw new Error('concurrent lifecycle announcements');
|
|
119
|
+
const result = await new Promise<Error | null>((resolve) => {
|
|
120
|
+
const message = `${JSON.stringify({ id, phase: next })}\n`;
|
|
121
|
+
pending = { message, resolve };
|
|
122
|
+
socket.write(message, (cause) => {
|
|
123
|
+
if (cause) fail(failure('writing lifecycle phase failed', cause));
|
|
124
|
+
});
|
|
125
|
+
});
|
|
126
|
+
if (result === null) phase = next;
|
|
127
|
+
return result;
|
|
128
|
+
},
|
|
129
|
+
async close(): Promise<void> {
|
|
130
|
+
closing = true;
|
|
131
|
+
if (socket.destroyed) return;
|
|
132
|
+
await new Promise<void>((resolve) => {
|
|
133
|
+
socket.once('close', resolve);
|
|
134
|
+
// The shell retains this endpoint for later commands: shutdown/end would poison
|
|
135
|
+
// every inherited reference. Terminal ACK drained our writes; close only ours.
|
|
136
|
+
socket.destroy();
|
|
137
|
+
});
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Await each destination write, bounding queued output and preserving its original bytes. */
|
|
143
|
+
async function forward(source: Readable, target: Writable): Promise<Error | null> {
|
|
144
|
+
try {
|
|
145
|
+
for await (const chunk of source) {
|
|
146
|
+
const bytes: unknown = chunk;
|
|
147
|
+
if (!Buffer.isBuffer(bytes)) throw new Error('child output was not a byte stream');
|
|
148
|
+
const error = await write(target, bytes);
|
|
149
|
+
if (error !== null) return error;
|
|
150
|
+
}
|
|
151
|
+
return null;
|
|
152
|
+
} catch (error) {
|
|
153
|
+
return failure('reading child output failed', error);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Buffer only possible JSON records; ACK their transition before releasing any of their bytes. */
|
|
158
|
+
async function forwardStdout(
|
|
159
|
+
source: Readable,
|
|
160
|
+
inspect: (line: Buffer) => Promise<Error | null>,
|
|
161
|
+
): Promise<Error | null> {
|
|
162
|
+
let pending: Buffer[] = [];
|
|
163
|
+
let start = true;
|
|
164
|
+
let json = false;
|
|
165
|
+
const record = async (line: Buffer): Promise<Error | null> => {
|
|
166
|
+
const error = await inspect(line);
|
|
167
|
+
return error ?? (await write(process.stdout, line));
|
|
168
|
+
};
|
|
169
|
+
try {
|
|
170
|
+
for await (const chunk of source) {
|
|
171
|
+
const bytes: unknown = chunk;
|
|
172
|
+
if (!Buffer.isBuffer(bytes)) throw new Error('child stdout was not a byte stream');
|
|
173
|
+
let offset = 0;
|
|
174
|
+
while (offset < bytes.length) {
|
|
175
|
+
if (start) json = bytes[offset] === 123;
|
|
176
|
+
const newline = bytes.indexOf(10, offset);
|
|
177
|
+
const end = newline === -1 ? bytes.length : newline + 1;
|
|
178
|
+
const piece = bytes.subarray(offset, end);
|
|
179
|
+
let error: Error | null = null;
|
|
180
|
+
if (json && newline === -1) {
|
|
181
|
+
pending.push(piece);
|
|
182
|
+
} else if (json) {
|
|
183
|
+
let line = piece;
|
|
184
|
+
if (pending.length !== 0) {
|
|
185
|
+
pending.push(piece);
|
|
186
|
+
line = Buffer.concat(pending);
|
|
187
|
+
pending = [];
|
|
188
|
+
}
|
|
189
|
+
error = await record(line);
|
|
190
|
+
} else {
|
|
191
|
+
error = await write(process.stdout, piece);
|
|
192
|
+
}
|
|
193
|
+
if (error !== null) return error;
|
|
194
|
+
start = newline !== -1;
|
|
195
|
+
offset = end;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return pending.length === 0 ? null : await record(Buffer.concat(pending));
|
|
199
|
+
} catch (error) {
|
|
200
|
+
return failure('reading child stdout failed', error);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** argv: invocation ID, runner kind, original executable, then its unchanged arguments. */
|
|
205
|
+
async function main([idText, runner, executable, ...args]: readonly string[]): Promise<void> {
|
|
206
|
+
const id = Number(idText);
|
|
207
|
+
if (
|
|
208
|
+
idText === undefined ||
|
|
209
|
+
!/^\d+$/.test(idText) ||
|
|
210
|
+
!Number.isSafeInteger(id) ||
|
|
211
|
+
(runner !== 'go' && runner !== 'cargo') ||
|
|
212
|
+
executable === undefined ||
|
|
213
|
+
executable === ''
|
|
214
|
+
) {
|
|
215
|
+
process.stderr.write('runner-hook: usage: <invocation-id> <go|cargo> <executable> [arguments...]\n');
|
|
216
|
+
process.exitCode = 2;
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
let child: ChildProcess | null = null;
|
|
220
|
+
let failed = false;
|
|
221
|
+
let interrupted: NodeJS.Signals | null = null;
|
|
222
|
+
const fail = (error: Error): void => {
|
|
223
|
+
if (failed) return;
|
|
224
|
+
failed = true;
|
|
225
|
+
process.exitCode = 1;
|
|
226
|
+
process.stderr.write(`runner-hook: ${error.message}\n`);
|
|
227
|
+
child?.kill('SIGKILL');
|
|
228
|
+
};
|
|
229
|
+
const forwardedSignals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT'];
|
|
230
|
+
const signals = forwardedSignals.map((name) => {
|
|
231
|
+
const listener = (): void => {
|
|
232
|
+
interrupted = name;
|
|
233
|
+
child?.kill(name);
|
|
234
|
+
};
|
|
235
|
+
process.on(name, listener);
|
|
236
|
+
return { name, listener };
|
|
237
|
+
});
|
|
238
|
+
process.stdout.on('error', fail);
|
|
239
|
+
process.stderr.on('error', fail);
|
|
240
|
+
let channel: Lifecycle | null = null;
|
|
241
|
+
let code: number | null = null;
|
|
242
|
+
let exitSignal: NodeJS.Signals | null = null;
|
|
243
|
+
try {
|
|
244
|
+
channel = lifecycle(id, fail);
|
|
245
|
+
const ready = await channel.announce('build');
|
|
246
|
+
if (ready !== null) fail(ready);
|
|
247
|
+
if (!failed && interrupted === null) {
|
|
248
|
+
// Descriptor 3 belongs only to this supervisor, never the tool or its descendants.
|
|
249
|
+
const running = spawn(executable, args, { stdio: ['inherit', 'pipe', 'pipe'] });
|
|
250
|
+
child = running;
|
|
251
|
+
const closed = new Promise<void>((resolve) => {
|
|
252
|
+
running.once('close', (status, reason) => {
|
|
253
|
+
code = status;
|
|
254
|
+
exitSignal = reason;
|
|
255
|
+
resolve();
|
|
256
|
+
});
|
|
257
|
+
});
|
|
258
|
+
running.on('error', (error) => fail(failure(`could not run ${JSON.stringify(executable)}`, error)));
|
|
259
|
+
const scan = nativePhase(runner);
|
|
260
|
+
const control = channel;
|
|
261
|
+
const stdout = forwardStdout(running.stdout, async (line) => {
|
|
262
|
+
const next = scan(line);
|
|
263
|
+
return next === null ? null : await control.announce(next);
|
|
264
|
+
}).then((error) => {
|
|
265
|
+
if (error !== null) fail(failure('forwarding stdout failed', error));
|
|
266
|
+
});
|
|
267
|
+
const stderr = forward(running.stderr, process.stderr).then((error) => {
|
|
268
|
+
if (error !== null) fail(failure('forwarding stderr failed', error));
|
|
269
|
+
});
|
|
270
|
+
await Promise.all([closed, stdout, stderr]);
|
|
271
|
+
} else {
|
|
272
|
+
exitSignal = interrupted;
|
|
273
|
+
}
|
|
274
|
+
} catch (error) {
|
|
275
|
+
fail(failure('supervisor failed', error));
|
|
276
|
+
}
|
|
277
|
+
// Write callbacks complete only once downstream has accepted every forwarded byte.
|
|
278
|
+
// Flush diagnostics too, before terminal and before re-raising a child's signal.
|
|
279
|
+
for (const error of await Promise.all([write(process.stdout, ''), write(process.stderr, '')])) {
|
|
280
|
+
if (error !== null) fail(failure('draining supervisor output failed', error));
|
|
281
|
+
}
|
|
282
|
+
if (channel !== null) {
|
|
283
|
+
const error = await channel.announce('terminal');
|
|
284
|
+
if (error !== null) fail(error);
|
|
285
|
+
await channel.close();
|
|
286
|
+
}
|
|
287
|
+
for (const { name, listener } of signals) process.off(name, listener);
|
|
288
|
+
process.exitCode = failed ? 1 : (code ?? 1);
|
|
289
|
+
if (!failed && exitSignal !== null) process.kill(process.pid, exitSignal);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
await main(process.argv.slice(2));
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test';
|
|
2
|
+
import { createRunnerLifecycle, withRunnerLifecycle } from './runner-lifecycle.js';
|
|
3
|
+
|
|
4
|
+
const event = (id: number, phase: string): string => JSON.stringify({ id, phase });
|
|
5
|
+
|
|
6
|
+
describe('private runner lifecycle', () => {
|
|
7
|
+
it('bounds startup and active execution, never build intervals, through the final owned close', () => {
|
|
8
|
+
const lifecycle = createRunnerLifecycle(2);
|
|
9
|
+
expect(lifecycle.isTesting()).toBe(true);
|
|
10
|
+
lifecycle.accept(event(0, 'build'));
|
|
11
|
+
expect(lifecycle.isTesting()).toBe(false);
|
|
12
|
+
lifecycle.accept(event(0, 'active'));
|
|
13
|
+
expect(lifecycle.isTesting()).toBe(true);
|
|
14
|
+
lifecycle.accept(event(0, 'build'));
|
|
15
|
+
expect(lifecycle.isTesting()).toBe(false);
|
|
16
|
+
lifecycle.accept(event(0, 'active'));
|
|
17
|
+
lifecycle.accept(event(0, 'terminal'));
|
|
18
|
+
expect(lifecycle.isTesting()).toBe(true);
|
|
19
|
+
lifecycle.accept(event(1, 'build'));
|
|
20
|
+
expect(lifecycle.isTesting()).toBe(false);
|
|
21
|
+
lifecycle.accept(event(1, 'active'));
|
|
22
|
+
expect(lifecycle.isTesting()).toBe(true);
|
|
23
|
+
lifecycle.accept(event(1, 'terminal'));
|
|
24
|
+
expect(lifecycle.isTesting()).toBe(false);
|
|
25
|
+
expect(lifecycle.error()).toBeNull();
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it('allows shell short-circuiting but refuses overlapping or resurrected invocations', () => {
|
|
29
|
+
const lifecycle = createRunnerLifecycle(3);
|
|
30
|
+
lifecycle.accept(event(0, 'build'));
|
|
31
|
+
lifecycle.accept(event(0, 'terminal'));
|
|
32
|
+
expect(lifecycle.accept(event(2, 'build'))).toEqual({ id: 2, phase: 'build' });
|
|
33
|
+
expect(lifecycle.accept(event(1, 'build'))).toBeNull();
|
|
34
|
+
expect(lifecycle.isTesting()).toBe(true);
|
|
35
|
+
expect(lifecycle.error()).not.toBeNull();
|
|
36
|
+
for (const lines of [
|
|
37
|
+
[event(0, 'terminal'), event(0, 'build')],
|
|
38
|
+
[event(0, 'build'), event(1, 'build')],
|
|
39
|
+
['test result: ok'],
|
|
40
|
+
[event(0, 'heartbeat')],
|
|
41
|
+
]) {
|
|
42
|
+
const invalid = createRunnerLifecycle(2);
|
|
43
|
+
for (const line of lines) invalid.accept(line);
|
|
44
|
+
expect(invalid.error()).not.toBeNull();
|
|
45
|
+
expect(invalid.isTesting()).toBe(true);
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
describe('native runner hooks', () => {
|
|
51
|
+
it('preserves runner selection, toolchains, separators, and harness arguments', () => {
|
|
52
|
+
const hooked = withRunnerLifecycle(
|
|
53
|
+
'cargo +stable --frozen test --message-format=human --lib selected -- --nocapture && go test -json ./second',
|
|
54
|
+
);
|
|
55
|
+
expect(hooked?.runners).toBe(2);
|
|
56
|
+
expect(hooked?.command).toContain(
|
|
57
|
+
'0 cargo cargo +stable --frozen test --message-format=json-render-diagnostics --lib selected -- --nocapture && ',
|
|
58
|
+
);
|
|
59
|
+
expect(hooked?.command).toContain('1 go go test -json ./second');
|
|
60
|
+
expect(withRunnerLifecycle('cargo test a || cargo test b; go test -json ./...')?.runners).toBe(3);
|
|
61
|
+
expect(withRunnerLifecycle('cargo test -- --message-format=human')?.command).toContain(
|
|
62
|
+
'cargo test --message-format=json-render-diagnostics -- --message-format=human',
|
|
63
|
+
);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('retains spawn accounting for Bun, nextest, mixed wrappers and unknown shell syntax', () => {
|
|
67
|
+
for (const command of [
|
|
68
|
+
'bun test src',
|
|
69
|
+
'cargo nextest run',
|
|
70
|
+
'cargo build && cargo test',
|
|
71
|
+
'go test ./... && bun test src',
|
|
72
|
+
'env FOO=bar cargo test',
|
|
73
|
+
'cargo test | cat',
|
|
74
|
+
'cargo test > output',
|
|
75
|
+
'cargo test 3>&1',
|
|
76
|
+
'cargo test &&',
|
|
77
|
+
'cargo test\ngo test',
|
|
78
|
+
'sh -c "cargo test"',
|
|
79
|
+
])
|
|
80
|
+
expect(withRunnerLifecycle(command)).toBeNull();
|
|
81
|
+
});
|
|
82
|
+
});
|