Repository navigation
Expand file tree
/
Copy pathpipedInput.test.ts
More file actions
210 lines (197 loc) · 7.36 KB
/
Copy pathpipedInput.test.ts
File metadata and controls
210 lines (197 loc) · 7.36 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
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
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import { spawn } from 'node:child_process';
import { once } from 'node:events';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { Rush } from '@microsoft/rush-lib';
import { captureDaemonRequest, DaemonClient } from '@rushstack/rush-client-core';
import {
DaemonRequestDispatchError,
RushDaemonHost,
type GlobalCommandExecutor,
type IDaemonRequestResolver
} from '@rushstack/rush-daemon';
import { getTestProcessEnvironment } from './TestProcessEnvironment';
const SCRIPT: string =
"const chunks=[];process.stdin.on('data',c=>{chunks.push(c);process.stdin.pause();" +
'setTimeout(()=>process.stdin.resume(),1);});' +
"process.stdin.on('end',()=>{process.stdout.write(Buffer.concat(chunks));" +
"process.stderr.write('pipe-ended');process.exitCode=7;});";
interface IPipedResult {
readonly code: number | undefined;
readonly stdout: Buffer;
readonly stderr: Buffer;
}
describe('standalone client piped input', () => {
let folder: string;
let project: string;
let host: RushDaemonHost | undefined;
beforeEach(() => {
folder = fs.mkdtempSync(path.join(os.tmpdir(), 'rush-cli-input-'));
project = path.join(folder, 'project');
fs.mkdirSync(project);
fs.mkdirSync(path.join(folder, 'common/config/rush'), { recursive: true });
fs.writeFileSync(
path.join(folder, 'rush.json'),
JSON.stringify({
rushVersion: Rush.version,
suppressNodeLtsWarning: true,
pnpmVersion: '10.27.0',
daemon: { enabled: false, autoStart: false },
projects: [{ packageName: 'sample', projectFolder: 'project' }],
projectFolderMinDepth: 1
})
);
fs.writeFileSync(
path.join(project, 'package.json'),
JSON.stringify({
name: 'sample',
version: '1.0.0',
scripts: { sample: `node -e "${SCRIPT}"` }
})
);
});
afterEach(async () => {
const closingHost: RushDaemonHost | undefined = host;
host = undefined;
await closingHost?.closeAsync();
fs.rmSync(folder, { recursive: true });
});
async function startHostAsync(requestResolver: IDaemonRequestResolver): Promise<void> {
const daemonPackage: { version: string } = require('@rushstack/rush-daemon/package.json');
host = await RushDaemonHost.startAsync({
repoRoot: folder,
rushVersion: Rush.version,
daemonVersion: daemonPackage.version,
requestResolver
});
}
async function invokeAsync(
input: Buffer,
useClient: boolean = true,
admissionArgs: ReadonlyArray<string> = []
): Promise<IPipedResult> {
const entry: string = useClient
? path.resolve(__dirname, '../../bin/rushx-client')
: path.join(path.dirname(require.resolve('@microsoft/rush/package.json')), 'bin/rushx');
const child = spawn(process.execPath, [entry, 'sample', ...admissionArgs], {
cwd: project,
env: {
...getTestProcessEnvironment(),
RUSH_DAEMON: '1',
RUSH_REPORTER: 'legacy',
RUSH_QUIET_MODE: '1',
CI: 'false',
TF_BUILD: 'false',
GITHUB_ACTIONS: 'false'
},
stdio: 'pipe'
});
const stdout: Buffer[] = [];
const stderr: Buffer[] = [];
child.stdout.on('data', (bytes: Buffer) => stdout.push(bytes));
child.stderr.on('data', (bytes: Buffer) => stderr.push(bytes));
child.stdin.end(input);
const [code] = await once(child, 'close');
return {
code: typeof code === 'number' ? code : undefined,
stdout: Buffer.concat(stdout),
stderr: Buffer.concat(stderr)
};
}
it.each([Buffer.from([0, 3, 255, 13]), Buffer.alloc(0), Buffer.alloc(2 * 1024 * 1024, 3)])(
'delivers pipe bytes and EOF through the real host without treating Ctrl+C bytes as signals',
async (input) => {
const executorAsync: GlobalCommandExecutor = async (context) => {
const child = context.spawnChild(process.execPath, ['-e', SCRIPT], { forwardInput: true });
const [code] = await once(child, 'close');
return { exitCode: typeof code === 'number' ? code : 1 };
};
await startHostAsync({
resolveRequestAsync: async () => ({
kind: 'global',
executor: executorAsync
})
});
const result: IPipedResult = await invokeAsync(input);
expect(result.code).toBe(7);
expect(result.stdout.equals(input)).toBe(true);
expect(result.stderr.toString()).toBe('pipe-ended');
},
15000
);
it.each([
{ args: ['--no-wait'], admission: { noWait: true } },
{ args: ['--wait-timeout=0.01'], admission: { waitTimeoutMs: 10 } }
])(
'forwards $args without leaking queue flags to scripts, which do not queue for admission',
async ({ args, admission }) => {
let started: () => void = () => {};
let release: () => void = () => {};
const running: Promise<void> = new Promise((resolve) => {
started = resolve;
});
const released: Promise<void> = new Promise((resolve) => {
release = resolve;
});
const runScriptAsync = jest.fn(async () => ({ exitCode: 0 }));
const holdAsync: GlobalCommandExecutor = async () => {
started();
await released;
return { exitCode: 0 };
};
await startHostAsync({
resolveRequestAsync: async ({ envelope }) => {
if (envelope.commandName === 'hold') return { kind: 'global', executor: holdAsync };
expect(envelope.argv).toEqual(['sample']);
expect(envelope.admission).toEqual(admission);
return { kind: 'global', executor: runScriptAsync };
}
});
const client: DaemonClient = await DaemonClient.connectAsync({ socketPath: host!.paths.socketPath });
const holding = client.executeAsync({
request: captureDaemonRequest({
argv: ['hold'],
commandName: 'hold',
commandOrigin: 'custom',
cwd: project,
environment: {},
terminal: { isTTY: false, supportsColor: false }
})
});
try {
await Promise.race([
running,
holding.then(() => {
throw new Error('The holding request finished before acquiring admission.');
})
]);
const result: IPipedResult = await invokeAsync(Buffer.alloc(0), true, args);
expect(result.code).toBe(0);
expect(result.stderr.toString()).not.toContain('daemon admission failed');
expect(runScriptAsync).toHaveBeenCalledTimes(1);
} finally {
release();
await holding;
await client.closeAsync();
}
},
15000
);
it('preserves every byte for native fallback when the host rejects before execution', async () => {
await startHostAsync({
resolveRequestAsync: async () => {
throw new DaemonRequestDispatchError('unsupported', 'No command integration in this test.');
}
});
const input: Buffer = Buffer.from('untouched stdin\n');
const native: IPipedResult = await invokeAsync(input, false);
const client: IPipedResult = await invokeAsync(input);
expect(client.code).toBe(native.code);
expect(client.stdout).toEqual(native.stdout);
expect(client.stderr.toString()).toContain('using in-process Rush');
expect(client.stderr.toString()).toContain('pipe-ended');
}, 15000);
});