/** * @file Helpers for the servers: run a script, and time and log a job. */ import { spawn } from 'node:child_process'; /** Run cmd with input on stdin; resolve to its stdout bytes, or reject with its stderr. */ export const runWith = (cmd, args, input) => new Promise((resolve, reject) => { const child = spawn(cmd, args, { stdio: ['pipe', 'pipe', 'pipe'] }); const out = [], err = []; child.stdout.on('data', (d) => out.push(d)); child.stderr.on('data', (d) => err.push(d)); child.on('error', reject); child.on('close', (code) => code === 0 ? resolve(Buffer.concat(out)) : reject(new Error(`${cmd} exit ${code}: ${Buffer.concat(err).toString().trim().slice(-500)}`))); child.stdin.end(input); }); /** Time a job and log how it went; failures are logged and rethrown. */ export const timed = async (what, job, describe) => { const t0 = Date.now(); try { const result = await job(); console.log(`${what} in ${Date.now() - t0} ms: ${describe(result)}`); return result; } catch (err) { console.error(`${what} failed after ${Date.now() - t0} ms: ${err.message}`); throw err; } };