// SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Bryan Joshua Pedini import { spawn } from 'node:child_process'; import { HarnessError } from './errors'; export interface ProcResult { code: number | null; signal: string | null; stdout: string; stderr: string; durationMs: number; } export interface ProcOptions { input?: string | Buffer; timeoutMs?: number; env?: NodeJS.ProcessEnv; } export function run(command: string, args: readonly string[], opts: ProcOptions = {}): Promise { const timeoutMs = opts.timeoutMs ?? 120_000; const started = Date.now(); return new Promise((resolve, reject) => { let child; try { child = spawn(command, [...args], { env: opts.env ?? process.env, stdio: ['pipe', 'pipe', 'pipe'] }); } catch (e) { reject(new HarnessError('spawn', `cannot start ${command}: ${(e as Error).message}`)); return; } const out: Buffer[] = []; const err: Buffer[] = []; let timedOut = false; const timer = setTimeout(() => { timedOut = true; child.kill('SIGKILL'); }, timeoutMs); child.stdout.on('data', (b: Buffer) => out.push(b)); child.stderr.on('data', (b: Buffer) => err.push(b)); child.on('error', (e) => { clearTimeout(timer); reject(new HarnessError('spawn', `cannot start ${command}: ${e.message}`)); }); child.on('close', (code, signal) => { clearTimeout(timer); const result: ProcResult = { code, signal, stdout: Buffer.concat(out).toString('utf8'), stderr: Buffer.concat(err).toString('utf8'), durationMs: Date.now() - started, }; if (timedOut) { reject(new HarnessError('timeout', `${command} ${args.slice(0, 4).join(' ')} did not finish within ${timeoutMs} ms`, result)); return; } resolve(result); }); child.stdin.on('error', () => undefined); if (opts.input !== undefined) child.stdin.end(opts.input); else child.stdin.end(); }); } export async function runOk(command: string, args: readonly string[], opts: ProcOptions = {}): Promise { const r = await run(command, args, opts); if (r.code !== 0) { throw new HarnessError('infrastructure', `${command} ${args.join(' ')} exited with ${r.code}: ${r.stderr.trim().slice(-2000)}`, r); } return r; } export function sleep(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } export async function pollUntil(what: string, fn: () => Promise, timeoutMs = 30_000, intervalMs = 250): Promise { const deadline = Date.now() + timeoutMs; let lastError: unknown; for (;;) { try { const v = await fn(); if (v !== undefined && v !== null && v !== false) return v as T; } catch (e) { lastError = e; } if (Date.now() > deadline) { throw new HarnessError('timeout', `${what} did not happen within ${timeoutMs} ms${lastError ? `: ${(lastError as Error).message}` : ''}`); } await sleep(intervalMs); } }