Improve process failure logic (#807)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 121a052 · Browse files · 7 files·+104 added−47 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+104 added−47 removed
- tests:+40 added−16 removed
- other:+64 added−31 removed
Provenance
- Commit
8ff263c- Tree
c3390a5- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
121a052
7 files changed+104 added−47 removed
modified:lib/error.js+35 added-21 removed
123456678891011121213141516161718192020212223242425262727282930313233343536373839404142434445464748495051525311 unmodified lines6566676849505169707172737475567677585960616263787980816667686982838485868766 unmodified linesimport {signalsByName} from 'human-signals';import stripFinalNewline from 'strip-final-newline';import {isBinary, binaryToString} from './stdio/utils.js';import {fixCwdError} from './cwd.js';
const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => {export const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => { if (timedOut) { return `timed out after ${timeout} milliseconds`; return `Command timed out after ${timeout} milliseconds`; }
if (isCanceled) { return 'was canceled'; return 'Command was canceled'; }
if (errorCode !== undefined) { return `failed with ${errorCode}`; return `Command failed with ${errorCode}`; }
if (signal !== undefined) { return `was killed with ${signal} (${signalDescription})`; return `Command was killed with ${signal} (${signalDescription})`; }
if (exitCode !== undefined) { return `failed with exit code ${exitCode}`; return `Command failed with exit code ${exitCode}`; }
return 'failed'; return 'Command failed';};
const getErrorSuffix = (error, cwd) => { if (error === undefined) { return {originalMessage: '', suffix: ''}; }
const originalErrorMessage = previousErrors.has(error) ? error.originalMessage : String(error?.message ?? error); const originalMessage = fixCwdError(originalErrorMessage, cwd); const suffix = `\n${originalMessage}`; return {originalMessage, suffix};};
// `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.// We normalize them to `undefined`export const normalizeExitPayload = (rawExitCode, rawSignal) => { const exitCode = rawExitCode === null ? undefined : rawExitCode; const signal = rawSignal === null ? undefined : rawSignal; const signalDescription = signal === undefined ? undefined : signalsByName[rawSignal].description; return {exitCode, signal, signalDescription};};
const serializeMessagePart = messagePart => Array.isArray(messagePart) ? messagePart.map(messageItem => serializeMessageItem(messageItem)).join('') : serializeMessageItem(messagePart);
11 unmodified lines
export const makeError = ({ stdio, all, error, signal, exitCode, error: rawError, signal: rawSignal, exitCode: rawExitCode, command, escapedCommand, timedOut, isCanceled, options: {timeoutDuration: timeout, cwd}, options: {timeoutDuration, timeout = timeoutDuration, cwd},}) => { // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`. // We normalize them to `undefined` exitCode = exitCode === null ? undefined : exitCode; signal = signal === null ? undefined : signal; const signalDescription = signal === undefined ? undefined : signalsByName[signal].description;
let error = rawError?.discarded ? undefined : rawError; const {exitCode, signal, signalDescription} = normalizeExitPayload(rawExitCode, rawSignal); const errorCode = error?.code; const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}); const execaMessage = `Command ${prefix}: ${command}`; const originalErrorMessage = previousErrors.has(error) ? error.originalMessage : String(error?.message ?? error); const originalMessage = fixCwdError(originalErrorMessage, cwd); const shortMessage = error === undefined ? execaMessage : `${execaMessage}\n${originalMessage}`; const {originalMessage, suffix} = getErrorSuffix(error, cwd); const shortMessage = `${prefix}: ${command}${suffix}`; const messageStdio = all === undefined ? [stdio[2], stdio[1]] : [all]; const message = [shortMessage, ...messageStdio, ...stdio.slice(3)] .map(messagePart => stripFinalNewline(serializeMessagePart(messagePart))) .filter(Boolean)66 unmodified linesmodified:lib/kill.js+20 added-1 removed
1 import {addAbortListener} from 'node:events';2 import os from 'node:os';3 import {setTimeout} from 'node:timers/promises';4 import {onExit} from 'signal-exit';5+import {normalizeExitPayload, getErrorPrefix} from './error.js';6 7 const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;8 9 // Monkey-patches `childProcess.kill()` to add `forceKillAfterDelay` behavior38 unmodified lines48 49 return forceKillAfterDelay;50 };51 52+export const waitForSuccessfulExit = async exitPromise => {53+ const [exitCode, signal] = await exitPromise;54+55+ if (!isProcessErrorExit(exitCode, signal) && isFailedExit(exitCode, signal)) {56+ const message = getErrorPrefix(normalizeExitPayload(exitCode, signal));57+ throw setDiscardedError(new Error(message));58+ }59+60+ return [exitCode, signal];61+};62+63+const isProcessErrorExit = (exitCode, signal) => exitCode === undefined && signal === undefined;64+export const isFailedExit = (exitCode, signal) => exitCode !== 0 || signal !== null;65+66 const killAfterTimeout = async (timeout, context, {signal}) => {67 await setTimeout(timeout, undefined, {signal});68 context.timedOut = true;54- throw new Error('Timed out');69+ const message = getErrorPrefix({timedOut: true, timeout});70+ throw setDiscardedError(new Error(message));71 };72 73 // `timeout` option handling74 export const throwOnTimeout = (timeout, context, controller) => timeout === 0 || timeout === undefined5 unmodified lines80 throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);81 }82 };83 84+// Indicates that the error is used only to interrupt control flow, but not in the return value85+const setDiscardedError = error => Object.assign(error, {discarded: true});86+87 // `cleanup` option handling88 export const cleanupOnExit = (spawned, {cleanup, detached}, {signal}) => {89 if (!cleanup || detached) {90 return;9 unmodified linesmodified:lib/stream.js+4 added-4 removed
1 unmodified line2 import {finished} from 'node:stream/promises';3 import {setImmediate} from 'node:timers/promises';4 import getStream, {getStreamAsArrayBuffer, getStreamAsArray} from 'get-stream';5 import mergeStreams from '@sindresorhus/merge-streams';6-import {throwOnTimeout} from './kill.js';6+import {waitForSuccessfulExit, throwOnTimeout} from './kill.js';7 import {isStandardStream} from './stdio/utils.js';8 import {generatorToDuplexStream} from './stdio/generator.js';9 10 // `all` interleaves `stdout` and `stderr`168 unmodified lines179 180 try {181 return await Promise.race([182 Promise.all([183- undefined,184- exitPromise,183+ {},184+ waitForSuccessfulExit(exitPromise),185 Promise.all(stdioPromises),186 allPromise,187 ...originalPromises,188 ...customStreamsEndPromises,3 unmodified lines192 ]);193 } catch (error) {194 spawned.kill();195 return Promise.all([196- error,196+ {error},197 exitPromise,198 Promise.all(stdioPromises.map(stdioPromise => getBufferedData(stdioPromise, encoding))),199 getBufferedData(allPromise, encoding),200 Promise.allSettled(originalPromises),4 unmodified linesmodified:test/stdio/node-stream.js+12 added-2 removed
132 unmodified lines133 waitedForDestroy = true;134 return error;135 }),136 });137- const childProcess = execa('forever.js', {stdout: [stream, 'pipe'], timeout: 1});138- const {timedOut} = await t.throwsAsync(childProcess);137+ const {timedOut} = await t.throwsAsync(execa('forever.js', {stdout: [stream, 'pipe'], timeout: 1}));138 t.true(timedOut);139 t.true(waitedForDestroy);140 });141 142+test('Handles custom streams destroy errors on process success', async t => {143+ const error = new Error('test');144+ const stream = new Writable({145+ destroy(destroyError, done) {146+ done(destroyError ?? error);147+ },148+ });149+ const thrownError = await t.throwsAsync(execa('empty.js', {stdout: [stream, 'pipe']}));150+ t.is(thrownError, error);151+});152+153 const testStreamEarlyExit = async (t, stream, streamName) => {154 await t.throwsAsync(execa('noop.js', {[streamName]: [stream, 'pipe'], uid: -1}));155 t.true(stream.destroyed);156 };97 unmodified linesmodified:test/error.js+18 added-9 removed
124 unmodified lines125 const {exitCode} = await execa('noop.js', ['foo']);126 t.is(exitCode, 0);127 });128 129-const testExitCode = async (t, number) => {130- const {exitCode} = await t.throwsAsync(131- execa('exit.js', [`${number}`]),132- {message: new RegExp(`failed with exit code ${number}`)},129+const testExitCode = async (t, expectedExitCode) => {130+ const {exitCode, originalMessage, shortMessage, message} = await t.throwsAsync(131+ execa('exit.js', [`${expectedExitCode}`]),132 );134- t.is(exitCode, number);133+ t.is(exitCode, expectedExitCode);134+ t.is(originalMessage, '');135+ t.is(shortMessage, `Command failed with exit code ${expectedExitCode}: exit.js ${expectedExitCode}`);136+ t.is(message, shortMessage);137 };138 139 test('exitCode is 2', testExitCode, 2);140 test('exitCode is 3', testExitCode, 3);65 unmodified lines206 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});207 208 subprocess.kill();209 208- const {isTerminated, signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});210+ const {isTerminated, signal, originalMessage, message, shortMessage} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});211 t.true(isTerminated);212 t.is(signal, 'SIGINT');213+ t.is(originalMessage, '');214+ t.is(shortMessage, 'Command was killed with SIGINT (User interruption with CTRL-C): forever.js');215+ t.is(message, shortMessage);216 });217 218 test('error.isTerminated is true if process was killed indirectly', async t => {219 const subprocess = execa('forever.js', {killSignal: 'SIGHUP'});112 unmodified lines332 333 const testUnusualError = async (t, error) => {334 const childProcess = execa('empty.js');335 childProcess.emit('error', error);331- const {message, originalMessage} = await t.throwsAsync(childProcess);332- t.true(message.includes(String(error)));336+ const {originalMessage, shortMessage, message} = await t.throwsAsync(childProcess);337 t.is(originalMessage, String(error));338+ t.true(shortMessage.includes(String(error)));339+ t.is(message, shortMessage);340 };341 342 test('error instance can be null', testUnusualError, null);343 test('error instance can be false', testUnusualError, false);6 unmodified lines350 351 test('error instance can be undefined', async t => {352 const childProcess = execa('empty.js');353 childProcess.emit('error');348- await t.throwsAsync(childProcess, {message: 'Command failed: empty.js'});354+ const {originalMessage, shortMessage, message} = await t.throwsAsync(childProcess);355+ t.is(originalMessage, '');356+ t.is(shortMessage, 'Command failed: empty.js');357+ t.is(message, shortMessage);358 });359 360 test('error instance can be a plain object', async t => {361 const childProcess = execa('empty.js');52 unmodified linesmodified:test/kill.js+10 added-5 removed
4 unmodified lines5 import test from 'ava';6 import {pEvent} from 'p-event';7 import isRunning from 'is-running';8 import {execa, execaSync} from '../index.js';9-import {setFixtureDir} from './helpers/fixtures-dir.js';9+import {setFixtureDir, FIXTURES_DIR} from './helpers/fixtures-dir.js';10 11 setFixtureDir();12 13 const isWindows = process.platform === 'win32';14-const TIMEOUT_REGEXP = /timed out after/;14 15 const spawnNoKillable = async (forceKillAfterDelay, options) => {16 const subprocess = execa('no-killable.js', {17 ipc: true,167 unmodified lines185 await subprocess;186 });187 188 test('timeout kills the process if it times out', async t => {190- const {isTerminated, signal, timedOut} = await t.throwsAsync(execa('forever.js', {timeout: 1}), {message: TIMEOUT_REGEXP});189+ const {isTerminated, signal, timedOut, originalMessage, shortMessage, message} = await t.throwsAsync(execa('forever.js', {timeout: 1}));190 t.true(isTerminated);191 t.is(signal, 'SIGTERM');192 t.true(timedOut);193+ t.is(originalMessage, '');194+ t.is(shortMessage, 'Command timed out after 1 milliseconds: forever.js');195+ t.is(message, shortMessage);196 });197 198 test('timeout kills the process if it times out, in sync mode', async t => {197- const {isTerminated, signal, timedOut} = await t.throws(() => {198- execaSync('forever.js', {timeout: 1, message: TIMEOUT_REGEXP});199+ const {isTerminated, signal, timedOut, originalMessage, shortMessage, message} = await t.throws(() => {200+ execaSync('node', ['forever.js'], {timeout: 1, cwd: FIXTURES_DIR});201 });202 t.true(isTerminated);203 t.is(signal, 'SIGTERM');204 t.true(timedOut);205+ t.is(originalMessage, 'spawnSync node ETIMEDOUT');206+ t.is(shortMessage, `Command timed out after 1 milliseconds: node forever.js\n${originalMessage}`);207+ t.is(message, shortMessage);208 });209 210 test('timeout does not kill the process if it does not time out', async t => {211 const {timedOut} = await execa('delay.js', ['500'], {timeout: 1e8});227 unmodified linesmodified:index.js+5 added-5 removed
8 unmodified lines9 import {makeError} from './lib/error.js';10 import {handleNodeOption} from './lib/node.js';11 import {handleInputAsync, pipeOutputAsync, cleanupStdioStreams} from './lib/stdio/async.js';12 import {handleInputSync, pipeOutputSync} from './lib/stdio/sync.js';13-import {spawnedKill, validateTimeout, normalizeForceKillAfterDelay, cleanupOnExit} from './lib/kill.js';13+import {spawnedKill, validateTimeout, normalizeForceKillAfterDelay, cleanupOnExit, isFailedExit} from './lib/kill.js';14 import {pipeToProcess} from './lib/pipe.js';15 import {getSpawnedResult, makeAllStream} from './lib/stream.js';16 import {mergePromise} from './lib/promise.js';17 import {joinCommand, getEscapedCommand} from './lib/escape.js';150 unmodified lines168 const handlePromise = async ({spawned, options, stdioStreamsGroups, originalStreams, command, escapedCommand, controller}) => {169 const context = {timedOut: false};170 171 const [172- error,172+ errorInfo,173 [exitCode, signal],174 stdioResults,175 allResult,176 ] = await getSpawnedResult({spawned, options, context, stdioStreamsGroups, originalStreams, controller});1 unmodified line178 179 const stdio = stdioResults.map(stdioResult => handleOutput(options, stdioResult));180 const all = handleOutput(options, allResult);181 182- if (error || exitCode !== 0 || signal !== null) {182+ if ('error' in errorInfo) {183 const isCanceled = options.signal?.aborted === true;184 const returnedError = makeError({185- error,185+ error: errorInfo.error,186 exitCode,187 signal,188 stdio,189 all,59 unmodified lines249 250 const output = result.output || Array.from({length: 3});251 const stdio = output.map(stdioOutput => handleOutput(options, stdioOutput));252 253- if (result.error || result.status !== 0 || result.signal !== null) {253+ if (result.error !== undefined || isFailedExit(result.status, result.signal)) {254 const error = makeError({255 stdio,256 error: result.error,257 signal: result.signal,96 unmodified lines