Improve process termination (#724)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 1fbf484 · Browse files · 7 files·+73 added−33 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+73 added−33 removed
- tests:+26 added−17 removed
- other:+47 added−16 removed
Provenance
- Commit
1c48d37- Tree
146a04a- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
1fbf484
7 files changed+73 added−33 removed
modified:lib/kill.js+1 added-1 removed
45 unmodified lines4647484950505152535424 unmodified lines45 unmodified lines
const killAfterTimeout = async ({spawned, timeout, killSignal, context, controller}) => { await setTimeout(timeout, undefined, {signal: controller.signal}); spawned.kill(killSignal); Object.assign(context, {timedOut: true, signal: killSignal}); context.timedOut = true; throw new Error('Timed out');};
// `timeout` option handling24 unmodified linesmodified:lib/stream.js+32 added-2 removed
103 unmodified lines104 }105 }106 };107 108+// Like `once()` except it never rejects, especially not on `error` event.109+const pEvent = (eventEmitter, eventName) => new Promise(resolve => {110+ eventEmitter.once(eventName, (...payload) => {111+ resolve([eventName, ...payload]);112+ });113+});114+115+const throwOnProcessError = async processErrorPromise => {116+ const [, error] = await processErrorPromise;117+ throw error;118+};119+120+// First the `spawn` event is emitted, then `exit`.121+// If the `error` event is emitted:122+// - before `spawn`: `exit` is never emitted.123+// - after `spawn`: `exit` is always emitted.124+// We only want to listen to `exit` if it will be emitted, i.e. if `spawn` has been emitted.125+// Therefore, the arguments order of `Promise.race()` is significant.126+const waitForFailedProcess = async (processSpawnPromise, processErrorPromise, processExitPromise) => {127+ const [eventName] = await Promise.race([processSpawnPromise, processErrorPromise]);128+ return eventName === 'spawn' ? processExitPromise : [];129+};130+131 // Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)132 export const getSpawnedResult = async ({133 spawned,134 options: {encoding, buffer, maxBuffer, timeout, killSignal, cleanup, detached},135 context,136 stdioStreamsGroups,137 controller,138 }) => {139+ const processSpawnPromise = pEvent(spawned, 'spawn');140+ const processErrorPromise = pEvent(spawned, 'error');141+ const processExitPromise = pEvent(spawned, 'exit');142+143 const removeExitHandler = cleanupOnExit(spawned, cleanup, detached);144 const customStreams = getCustomStreams(stdioStreamsGroups);145 146 const stdioPromises = spawned.stdio.map((stream, index) => getStdioPromise({stream, stdioStreams: stdioStreamsGroups[index], encoding, buffer, maxBuffer}));2 unmodified lines149 150 try {151 return await Promise.race([152 Promise.all([126- once(spawned, 'exit'),153+ undefined,154+ processExitPromise,155 Promise.all(stdioPromises),156 allPromise,157 ...customStreamsEndPromises,158 ]),159+ throwOnProcessError(processErrorPromise),160 ...throwOnCustomStreamsError(customStreams),161 ...throwIfStreamError(spawned.stdin),162 ...throwOnTimeout({spawned, timeout, killSignal, context, controller}),163 ]);164 } catch (error) {165 spawned.kill();166 const results = await Promise.all([138- [undefined, context.signal, error],167+ error,168+ waitForFailedProcess(processSpawnPromise, processErrorPromise, processExitPromise),169 Promise.all(stdioPromises.map(stdioPromise => getBufferedData(stdioPromise, encoding))),170 getBufferedData(allPromise, encoding),171 ]);172 cleanupStdioStreams(customStreams, error);7 unmodified linesmodified:test/error.js+11 added-4 removed
160 unmodified lines161 const subprocess = execa('forever.js');162 163 subprocess.kill();164 165- const {isTerminated} = await t.throwsAsync(subprocess, {message: /was killed with SIGTERM/});165+ const {isTerminated, signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGTERM/});166 t.true(isTerminated);167+ t.is(signal, 'SIGTERM');168 });169 170 test('error.isTerminated is true if process was killed indirectly', async t => {171 const subprocess = execa('forever.js');172 173 process.kill(subprocess.pid, 'SIGINT');174 175 // `process.kill()` is emulated by Node.js on Windows175- const message = isWindows ? /failed with exit code 1/ : /was killed with SIGINT/;176- const {isTerminated} = await t.throwsAsync(subprocess, {message});177- t.not(isTerminated, isWindows);176+ if (isWindows) {177+ const {isTerminated, signal} = await t.throwsAsync(subprocess, {message: /failed with exit code 1/});178+ t.is(isTerminated, false);179+ t.is(signal, undefined);180+ } else {181+ const {isTerminated, signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});182+ t.is(isTerminated, true);183+ t.is(signal, 'SIGINT');184+ }185 });186 187 test('result.isTerminated is false if not killed', async t => {188 const {isTerminated} = await execa('noop.js');106 unmodified linesmodified:test/kill.js+15 added-13 removed
1 import process from 'node:process';2+import {once} from 'node:events';3 import {setTimeout} from 'node:timers/promises';4 import test from 'ava';5 import {pEvent} from 'p-event';6 import isRunning from 'is-running';72 unmodified lines79 const abortController = new AbortController();80 const {subprocess} = await spawnNoKillable(1, {signal: abortController.signal});81 abortController.abort();82 const {isTerminated, signal, isCanceled} = await t.throwsAsync(subprocess);82- t.false(isTerminated);83- t.is(signal, undefined);83+ t.true(isTerminated);84+ t.is(signal, 'SIGKILL');85 t.true(isCanceled);86 });87 88 test.serial('`forceKillAfterDelay` works with the "timeout" option', async t => {89 const {subprocess} = await spawnNoKillable(1, {timeout: 2e3});90 const {isTerminated, signal, timedOut} = await t.throwsAsync(subprocess);91 t.true(isTerminated);91- t.is(signal, 'SIGTERM');92+ t.is(signal, 'SIGKILL');93 t.true(timedOut);94 });95 96 test('`forceKillAfterDelay` works with the "maxBuffer" option', async t => {97 const {subprocess} = await spawnNoKillable(1, {maxBuffer: 1});98 const {isTerminated, signal} = await t.throwsAsync(subprocess);98- t.false(isTerminated);99- t.is(signal, undefined);99+ t.true(isTerminated);100+ t.is(signal, 'SIGKILL');101 });102 103 test('`forceKillAfterDelay` works with "error" events on childProcess', async t => {104 const {subprocess} = await spawnNoKillable(1);105 subprocess.emit('error', new Error('test'));106 const {isTerminated, signal} = await t.throwsAsync(subprocess);106- t.false(isTerminated);107- t.is(signal, undefined);107+ t.true(isTerminated);108+ t.is(signal, 'SIGKILL');109 });110 111 test('`forceKillAfterDelay` works with "error" events on childProcess.stdout', async t => {112 const {subprocess} = await spawnNoKillable(1);113 subprocess.stdout.destroy(new Error('test'));114 const {isTerminated, signal} = await t.throwsAsync(subprocess);114- t.false(isTerminated);115- t.is(signal, undefined);115+ t.true(isTerminated);116+ t.is(signal, 'SIGKILL');117 });118 }119 120 test('execa() returns a promise with kill()', async t => {142 unmodified lines263 });264 t.false(isCanceled);265 });266 266-test('calling abort is not considered a signal termination', async t => {267+test('calling abort is considered a signal termination', async t => {268 const abortController = new AbortController();268- const subprocess = execa('noop.js', {signal: abortController.signal});269+ const subprocess = execa('forever.js', {signal: abortController.signal});270+ await once(subprocess, 'spawn');271 abortController.abort();272 const {isTerminated, signal} = await t.throwsAsync(subprocess);271- t.false(isTerminated);272- t.is(signal, undefined);273+ t.true(isTerminated);274+ t.is(signal, 'SIGTERM');275 });276 277 test('error.isCanceled is true when abort is used', async t => {278 const abortController = new AbortController();37 unmodified linesmodified:index.d.ts+6 added-6 removed
663 unmodified lines664 */665 timedOut: boolean;666 667 /**668- Whether the process was terminated using either:669- - `childProcess.kill()`.670- - A signal sent by another process. This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).668+ Whether the process was terminated by a signal (like `SIGTERM`) sent by either:669+ - The current process.670+ - Another process. This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).671 */672 isTerminated: boolean;673 674 /**675- The name of the signal (like `SIGFPE`) that terminated the process using either:676- - `childProcess.kill()`.677- - A signal sent by another process. This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).675+ The name of the signal (like `SIGTERM`) that terminated the process, sent by either:676+ - The current process.677+ - Another process. This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).678 679 If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`.680 */681 signal?: string;604 unmodified linesmodified:index.js+2 added-1 removed
159 unmodified lines160 const handlePromise = async ({spawned, options, stdioStreamsGroups, command, escapedCommand, controller}) => {161 const context = {timedOut: false};162 163 const [164- [exitCode, signal, error],164+ error,165+ [, exitCode, signal],166 stdioResults,167 allResult,168 ] = await getSpawnedResult({spawned, options, context, stdioStreamsGroups, controller});169 const stdio = stdioResults.map(stdioResult => handleOutput(options, stdioResult));175 unmodified linesmodified:readme.md+6 added-6 removed
436 unmodified lines437 #### isTerminated438 439 Type: `boolean`440 441-Whether the process was terminated using either:442-- `childProcess.kill()`.443-- A signal sent by another process. This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).441+Whether the process was terminated by a signal (like `SIGTERM`) sent by either:442+- The current process.443+- Another process. This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).444 445 #### signal446 447 Type: `string | undefined`448 449-The name of the signal (like `SIGFPE`) that terminated the process using either:450-- `childProcess.kill()`.451-- A signal sent by another process. This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).449+The name of the signal (like `SIGTERM`) that terminated the process, sent by either:450+- The current process.451+- Another process. This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).452 453 If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`.454 455 #### signalDescription485 unmodified lines