46 lines
1.5 KiB
JavaScript
46 lines
1.5 KiB
JavaScript
/**
|
|
* @file Helpers for the servers: run one command, and time and log a job.
|
|
* They reach only what they're given: spawn, and a clock.
|
|
*/
|
|
|
|
/**
|
|
* A command bound to one program and its arguments: run(input) feeds it stdin and
|
|
* resolves to its stdout bytes, or rejects with its stderr.
|
|
*
|
|
* @param {typeof import('node:child_process').spawn} spawn
|
|
* @param {string} cmd
|
|
* @param {string[]} args
|
|
*/
|
|
export const makeCommand = (spawn, 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.
|
|
*
|
|
* @template T
|
|
* @param {() => number} now milliseconds
|
|
* @param {string} what
|
|
* @param {() => Promise<T>} job
|
|
* @param {(result: T) => string} describe
|
|
*/
|
|
export const timed = async (now, what, job, describe) => {
|
|
const t0 = now();
|
|
try {
|
|
const result = await job();
|
|
console.log(`${what} in ${now() - t0} ms: ${describe(result)}`);
|
|
return result;
|
|
} catch (err) {
|
|
console.error(`${what} failed after ${now() - t0} ms: ${err.message}`);
|
|
throw err;
|
|
}
|
|
};
|