Skip to content

Commit 21b7a1f

Browse files
committed
test(remote): cover artifact download errors, upload progress output, and Metro stop escalation
Cover the uncovered branches behind the #3421 CRAP findings through the owning modules' public entry points: - downloadRemoteArtifactFromUrl: HTTP error responses with status/body details, transport errors before the response starts, a timeout before materialization begins, and a directory download failure that must not touch the caller-owned root or leave staging behind. - createStderrUploadProgressReporter: all four event formats plus the byte-magnitude and percent-clamp helpers they exercise. - stopSpawnedMetroProcess via prepareMetroRuntime: ESRCH/EPERM on SIGTERM, SIGKILL escalation, ESRCH/EPERM on SIGKILL, and unexpected kill errors.
1 parent da46f4c commit 21b7a1f

3 files changed

Lines changed: 432 additions & 23 deletions

File tree

‎src/__tests__/client-metro-startup-cleanup.test.ts‎

Lines changed: 159 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ afterEach(() => {
2626
vi.unstubAllGlobals();
2727
});
2828

29-
test('prepareMetroRuntime stops a spawned Metro process when startup readiness times out', async () => {
30-
const tempRoot = mkdtempForTestSync('agent-device-metro-startup-cleanup-');
29+
function createMetroProject(label: string): string {
30+
const tempRoot = mkdtempForTestSync(`agent-device-metro-startup-cleanup-${label}-`);
3131
const projectRoot = path.join(tempRoot, 'project');
3232
fs.mkdirSync(path.join(projectRoot, 'node_modules'), { recursive: true });
3333
fs.writeFileSync(
@@ -40,39 +40,175 @@ test('prepareMetroRuntime stops a spawned Metro process when startup readiness t
4040
},
4141
}),
4242
);
43+
return projectRoot;
44+
}
4345

