Skip to content

Commit

Permalink
better timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
mydea committed Jul 11, 2023
1 parent 69a988c commit 97f60c3
Showing 1 changed file with 25 additions and 17 deletions.
42 changes: 25 additions & 17 deletions packages/e2e-tests/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,42 @@ interface SpawnOptions {
}

export function spawnAsync(cmd: string, options?: SpawnOptions, input?: string): Promise<SpawnAsync> {
const start = Date.now();
const timeoutMs = options?.timeout || 60_000 * 5;

return new Promise<SpawnAsync>(resolve => {
const cp = childProcess.spawn(cmd, { shell: true, ...options });

// Ensure we properly time out after max. 5 min per command
const timeout = setTimeout(() => {
let timeout: ReturnType<typeof setTimeout> | undefined = setTimeout(() => {
console.log(`Command "${cmd}" timed out after 5 minutes.`);
cp.kill();
}, 5 * 60_000);
end(null, `ETDIMEDOUT: Process timed out after ${timeoutMs} ms.`);
}, timeoutMs);

const stderr: unknown[] = [];
const stdout: string[] = [];
let error: Error | undefined;

function end(status: number | null, errorMessage?: string): void {
// This means we already ended
if (!timeout) {
return;
}

if (!error && errorMessage) {
error = new Error(errorMessage);
}

clearTimeout(timeout);
timeout = undefined;
resolve({
stdout: stdout.join(''),
stderr: stderr.join(''),
error: error || (status !== 0 ? new Error(`Process exited with status ${status}`) : undefined),
status,
});
}

cp.stdout.on('data', data => {
stdout.push(data ? (data as object).toString() : '');
});
Expand All @@ -53,20 +74,7 @@ export function spawnAsync(cmd: string, options?: SpawnOptions, input?: string):
});

cp.on('close', status => {
const end = Date.now();

// We manually mark this as timed out if the process takes too long
if (!error && status === 1 && options?.timeout && end >= start + options.timeout) {
error = new Error(`ETDIMEDOUT: Process timed out after ${options.timeout} ms.`);
}

clearTimeout(timeout);
resolve({
stdout: stdout.join(''),
stderr: stderr.join(''),
error: error || (status !== 0 ? new Error(`Process exited with status ${status}`) : undefined),
status,
});
end(status);
});

if (input) {
Expand Down

0 comments on commit 97f60c3

Please sign in to comment.