Add `error.isForcefullyTerminated` (#1111)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent ff02af6 · Browse files · 16 files·+228 added−55 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
16 files+228 added−55 removed
- tests:+112 added−34 removed
- other:+116 added−21 removed
Provenance
- Commit
e69985d- Tree
fdc709c- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
ff02af6
16 files changed+228 added−55 removed
modified:docs/api.md+10 added
667 unmodified lines668 - [Another process](termination.md#inter-process-termination). This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).669 670 [More info.](termination.md#signal-name-and-description)671 672+### error.isForcefullyTerminated673+674+_Type:_ `boolean`675+676+Whether the subprocess was terminated by the [`SIGKILL`](termination.md#sigkill) signal sent by the [`forceKillAfterDelay`](#optionsforcekillafterdelay) option.677+678+[More info.](termination.md#forceful-termination)679+680 ### error.exitCode681 682 _Type:_ `number | undefined`683 351 unmodified lines1035 _Default:_ `5000`1036 1037 If the subprocess is terminated but does not exit, forcefully exit it by sending [`SIGKILL`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGKILL).1038 1039+When this happens, [`error.isForcefullyTerminated`](#errorisforcefullyterminated) becomes `true`.1040+1041 [More info.](termination.md#forceful-termination)1042 1043 ### options.killSignal1044 125 unmodified linesmodified:docs/termination.md+2 added
150 unmodified lines151 If the subprocess is terminated but does not exit, [`SIGKILL`](#sigkill) is automatically sent to forcefully terminate it.152 153 The grace period is set by the [`forceKillAfterDelay`](api.md#optionsforcekillafterdelay) option, which is 5 seconds by default. This feature can be disabled with `false`.154 155+The [`error.isForcefullyTerminated`](api.md#errorisforcefullyterminated) boolean property can be used to check whether a subprocess was forcefully terminated by the `forceKillAfterDelay` option.156+157 This works when the subprocess is terminated by either:158 - Calling [`subprocess.kill()`](api.md#subprocesskillsignal-error) with no arguments.159 - The [`cancelSignal`](#canceling), [`timeout`](#timeout), [`maxBuffer`](output.md#big-output) or [`cleanup`](#current-process-exit) option.160 64 unmodified linesmodified:lib/methods/main-async.js+5 added-3 removed
100 unmodified lines1011021031041051061071081091101111121131141157 unmodified lines12312412512612712812913013113213313413213313413513613713813937 unmodified lines17717817918018118218318418514 unmodified lines100 unmodified lines const originalStreams = [...subprocess.stdio]; pipeOutputAsync(subprocess, fileDescriptors, controller); cleanupOnExit(subprocess, options, controller);
const context = {timedOut: false, isCanceled: false}; const onInternalError = createDeferred(); subprocess.kill = subprocessKill.bind(undefined, { kill: subprocess.kill.bind(subprocess), options, onInternalError, context, controller, }); subprocess.all = makeAllStream(subprocess, options); addConvertedStreams(subprocess, options);7 unmodified lines fileDescriptors, originalStreams, command, escapedCommand, context, onInternalError, controller, }); return {subprocess, promise};};
// Asynchronous logic, as opposed to the previous logic which can be run synchronously, i.e. can be returned to user right awayconst handlePromise = async ({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, onInternalError, controller}) => { const context = {timedOut: false, isCanceled: false};
const handlePromise = async ({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, context, onInternalError, controller}) => { const [ errorInfo, [exitCode, signal], stdioResults,37 unmodified lines escapedCommand, timedOut: context.timedOut, isCanceled: context.isCanceled, isMaxBuffer: errorInfo.error instanceof MaxBufferError, isForcefullyTerminated: context.isForcefullyTerminated, exitCode, signal, stdio, all,14 unmodified linesmodified:lib/methods/main-sync.js+1 added
154 unmodified lines155 escapedCommand,156 timedOut,157 isCanceled: false,158 isMaxBuffer,159+ isForcefullyTerminated: false,160 exitCode,161 signal,162 stdio,163 all,5 unmodified linesmodified:lib/resolve/exit-async.js+7 added-1 removed
6 unmodified lines7 // Since the `exit` event contains the signal name, we want to make sure we are listening for it.8 // This function also takes into account the following unlikely cases:9 // - `exit` being emitted in the same microtask as `spawn`10 // - `error` being emitted multiple times11-export const waitForExit = async subprocess => {11+export const waitForExit = async (subprocess, context) => {12+ const [exitCode, signal] = await waitForExitOrError(subprocess);13+ context.isForcefullyTerminated ??= false;14+ return [exitCode, signal];15+};16+17+const waitForExitOrError = async subprocess => {18 const [spawnPayload, exitPayload] = await Promise.allSettled([19 once(subprocess, 'spawn'),20 once(subprocess, 'exit'),21 ]);33 unmodified linesmodified:lib/resolve/wait-subprocess.js+1 added-1 removed
31 unmodified lines32 originalStreams,33 onInternalError,34 controller,35 }) => {36- const exitPromise = waitForExit(subprocess);36+ const exitPromise = waitForExit(subprocess, context);37 const streamInfo = {38 originalStreams,39 fileDescriptors,40 subprocess,88 unmodified linesmodified:lib/return/message.js+36 added-5 removed
2 unmodified lines3 import {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';4 import {fixCwdError} from '../arguments/cwd.js';5 import {escapeLines} from '../arguments/escape.js';6 import {getMaxBufferMessage} from '../io/max-buffer.js';7+import {getSignalDescription} from '../terminate/signal.js';8 import {DiscardedError, isExecaError} from './final-error.js';9 10 // Computes `error.message`, `error.shortMessage` and `error.originalMessage`11 export const createMessages = ({7 unmodified lines19 escapedCommand,20 timedOut,21 isCanceled,22 isMaxBuffer,23+ isForcefullyTerminated,24+ forceKillAfterDelay,25+ killSignal,26 maxBuffer,27 timeout,28 cwd,29 }) => {8 unmodified lines38 signal,39 signalDescription,40 exitCode,41 isCanceled,42+ isForcefullyTerminated,43+ forceKillAfterDelay,44+ killSignal,45 });46 const originalMessage = getOriginalMessage(originalError, cwd);47 const suffix = originalMessage === undefined ? '' : `\n${originalMessage}`;48 const shortMessage = `${prefix}: ${escapedCommand}${suffix}`;9 unmodified lines58 .join('\n\n');59 return {originalMessage, shortMessage, message};60 };61 55-const getErrorPrefix = ({originalError, timedOut, timeout, isMaxBuffer, maxBuffer, errorCode, signal, signalDescription, exitCode, isCanceled}) => {62+const getErrorPrefix = ({63+ originalError,64+ timedOut,65+ timeout,66+ isMaxBuffer,67+ maxBuffer,68+ errorCode,69+ signal,70+ signalDescription,71+ exitCode,72+ isCanceled,73+ isForcefullyTerminated,74+ forceKillAfterDelay,75+ killSignal,76+}) => {77+ const forcefulSuffix = getForcefulSuffix(isForcefullyTerminated, forceKillAfterDelay);78+79 if (timedOut) {57- return `Command timed out after ${timeout} milliseconds`;80+ return `Command timed out after ${timeout} milliseconds${forcefulSuffix}`;81 }82 83 if (isCanceled) {61- return 'Command was canceled';84+ return `Command was canceled${forcefulSuffix}`;85 }86 87 if (isMaxBuffer) {65- return getMaxBufferMessage(originalError, maxBuffer);88+ return `${getMaxBufferMessage(originalError, maxBuffer)}${forcefulSuffix}`;89 }90 91 if (errorCode !== undefined) {69- return `Command failed with ${errorCode}`;92+ return `Command failed with ${errorCode}${forcefulSuffix}`;93 }94 95+ if (isForcefullyTerminated) {96+ return `Command was killed with ${killSignal} (${getSignalDescription(killSignal)})${forcefulSuffix}`;97+ }98+99 if (signal !== undefined) {100 return `Command was killed with ${signal} (${signalDescription})`;101 }102 3 unmodified lines106 107 return 'Command failed';108 };109 110+const getForcefulSuffix = (isForcefullyTerminated, forceKillAfterDelay) => isForcefullyTerminated111+ ? ` and was forcefully terminated after ${forceKillAfterDelay} milliseconds`112+ : '';113+114 const getOriginalMessage = (originalError, cwd) => {115 if (originalError instanceof DiscardedError) {116 return;117 }27 unmodified linesmodified:lib/return/result.js+19 added-3 removed
1-import {signalsByName} from 'human-signals';1+import {getSignalDescription} from '../terminate/signal.js';2 import {getDurationMs} from './duration.js';3 import {getFinalError} from './final-error.js';4 import {createMessages} from './message.js';5 15 unmodified lines21 timedOut: false,22 isCanceled: false,23 isTerminated: false,24 isMaxBuffer: false,25+ isForcefullyTerminated: false,26 exitCode: 0,27 stdout: stdio[1],28 stderr: stdio[2],29 all,18 unmodified lines48 startTime,49 timedOut: false,50 isCanceled: false,51 isMaxBuffer: false,52+ isForcefullyTerminated: false,53 stdio: Array.from({length: fileDescriptors.length}),54 ipcOutput: [],55 options,56 isSync,7 unmodified lines64 startTime,65 timedOut,66 isCanceled,67 isMaxBuffer,68+ isForcefullyTerminated,69 exitCode: rawExitCode,70 signal: rawSignal,71 stdio,72 all,73 ipcOutput,71- options: {timeoutDuration, timeout = timeoutDuration, cwd, maxBuffer},74+ options: {75+ timeoutDuration,76+ timeout = timeoutDuration,77+ forceKillAfterDelay,78+ killSignal,79+ cwd,80+ maxBuffer,81+ },82 isSync,83 }) => {84 const {exitCode, signal, signalDescription} = normalizeExitPayload(rawExitCode, rawSignal);85 const {originalMessage, shortMessage, message} = createMessages({7 unmodified lines93 escapedCommand,94 timedOut,95 isCanceled,96 isMaxBuffer,97+ isForcefullyTerminated,98+ forceKillAfterDelay,99+ killSignal,100 maxBuffer,101 timeout,102 cwd,103 });5 unmodified lines109 startTime,110 timedOut,111 isCanceled,112 isMaxBuffer,113+ isForcefullyTerminated,114 exitCode,115 signal,116 signalDescription,117 stdio,13 unmodified lines131 startTime,132 timedOut,133 isCanceled,134 isMaxBuffer,135+ isForcefullyTerminated,136 exitCode,137 signal,138 signalDescription,139 stdio,13 unmodified lines153 timedOut,154 isCanceled,155 isTerminated: signal !== undefined,156 isMaxBuffer,157+ isForcefullyTerminated,158 exitCode,159 signal,160 signalDescription,161 code: error.cause?.code,11 unmodified lines173 // We normalize them to `undefined`174 const normalizeExitPayload = (rawExitCode, rawSignal) => {175 const exitCode = rawExitCode === null ? undefined : rawExitCode;176 const signal = rawSignal === null ? undefined : rawSignal;161- const signalDescription = signal === undefined ? undefined : signalsByName[rawSignal].description;177+ const signalDescription = signal === undefined ? undefined : getSignalDescription(rawSignal);178 return {exitCode, signal, signalDescription};179 };modified:lib/terminate/kill.js+20 added-8 removed
21 unmodified lines22 const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;23 24 // Monkey-patches `subprocess.kill()` to add `forceKillAfterDelay` behavior and `.kill(error)`25 export const subprocessKill = (26- {kill, options: {forceKillAfterDelay, killSignal}, onInternalError, controller},26+ {kill, options: {forceKillAfterDelay, killSignal}, onInternalError, context, controller},27 signalOrError,28 errorArgument,29 ) => {30 const {signal, error} = parseKillArguments(signalOrError, errorArgument, killSignal);4 unmodified lines35 signal,36 forceKillAfterDelay,37 killSignal,38 killResult,39+ context,40 controller,41 });42 return killResult;43 };22 unmodified lines66 onInternalError.reject(error);67 }68 };69 69-const setKillTimeout = async ({kill, signal, forceKillAfterDelay, killSignal, killResult, controller}) => {70- if (!shouldForceKill(signal, forceKillAfterDelay, killSignal, killResult)) {70+const setKillTimeout = async ({kill, signal, forceKillAfterDelay, killSignal, killResult, context, controller}) => {71+ if (signal === killSignal && killResult) {72+ killOnTimeout({73+ kill,74+ forceKillAfterDelay,75+ context,76+ controllerSignal: controller.signal,77+ });78+ }79+};80+81+// Forcefully terminate a subprocess after a timeout82+export const killOnTimeout = async ({kill, forceKillAfterDelay, context, controllerSignal}) => {83+ if (forceKillAfterDelay === false) {84 return;85 }86 87 try {75- await setTimeout(forceKillAfterDelay, undefined, {signal: controller.signal});76- kill('SIGKILL');88+ await setTimeout(forceKillAfterDelay, undefined, {signal: controllerSignal});89+ if (kill('SIGKILL')) {90+ context.isForcefullyTerminated ??= true;91+ }92 } catch {}93 };94 80-const shouldForceKill = (signal, forceKillAfterDelay, killSignal, killResult) => signal === killSignal81- && forceKillAfterDelay !== false82- && killResult;modified:lib/terminate/signal.js+4 added
1 import {constants} from 'node:os';2+import {signalsByName} from 'human-signals';3 4 // Normalize signals for comparison purpose.5 // Also validate the signal exists.6 export const normalizeKillSignal = killSignal => {57 unmodified lines64 65 const getAvailableSignalIntegers = () => [...new Set(Object.values(constants.signals)66 .sort((signalInteger, signalIntegerTwo) => signalInteger - signalIntegerTwo))]67 .join(', ');68+69+// Human-friendly description of a signal70+export const getSignalDescription = signal => signalsByName[signal].description;modified:test/return/result.js+2 added
18 unmodified lines19 'timedOut',20 'isCanceled',21 'isTerminated',22 'isMaxBuffer',23+ 'isForcefullyTerminated',24 'exitCode',25 'stdout',26 'stderr',27 'all',21 unmodified lines49 'timedOut',50 'isCanceled',51 'isTerminated',52 'isMaxBuffer',53+ 'isForcefullyTerminated',54 'exitCode',55 'stdout',56 'stderr',57 'all',88 unmodified linesmodified:test/terminate/cancel.js+9 added-9 removed
122 unmodified lines123 });124 125 test('calling abort with no argument keeps error properties', async t => {126 const abortController = new AbortController();127- const subprocess = execa('noop.js', {cancelSignal: abortController.signal});127+ const subprocess = execa('empty.js', {cancelSignal: abortController.signal});128 abortController.abort();129 const {cause, originalMessage, shortMessage, message} = await t.throwsAsync(subprocess);130 t.is(cause.message, 'This operation was aborted');131 t.is(cause.name, 'AbortError');132 t.is(originalMessage, 'This operation was aborted');133- t.is(shortMessage, 'Command was canceled: noop.js\nThis operation was aborted');134- t.is(message, 'Command was canceled: noop.js\nThis operation was aborted');133+ t.is(shortMessage, 'Command was canceled: empty.js\nThis operation was aborted');134+ t.is(message, 'Command was canceled: empty.js\nThis operation was aborted');135 });136 137 test('calling abort with an error instance keeps error properties', async t => {138 const abortController = new AbortController();139- const subprocess = execa('noop.js', {cancelSignal: abortController.signal});139+ const subprocess = execa('empty.js', {cancelSignal: abortController.signal});140 const error = new Error(foobarString);141 error.code = foobarString;142 abortController.abort(error);143 const {cause, originalMessage, shortMessage, message, code} = await t.throwsAsync(subprocess);144 t.is(cause, error);145 t.is(originalMessage, foobarString);146- t.is(shortMessage, `Command was canceled: noop.js\n${foobarString}`);147- t.is(message, `Command was canceled: noop.js\n${foobarString}`);146+ t.is(shortMessage, `Command was canceled: empty.js\n${foobarString}`);147+ t.is(message, `Command was canceled: empty.js\n${foobarString}`);148 t.is(code, foobarString);149 });150 151 test('calling abort with null keeps error properties', async t => {152 const abortController = new AbortController();153- const subprocess = execa('noop.js', {cancelSignal: abortController.signal});153+ const subprocess = execa('empty.js', {cancelSignal: abortController.signal});154 abortController.abort(null);155 const {cause, originalMessage, shortMessage, message} = await t.throwsAsync(subprocess);156 t.is(cause, null);157 t.is(originalMessage, 'null');158- t.is(shortMessage, 'Command was canceled: noop.js\nnull');159- t.is(message, 'Command was canceled: noop.js\nnull');158+ t.is(shortMessage, 'Command was canceled: empty.js\nnull');159+ t.is(message, 'Command was canceled: empty.js\nnull');160 });161 162 test('calling abort twice should show the same behaviour as calling it once', async t => {163 const abortController = new AbortController();28 unmodified linesmodified:test/terminate/kill-force.js+101 added-25 removed
5 unmodified lines6 import isRunning from 'is-running';7 import {execa} from '../../index.js';8 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';9 import {assertMaxListeners} from '../helpers/listeners.js';10+import {foobarString} from '../helpers/input.js';11+import {getEarlyErrorSubprocess} from '../helpers/early-error.js';12 13 setFixtureDirectory();14 15 const isWindows = process.platform === 'win32';7 unmodified lines23 await subprocess.getOneMessage();24 return {subprocess};25 };26 27+const noKillableSimpleOptions = {killSignal: 'SIGWINCH', forceKillAfterDelay: 1};25-const spawnNoKillableSimple = options => execa('forever.js', {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, ...options});28+const spawnNoKillableSimple = options => execa('forever.js', {...noKillableSimpleOptions, ...options});29 30 test('kill("SIGKILL") should terminate cleanly', async t => {31 const {subprocess} = await spawnNoKillable();32 33 subprocess.kill('SIGKILL');34 32- const {isTerminated, signal} = await t.throwsAsync(subprocess);35+ const {isTerminated, signal, isForcefullyTerminated, shortMessage} = await t.throwsAsync(subprocess);36 t.true(isTerminated);37 t.is(signal, 'SIGKILL');38+ t.false(isForcefullyTerminated);39+ t.is(shortMessage, 'Command was killed with SIGKILL (Forced termination): no-killable.js');40 });41 42 const testInvalidForceKill = async (t, forceKillAfterDelay) => {43 t.throws(() => {7 unmodified lines51 // `SIGTERM` cannot be caught on Windows, and it always aborts the subprocess (like `SIGKILL` on Unix).52 // Therefore, this feature and those tests must be different on Windows.53 if (isWindows) {54 test('Can call `.kill()` with `forceKillAfterDelay` on Windows', async t => {50- const {subprocess} = await spawnNoKillable(1);55+ const {subprocess} = await spawnNoKillable();56 subprocess.kill();57 53- const {isTerminated, signal} = await t.throwsAsync(subprocess);58+ const {isTerminated, signal, isForcefullyTerminated, shortMessage} = await t.throwsAsync(subprocess);59 t.true(isTerminated);60 t.is(signal, 'SIGTERM');61+ t.false(isForcefullyTerminated);62+ t.is(shortMessage, 'Command was killed with SIGTERM (Termination): no-killable.js');63 });64 } else {65 const testNoForceKill = async (t, forceKillAfterDelay, killArgument, options) => {66 const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);3 unmodified lines70 await setTimeout(6e3);71 t.true(isRunning(subprocess.pid));72 subprocess.kill('SIGKILL');73 67- const {isTerminated, signal} = await t.throwsAsync(subprocess);74+ const {isTerminated, signal, isForcefullyTerminated} = await t.throwsAsync(subprocess);75 t.true(isTerminated);76 t.is(signal, 'SIGKILL');77+ t.false(isForcefullyTerminated);78 };79 80 test('`forceKillAfterDelay: false` should not kill after a timeout', testNoForceKill, false);81 test('`forceKillAfterDelay` should not kill after a timeout with other signals', testNoForceKill, true, 'SIGINT');82 test('`forceKillAfterDelay` should not kill after a timeout with wrong killSignal string', testNoForceKill, true, 'SIGTERM', {killSignal: 'SIGINT'});83 test('`forceKillAfterDelay` should not kill after a timeout with wrong killSignal number', testNoForceKill, true, constants.signals.SIGTERM, {killSignal: constants.signals.SIGINT});84 85+ // eslint-disable-next-line max-params77- const testForceKill = async (t, forceKillAfterDelay, killArgument, options) => {86+ const testForceKill = async (t, forceKillAfterDelay, killSignal, expectedDelay, expectedKillSignal, options) => {87 const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);88 80- subprocess.kill(killArgument);89+ subprocess.kill(killSignal);90 82- const {isTerminated, signal} = await t.throwsAsync(subprocess);91+ const {isTerminated, signal, isForcefullyTerminated, shortMessage} = await t.throwsAsync(subprocess);92 t.true(isTerminated);93 t.is(signal, 'SIGKILL');94+ t.true(isForcefullyTerminated);95+ const messageSuffix = killSignal instanceof Error ? `\n${killSignal.message}` : '';96+ const signalDescription = expectedKillSignal === 'SIGINT' ? 'User interruption with CTRL-C' : 'Termination';97+ t.is(shortMessage, `Command was killed with ${expectedKillSignal} (${signalDescription}) and was forcefully terminated after ${expectedDelay} milliseconds: no-killable.js${messageSuffix}`);98 };99 87- test('`forceKillAfterDelay: number` should kill after a timeout', testForceKill, 50);88- test('`forceKillAfterDelay: true` should kill after a timeout', testForceKill, true);89- test('`forceKillAfterDelay: undefined` should kill after a timeout', testForceKill, undefined);90- test('`forceKillAfterDelay` should kill after a timeout with SIGTERM', testForceKill, 50, 'SIGTERM');91- test('`forceKillAfterDelay` should kill after a timeout with the killSignal string', testForceKill, 50, 'SIGINT', {killSignal: 'SIGINT'});92- test('`forceKillAfterDelay` should kill after a timeout with the killSignal string, mixed', testForceKill, 50, 'SIGINT', {killSignal: constants.signals.SIGINT});93- test('`forceKillAfterDelay` should kill after a timeout with the killSignal number', testForceKill, 50, constants.signals.SIGINT, {killSignal: constants.signals.SIGINT});94- test('`forceKillAfterDelay` should kill after a timeout with the killSignal number, mixed', testForceKill, 50, constants.signals.SIGINT, {killSignal: 'SIGINT'});95- test('`forceKillAfterDelay` should kill after a timeout with an error', testForceKill, 50, new Error('test'));96- test('`forceKillAfterDelay` should kill after a timeout with an error and a killSignal', testForceKill, 50, new Error('test'), {killSignal: 'SIGINT'});100+ test('`forceKillAfterDelay: number` should kill after a timeout', testForceKill, 50, undefined, 50, 'SIGTERM');101+ test('`forceKillAfterDelay: true` should kill after a timeout', testForceKill, true, undefined, 5e3, 'SIGTERM');102+ test('`forceKillAfterDelay: undefined` should kill after a timeout', testForceKill, undefined, undefined, 5e3, 'SIGTERM');103+ test('`forceKillAfterDelay` should kill after a timeout with SIGTERM', testForceKill, 50, 'SIGTERM', 50, 'SIGTERM');104+ test('`forceKillAfterDelay` should kill after a timeout with the killSignal string', testForceKill, 50, 'SIGINT', 50, 'SIGINT', {killSignal: 'SIGINT'});105+ test('`forceKillAfterDelay` should kill after a timeout with the killSignal string, mixed', testForceKill, 50, 'SIGINT', 50, 'SIGINT', {killSignal: constants.signals.SIGINT});106+ test('`forceKillAfterDelay` should kill after a timeout with the killSignal number', testForceKill, 50, constants.signals.SIGINT, 50, 'SIGINT', {killSignal: constants.signals.SIGINT});107+ test('`forceKillAfterDelay` should kill after a timeout with the killSignal number, mixed', testForceKill, 50, constants.signals.SIGINT, 50, 'SIGINT', {killSignal: 'SIGINT'});108+ test('`forceKillAfterDelay` should kill after a timeout with an error', testForceKill, 50, new Error('test'), 50, 'SIGTERM');109+ test('`forceKillAfterDelay` should kill after a timeout with an error and a killSignal', testForceKill, 50, new Error('test'), 50, 'SIGINT', {killSignal: 'SIGINT'});110 98- test('`forceKillAfterDelay` works with the "signal" option', async t => {111+ test('`forceKillAfterDelay` works with the "cancelSignal" option', async t => {112 const abortController = new AbortController();113 const subprocess = spawnNoKillableSimple({cancelSignal: abortController.signal});114 await once(subprocess, 'spawn');102- abortController.abort();103- const {isTerminated, signal, isCanceled} = await t.throwsAsync(subprocess);115+ abortController.abort('');116+ const {isTerminated, signal, isCanceled, isForcefullyTerminated, shortMessage} = await t.throwsAsync(subprocess);117 t.true(isTerminated);118 t.is(signal, 'SIGKILL');119 t.true(isCanceled);120+ t.true(isForcefullyTerminated);121+ t.is(shortMessage, 'Command was canceled and was forcefully terminated after 1 milliseconds: forever.js');122 });123 124 test('`forceKillAfterDelay` works with the "timeout" option', async t => {110- const subprocess = spawnNoKillableSimple({timeout: 1});111- const {isTerminated, signal, timedOut} = await t.throwsAsync(subprocess);125+ const {isTerminated, signal, timedOut, isForcefullyTerminated, shortMessage} = await t.throwsAsync(spawnNoKillableSimple({timeout: 1}));126 t.true(isTerminated);127 t.is(signal, 'SIGKILL');128 t.true(timedOut);129+ t.true(isForcefullyTerminated);130+ t.is(shortMessage, 'Command timed out after 1 milliseconds and was forcefully terminated after 1 milliseconds: forever.js');131 });132 133+ test('`forceKillAfterDelay` works with the "maxBuffer" option', async t => {134+ const subprocess = execa('noop-forever.js', ['.'], {...noKillableSimpleOptions, maxBuffer: 1});135+ const [chunk] = await once(subprocess.stdout, 'data');136+ t.is(chunk.toString(), '.\n');137+ subprocess.kill();138+ const {isTerminated, signal, isForcefullyTerminated, shortMessage} = await t.throwsAsync(subprocess);139+ t.true(isTerminated);140+ t.is(signal, 'SIGKILL');141+ t.true(isForcefullyTerminated);142+ t.is(shortMessage, 'Command\'s stdout was larger than 1 characters and was forcefully terminated after 1 milliseconds: noop-forever.js .\nmaxBuffer exceeded');143+ });144+145+ test('`forceKillAfterDelay` works with the "error" event', async t => {146+ const subprocess = spawnNoKillableSimple();147+ await once(subprocess, 'spawn');148+ const error = new Error(foobarString);149+ error.code = 'ECODE';150+ subprocess.emit('error', error);151+ subprocess.kill();152+ const {isTerminated, signal, isForcefullyTerminated, shortMessage, originalMessage, cause} = await t.throwsAsync(subprocess);153+ t.true(isTerminated);154+ t.is(signal, 'SIGKILL');155+ t.true(isForcefullyTerminated);156+ t.is(cause, error);157+ t.is(originalMessage, error.message);158+ t.is(shortMessage, `Command failed with ${error.code} and was forcefully terminated after 1 milliseconds: forever.js\n${error.message}`);159+ });160+161 test.serial('Can call `.kill()` with `forceKillAfterDelay` many times without triggering the maxListeners warning', async t => {162 const checkMaxListeners = assertMaxListeners(t);163 164 const subprocess = spawnNoKillableSimple();165 for (let index = 0; index < defaultMaxListeners + 1; index += 1) {166 subprocess.kill();167 }168 125- const {isTerminated, signal} = await t.throwsAsync(subprocess);169+ const {isTerminated, signal, isForcefullyTerminated} = await t.throwsAsync(subprocess);170 t.true(isTerminated);171 t.is(signal, 'SIGKILL');172+ t.true(isForcefullyTerminated);173 174 checkMaxListeners();175 });176 1 unmodified line178 const subprocess = spawnNoKillableSimple();179 subprocess.kill();180 subprocess.kill();181 137- const {isTerminated, signal} = await t.throwsAsync(subprocess);182+ const {isTerminated, signal, isForcefullyTerminated} = await t.throwsAsync(subprocess);183 t.true(isTerminated);184 t.is(signal, 'SIGKILL');185+ t.true(isForcefullyTerminated);186 });187 }188+189+test('result.isForcefullyTerminated is false on success', async t => {190+ const {isForcefullyTerminated} = await execa('empty.js');191+ t.false(isForcefullyTerminated);192+});193+194+test('error.isForcefullyTerminated is false on spawn errors', async t => {195+ const {isForcefullyTerminated} = await t.throwsAsync(getEarlyErrorSubprocess());196+ t.false(isForcefullyTerminated);197+});198+199+test('error.isForcefullyTerminated is false when already terminated', async t => {200+ const abortController = new AbortController();201+ const final = async function * () {202+ try {203+ await setTimeout(1e6, undefined, {signal: abortController.signal});204+ } catch {}205+206+ yield * [];207+ };208+209+ const subprocess = execa('forever.js', {stdout: {final}});210+ subprocess.kill();211+ await setTimeout(6e3);212+ abortController.abort();213+ const {isForcefullyTerminated, isTerminated, signal} = await t.throwsAsync(subprocess);214+ t.false(isForcefullyTerminated);215+ t.true(isTerminated);216+ t.is(signal, 'SIGTERM');217+});modified:test-d/return/result-main.test-d.ts+4 added
27 unmodified lines28 expectType<boolean>(unicornsResult.timedOut);29 expectType<boolean>(unicornsResult.isCanceled);30 expectType<boolean>(unicornsResult.isTerminated);31 expectType<boolean>(unicornsResult.isMaxBuffer);32+expectType<boolean>(unicornsResult.isForcefullyTerminated);33 expectType<keyof SignalConstants | undefined>(unicornsResult.signal);34 expectType<string | undefined>(unicornsResult.signalDescription);35 expectType<string>(unicornsResult.cwd);36 expectType<number>(unicornsResult.durationMs);8 unmodified lines45 expectType<boolean>(unicornsResultSync.timedOut);46 expectType<boolean>(unicornsResultSync.isCanceled);47 expectType<boolean>(unicornsResultSync.isTerminated);48 expectType<boolean>(unicornsResultSync.isMaxBuffer);49+expectType<boolean>(unicornsResultSync.isForcefullyTerminated);50 expectType<keyof SignalConstants | undefined>(unicornsResultSync.signal);51 expectType<string | undefined>(unicornsResultSync.signalDescription);52 expectType<string>(unicornsResultSync.cwd);53 expectType<number>(unicornsResultSync.durationMs);9 unmodified lines63 expectType<boolean>(error.timedOut);64 expectType<boolean>(error.isCanceled);65 expectType<boolean>(error.isTerminated);66 expectType<boolean>(error.isMaxBuffer);67+ expectType<boolean>(error.isForcefullyTerminated);68 expectType<keyof SignalConstants | undefined>(error.signal);69 expectType<string | undefined>(error.signalDescription);70 expectType<string>(error.cwd);71 expectType<number>(error.durationMs);14 unmodified lines86 expectType<boolean>(errorSync.timedOut);87 expectType<boolean>(errorSync.isCanceled);88 expectType<boolean>(errorSync.isTerminated);89 expectType<boolean>(errorSync.isMaxBuffer);90+ expectType<boolean>(errorSync.isForcefullyTerminated);91 expectType<keyof SignalConstants | undefined>(errorSync.signal);92 expectType<string | undefined>(errorSync.signalDescription);93 expectType<string>(errorSync.cwd);94 expectType<number>(errorSync.durationMs);6 unmodified linesmodified:types/arguments/options.d.ts+2 added
277 unmodified lines278 279 /**280 If the subprocess is terminated but does not exit, forcefully exit it by sending [`SIGKILL`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGKILL).281 282+ When this happens, `error.isForcefullyTerminated` becomes `true`.283+284 @default 5000285 */286 readonly forceKillAfterDelay?: Unless<IsSync, number | false>;287 97 unmodified linesmodified:types/return/result.d.ts+5 added
111 unmodified lines112 */113 isTerminated: boolean;114 115 /**116+ Whether the subprocess was terminated by the `SIGKILL` signal sent by the `forceKillAfterDelay` option.117+ */118+ isForcefullyTerminated: boolean;119+120+ /**121 The numeric [exit code](https://en.wikipedia.org/wiki/Exit_status) of the subprocess that was run.122 123 This is `undefined` when the subprocess could not be spawned or was terminated by a signal.124 */74 unmodified lines