Skip to content
Myr

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

7 files+104 added−47 removed

modified:lib/error.js+35 added-21 removed
modified:lib/kill.js+20 added-1 removed
1import {addAbortListener} from 'node:events';2import os from 'node:os';3import {setTimeout} from 'node:timers/promises';4import {onExit} from 'signal-exit';5import {normalizeExitPayload, getErrorPrefix} from './error.js';67const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;89// Monkey-patches `childProcess.kill()` to add `forceKillAfterDelay` behavior
38 unmodified lines
4849 return forceKillAfterDelay;50};5152export const waitForSuccessfulExit = async exitPromise => {53 const [exitCode, signal] = await exitPromise;5455 if (!isProcessErrorExit(exitCode, signal) && isFailedExit(exitCode, signal)) {56 const message = getErrorPrefix(normalizeExitPayload(exitCode, signal));57 throw setDiscardedError(new Error(message));58 }5960 return [exitCode, signal];61};6263const isProcessErrorExit = (exitCode, signal) => exitCode === undefined && signal === undefined;64export const isFailedExit = (exitCode, signal) => exitCode !== 0 || signal !== null;6566const 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};7273// `timeout` option handling74export const throwOnTimeout = (timeout, context, controller) => timeout === 0 || timeout === undefined
5 unmodified lines
80 throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);81 }82};8384// Indicates that the error is used only to interrupt control flow, but not in the return value85const setDiscardedError = error => Object.assign(error, {discarded: true});8687// `cleanup` option handling88export const cleanupOnExit = (spawned, {cleanup, detached}, {signal}) => {89 if (!cleanup || detached) {90 return;
9 unmodified lines
modified:lib/stream.js+4 added-4 removed
1 unmodified line
2import {finished} from 'node:stream/promises';3import {setImmediate} from 'node:timers/promises';4import getStream, {getStreamAsArrayBuffer, getStreamAsArray} from 'get-stream';5import mergeStreams from '@sindresorhus/merge-streams';6import {throwOnTimeout} from './kill.js';6import {waitForSuccessfulExit, throwOnTimeout} from './kill.js';7import {isStandardStream} from './stdio/utils.js';8import {generatorToDuplexStream} from './stdio/generator.js';910// `all` interleaves `stdout` and `stderr`
168 unmodified lines
179180 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 lines
192 ]);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 lines
modified:test/stdio/node-stream.js+12 added-2 removed
132 unmodified lines
133 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});141142test('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});152153const 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 lines
modified:test/error.js+18 added-9 removed
124 unmodified lines
125 const {exitCode} = await execa('noop.js', ['foo']);126 t.is(exitCode, 0);127});128129const testExitCode = async (t, number) => {130 const {exitCode} = await t.throwsAsync(131 execa('exit.js', [`${number}`]),132 {message: new RegExp(`failed with exit code ${number}`)},129const 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};138139test('exitCode is 2', testExitCode, 2);140test('exitCode is 3', testExitCode, 3);
65 unmodified lines
206 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});207208 subprocess.kill();209208 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});217218test('error.isTerminated is true if process was killed indirectly', async t => {219 const subprocess = execa('forever.js', {killSignal: 'SIGHUP'});
112 unmodified lines
332333const 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};341342test('error instance can be null', testUnusualError, null);343test('error instance can be false', testUnusualError, false);
6 unmodified lines
350351test('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});359360test('error instance can be a plain object', async t => {361 const childProcess = execa('empty.js');
52 unmodified lines
modified:test/kill.js+10 added-5 removed
4 unmodified lines
5import test from 'ava';6import {pEvent} from 'p-event';7import isRunning from 'is-running';8import {execa, execaSync} from '../index.js';9import {setFixtureDir} from './helpers/fixtures-dir.js';9import {setFixtureDir, FIXTURES_DIR} from './helpers/fixtures-dir.js';1011setFixtureDir();1213const isWindows = process.platform === 'win32';14const TIMEOUT_REGEXP = /timed out after/;1415const spawnNoKillable = async (forceKillAfterDelay, options) => {16 const subprocess = execa('no-killable.js', {17 ipc: true,
167 unmodified lines
185 await subprocess;186});187188test('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});197198test('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});209210test('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 lines
modified:index.js+5 added-5 removed
8 unmodified lines
9import {makeError} from './lib/error.js';10import {handleNodeOption} from './lib/node.js';11import {handleInputAsync, pipeOutputAsync, cleanupStdioStreams} from './lib/stdio/async.js';12import {handleInputSync, pipeOutputSync} from './lib/stdio/sync.js';13import {spawnedKill, validateTimeout, normalizeForceKillAfterDelay, cleanupOnExit} from './lib/kill.js';13import {spawnedKill, validateTimeout, normalizeForceKillAfterDelay, cleanupOnExit, isFailedExit} from './lib/kill.js';14import {pipeToProcess} from './lib/pipe.js';15import {getSpawnedResult, makeAllStream} from './lib/stream.js';16import {mergePromise} from './lib/promise.js';17import {joinCommand, getEscapedCommand} from './lib/escape.js';
150 unmodified lines
168const handlePromise = async ({spawned, options, stdioStreamsGroups, originalStreams, command, escapedCommand, controller}) => {169 const context = {timedOut: false};170171 const [172 error,172 errorInfo,173 [exitCode, signal],174 stdioResults,175 allResult,176 ] = await getSpawnedResult({spawned, options, context, stdioStreamsGroups, originalStreams, controller});
1 unmodified line
178179 const stdio = stdioResults.map(stdioResult => handleOutput(options, stdioResult));180 const all = handleOutput(options, allResult);181182 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 lines
249250 const output = result.output || Array.from({length: 3});251 const stdio = output.map(stdioOutput => handleOutput(options, stdioOutput));252253 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