44-
vi.mocked(runCmdDetached).mockReturnValue(987);
45-
vi.mocked(waitForProcessExit).mockResolvedValue(true);
46-
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);
46+
function metroPrepareInput(projectRoot: string) {
47+
return {
48+
projectRoot,
49+
publicBaseUrl: 'https://public.example.test',
50+
metroPort: 8081,
51+
reuseExisting: true,
52+
installDependenciesIfNeeded: false,
53+
probeTimeoutMs: 10,
54+
startupTimeoutMs: 30_000,
55+
env: { ...process.env, AGENT_DEVICE_DAEMON_AUTH_TOKEN: 'daemon-token' },
56+
} as const;
57+
}
58+
59+
/** Starts a prepare whose Metro never becomes ready, letting readiness time out under fake timers. */
60+
async function runMetroPrepareThroughTimeout(projectRoot: string): Promise<void> {
4761
const fetchMock = vi.fn().mockResolvedValue({
4862
ok: true,
4963
status: 200,
5064
text: async () => 'packager-status:not-running',
5165
});
5266
vi.stubGlobal('fetch', fetchMock);
5367
vi.useFakeTimers();
68+
const preparePromise = prepareMetroRuntime(metroPrepareInput(projectRoot));
69+
const expectedFailure = assert.rejects(
70+
preparePromise,
71+
/React Native dev server did not become ready at http:\/\/127\.0\.0\.1:8081\/status within 30000ms/,
72+
);
73+
await vi.advanceTimersByTimeAsync(30_000);
74+
await expectedFailure;
75+
}
76+
77+
type KillSignal = 'SIGTERM' | 'SIGKILL';
78+
79+
function spyOnKill(behavior: (signal: KillSignal) => boolean): {
80+
signals: Array<[number, string]>;
81+
} {
82+
const signals: Array<[number, string]> = [];
83+
vi.spyOn(process, 'kill').mockImplementation(((pid: number, signal?: string | number) => {
84+
const name = (signal ?? 'SIGTERM') as KillSignal;
85+
signals.push([pid, name]);
86+
return behavior(name) as true;
87+
}) as typeof process.kill);
88+
return { signals };
89+
}
90+
91+
function killError(code: string): NodeJS.ErrnoException {
92+
return Object.assign(new Error(`kill failed: ${code}`), { code });
93+
}
94+
95+
test('prepareMetroRuntime stops a spawned Metro process when startup readiness times out', async () => {
96+
const projectRoot = createMetroProject('timeout');
97+
vi.mocked(runCmdDetached).mockReturnValue(987);
98+
vi.mocked(waitForProcessExit).mockResolvedValue(true);
99+
const kill = spyOnKill(() => true);
54100

55101
try {
56-
const preparePromise = prepareMetroRuntime({
57-
projectRoot,
58-
publicBaseUrl: 'https://public.example.test',
59-
metroPort: 8081,
60-
reuseExisting: true,
61-
installDependenciesIfNeeded: false,
62-
probeTimeoutMs: 10,
63-
startupTimeoutMs: 30_000,
64-
env: { ...process.env, AGENT_DEVICE_DAEMON_AUTH_TOKEN: 'daemon-token' },
102+
await runMetroPrepareThroughTimeout(projectRoot);
103+
assert.equal(vi.mocked(runCmdDetached).mock.calls.length, 1);
104+
assert.deepEqual(kill.signals, [[987, 'SIGTERM']]);
105+
assert.deepEqual(vi.mocked(waitForProcessExit).mock.calls, [[987, 1_000]]);
106+
} finally {
107+
fs.rmSync(path.dirname(projectRoot), { recursive: true, force: true });
108+
}
109+
});
110+
111+
test('stopSpawnedMetroProcess treats ESRCH or EPERM on SIGTERM as an already-stopped process', async () => {
112+
for (const code of ['ESRCH', 'EPERM']) {
113+
vi.clearAllMocks();
114+
const projectRoot = createMetroProject(`term-${code}`);
115+
vi.mocked(runCmdDetached).mockReturnValue(987);
116+
const kill = spyOnKill(() => {
117+
throw killError(code);
65118
});
66119

67-
const expectedFailure = assert.rejects(
68-
preparePromise,
69-
/React Native dev server did not become ready at http:\/\/127\.0\.0\.1:8081\/status within 30000ms/,
70-
);
71-
await vi.advanceTimersByTimeAsync(30_000);
72-
await expectedFailure;
73-
assert.equal(vi.mocked(runCmdDetached).mock.calls.length, 1);
74-
assert.deepEqual(killSpy.mock.calls[0], [987, 'SIGTERM']);
120+
try {
121+
await runMetroPrepareThroughTimeout(projectRoot);
122+
assert.deepEqual(kill.signals, [[987, 'SIGTERM']], `${code} on SIGTERM must stop cleanup`);
123+
assert.equal(vi.mocked(waitForProcessExit).mock.calls.length, 0, code);
124+
} finally {
125+
fs.rmSync(path.dirname(projectRoot), { recursive: true, force: true });
126+
}
127+
}
128+
});
129+
130+
test('stopSpawnedMetroProcess escalates to SIGKILL when SIGTERM does not exit the process', async () => {
131+
const projectRoot = createMetroProject('escalate');
132+
vi.mocked(runCmdDetached).mockReturnValue(987);
133+
vi.mocked(waitForProcessExit).mockResolvedValue(false);
134+
const kill = spyOnKill(() => true);
135+
136+
try {
137+
await runMetroPrepareThroughTimeout(projectRoot);
138+
assert.deepEqual(kill.signals, [
139+
[987, 'SIGTERM'],
140+
[987, 'SIGKILL'],
141+
]);
142+
assert.deepEqual(vi.mocked(waitForProcessExit).mock.calls, [
143+
[987, 1_000],
144+
[987, 1_000],
145+
]);
146+
} finally {
147+
fs.rmSync(path.dirname(projectRoot), { recursive: true, force: true });
148+
}
149+
});
150+
151+
test('stopSpawnedMetroProcess treats ESRCH or EPERM on SIGKILL as exited without waiting again', async () => {
152+
for (const code of ['ESRCH', 'EPERM']) {
153+
vi.clearAllMocks();
154+
const projectRoot = createMetroProject(`kill-${code}`);
155+
vi.mocked(runCmdDetached).mockReturnValue(987);
156+
vi.mocked(waitForProcessExit).mockResolvedValue(false);
157+
const kill = spyOnKill((signal) => {
158+
if (signal === 'SIGKILL') throw killError(code);
159+
return true;
160+
});
161+
162+
try {
163+
await runMetroPrepareThroughTimeout(projectRoot);
164+
assert.deepEqual(kill.signals, [
165+
[987, 'SIGTERM'],
166+
[987, 'SIGKILL'],
167+
]);
168+
assert.deepEqual(
169+
vi.mocked(waitForProcessExit).mock.calls,
170+
[[987, 1_000]],
171+
`${code} on SIGKILL means the process is already gone; no second exit wait`,
172+
);
173+
} finally {
174+
fs.rmSync(path.dirname(projectRoot), { recursive: true, force: true });
175+
}
176+
}
177+
});
178+
179+
test('prepareMetroRuntime still reports the readiness timeout when SIGKILL fails unexpectedly', async () => {
180+
const projectRoot = createMetroProject('kill-eacces');
181+
vi.mocked(runCmdDetached).mockReturnValue(987);
182+
vi.mocked(waitForProcessExit).mockResolvedValue(false);
183+
const kill = spyOnKill((signal) => {
184+
if (signal === 'SIGKILL') throw killError('EACCES');
185+
return true;
186+
});
187+
188+
try {
189+
await runMetroPrepareThroughTimeout(projectRoot);
190+
assert.deepEqual(kill.signals, [
191+
[987, 'SIGTERM'],
192+
[987, 'SIGKILL'],
193+
]);
194+
assert.deepEqual(vi.mocked(waitForProcessExit).mock.calls, [[987, 1_000]]);
195+
} finally {
196+
fs.rmSync(path.dirname(projectRoot), { recursive: true, force: true });
197+
}
198+
});
199+
200+
test('prepareMetroRuntime still reports the readiness timeout when SIGTERM fails unexpectedly', async () => {
201+
const projectRoot = createMetroProject('term-eacces');
202+
vi.mocked(runCmdDetached).mockReturnValue(987);
203+
const kill = spyOnKill(() => {
204+
throw killError('EACCES');
205+
});
206+
207+
try {
208+
await runMetroPrepareThroughTimeout(projectRoot);
209+
assert.deepEqual(kill.signals, [[987, 'SIGTERM']]);
210+
assert.equal(vi.mocked(waitForProcessExit).mock.calls.length, 0);
75211
} finally {
76-
fs.rmSync(tempRoot, { recursive: true, force: true });
212+
fs.rmSync(path.dirname(projectRoot), { recursive: true, force: true });
77213
}
78214
});
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
import { test } from 'vitest';
2+
import assert from 'node:assert/strict';
3+
import fs from 'node:fs';
4+
import net from 'node:net';
5+
import http from 'node:http';
6+
import path from 'node:path';
7+
import {
8+
closeLoopbackServer,
9+
listenOnLoopback,
10+
skipWhenLoopbackUnavailable,
11+
} from '../../__tests__/test-utils/loopback.ts';
12+
import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts';
13+
import { downloadRemoteArtifactFromUrl } from '../artifact-download.ts';
14+
15+
type DownloadParams = Parameters<typeof downloadRemoteArtifactFromUrl>[0];
16+
17+
function downloadTo(
18+
tempRoot: string,
19+
port: number,
20+
overrides: Partial<DownloadParams> = {},
21+
): Promise<string> {
22+
return downloadRemoteArtifactFromUrl({
23+
artifactUrl: new URL(`http://127.0.0.1:${port}/agent-device/artifacts/artifact`),
24+
token: 'remote-secret',
25+
artifactId: 'artifact',
26+
destinationPath: path.join(tempRoot, 'artifacts', 'screen.png'),
27+
requestScope: { requestId: 'req-artifact-download' },
28+
...overrides,
29+
});
30+
}
31+
32+
async function closedLoopbackPort(): Promise<number> {
33+
const server = net.createServer();
34+
const port = await listenOnLoopback(server);
35+
await closeLoopbackServer(server);
36+
return port;
37+
}
38+
39+
test('downloadRemoteArtifactFromUrl reports HTTP error responses with status and body', async (t) => {
40+
if (await skipWhenLoopbackUnavailable(t, 'artifact download error-response coverage')) return;
41+
const tempRoot = mkdtempForTestSync('agent-device-artifact-http-error-');
42+
const destinationPath = path.join(tempRoot, 'artifacts', 'screen.png');
43+
const server = http.createServer((_req, res) => {
44+
res.statusCode = 404;
45+
res.end('artifact expired');
46+
});
47+
const port = await listenOnLoopback(server);
48+
49+
try {
50+
await assert.rejects(
51+
() => downloadTo(tempRoot, port),
52+
(error: unknown) => {
53+
assert.equal(
54+
error instanceof Error && error.message === 'Failed to download remote artifact',
55+
true,
56+
);
57+
const details = (error as { details?: Record<string, unknown> }).details;
58+
assert.equal(details?.statusCode, 404);
59+
assert.equal(details?.body, 'artifact expired');
60+
assert.equal(details?.artifactId, 'artifact');
61+
assert.equal(details?.requestId, 'req-artifact-download');
62+
return true;
63+
},
64+
);
65+
assert.equal(fs.existsSync(destinationPath), false);
66+
} finally {
67+
await closeLoopbackServer(server);
68+
fs.rmSync(tempRoot, { recursive: true, force: true });
69+
}
70+
});
71+
72+
test('downloadRemoteArtifactFromUrl wraps transport errors raised before the response starts', async (t) => {
73+
if (await skipWhenLoopbackUnavailable(t, 'artifact download transport-error coverage')) return;
74+
const tempRoot = mkdtempForTestSync('agent-device-artifact-transport-error-');
75+
const port = await closedLoopbackPort();
76+
77+
try {
78+
await assert.rejects(
79+
() => downloadTo(tempRoot, port),
80+
(error: unknown) => {
81+
assert.equal(
82+
error instanceof Error && error.message === 'Failed to download remote artifact',
83+
true,
84+
);
85+
const wrapped = (error as { cause?: Error }).cause;
86+
assert.equal(wrapped instanceof Error, true);
87+
assert.equal((wrapped as NodeJS.ErrnoException | undefined)?.code, 'ECONNREFUSED');
88+
return true;
89+
},
90+
);
91+
assert.equal(fs.existsSync(path.join(tempRoot, 'artifacts', 'screen.png')), false);
92+
} finally {
93+
fs.rmSync(tempRoot, { recursive: true, force: true });
94+
}
95+
});
96+
97+
test('downloadRemoteArtifactFromUrl times out before response headers arrive without materializing', async (t) => {
98+
if (await skipWhenLoopbackUnavailable(t, 'artifact download pre-response timeout coverage'))
99+
return;
100+
const tempRoot = mkdtempForTestSync('agent-device-artifact-header-timeout-');
101+
const server = http.createServer(() => {
102+
// Accept the request and never answer, so the timeout fires before materialization starts.
103+
});
104+
const port = await listenOnLoopback(server);
105+
106+
try {
107+
await assert.rejects(
108+
() => downloadTo(tempRoot, port, { timeoutMs: 50 }),
109+
(error: unknown) => {
110+
assert.match(String((error as Error).message), /timed out/i);
111+
const details = (error as { details?: Record<string, unknown> }).details;
112+
assert.equal(details?.timeoutMs, 50);
113+
assert.equal(details?.artifactId, 'artifact');
114+
return true;
115+
},
116+
);
117+
assert.equal(fs.existsSync(path.join(tempRoot, 'artifacts', 'screen.png')), false);
118+
} finally {
119+
await closeLoopbackServer(server);
120+
fs.rmSync(tempRoot, { recursive: true, force: true });
121+
}
122+
});
123+
124+
test('downloadRemoteArtifactFromUrl leaves a caller-owned directory root untouched when the download fails', async (t) => {
125+
if (await skipWhenLoopbackUnavailable(t, 'artifact download directory-cleanup coverage')) return;
126+
const tempRoot = mkdtempForTestSync('agent-device-artifact-directory-error-');
127+
const artifactsRoot = path.join(tempRoot, 'remote-device-artifacts');
128+
fs.mkdirSync(artifactsRoot, { recursive: true });
129+
fs.writeFileSync(path.join(artifactsRoot, 'previous-run-marker.txt'), 'keep me');
130+
const server = http.createServer((_req, res) => {
131+
res.statusCode = 500;
132+
res.end('daemon exploded');
133+
});
134+
const port = await listenOnLoopback(server);
135+
136+
try {
137+
await assert.rejects(
138+
() =>
139+
downloadTo(tempRoot, port, {
140+
destinationPath: artifactsRoot,
141+
isDirectory: true,
142+
}),
143+
(error: unknown) => {
144+
assert.match(String((error as Error).message), /Failed to download remote artifact/);
145+
return true;
146+
},
147+
);
148+
assert.equal(
149+
fs.readFileSync(path.join(artifactsRoot, 'previous-run-marker.txt'), 'utf8'),
150+
'keep me',
151+
);
152+
assert.deepEqual(
153+
fs.readdirSync(artifactsRoot),
154+
['previous-run-marker.txt'],
155+
'a failed directory download must not leave staging behind',
156+
);
157+
} finally {
158+
await closeLoopbackServer(server);
159+
fs.rmSync(tempRoot, { recursive: true, force: true });
160+
}
161+
});

0 commit comments

Comments
 (0)