Skip to content
Myr

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

7 files+73 added−33 removed

modified:lib/kill.js+1 added-1 removed
modified:lib/stream.js+32 added-2 removed
103 unmodified lines
104 }105 }106};107108// Like `once()` except it never rejects, especially not on `error` event.109const pEvent = (eventEmitter, eventName) => new Promise(resolve => {110 eventEmitter.once(eventName, (...payload) => {111 resolve([eventName, ...payload]);112 });113});114115const throwOnProcessError = async processErrorPromise => {116 const [, error] = await processErrorPromise;117 throw error;118};119120// 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.126const waitForFailedProcess = async (processSpawnPromise, processErrorPromise, processExitPromise) => {127 const [eventName] = await Promise.race([processSpawnPromise, processErrorPromise]);128 return eventName === 'spawn' ? processExitPromise : [];129};130131// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)132export 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');142143 const removeExitHandler = cleanupOnExit(spawned, cleanup, detached);144 const customStreams = getCustomStreams(stdioStreamsGroups);145146 const stdioPromises = spawned.stdio.map((stream, index) => getStdioPromise({stream, stdioStreams: stdioStreamsGroups[index], encoding, buffer, maxBuffer}));
2 unmodified lines
149150 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 lines
modified:test/error.js+11 added-4 removed
160 unmodified lines
161 const subprocess = execa('forever.js');162163 subprocess.kill();164165 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});169170test('error.isTerminated is true if process was killed indirectly', async t => {171 const subprocess = execa('forever.js');172173 process.kill(subprocess.pid, 'SIGINT');174175 // `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});186187test('result.isTerminated is false if not killed', async t => {188 const {isTerminated} = await execa('noop.js');
106 unmodified lines
modified:test/kill.js+15 added-13 removed
1import process from 'node:process';2import {once} from 'node:events';3import {setTimeout} from 'node:timers/promises';4import test from 'ava';5import {pEvent} from 'p-event';6import isRunning from 'is-running';
72 unmodified lines
79 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 });8788 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 });9596 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 });102103 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 });110111 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}119120test('execa() returns a promise with kill()', async t => {
142 unmodified lines
263 });264 t.false(isCanceled);265});266266test('calling abort is not considered a signal termination', async t => {267test('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});276277test('error.isCanceled is true when abort is used', async t => {278 const abortController = new AbortController();
37 unmodified lines
modified:index.d.ts+6 added-6 removed
663 unmodified lines
664 */665 timedOut: boolean;666667 /**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;673674 /**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).678679 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 lines
modified:index.js+2 added-1 removed
159 unmodified lines
160const handlePromise = async ({spawned, options, stdioStreamsGroups, command, escapedCommand, controller}) => {161 const context = {timedOut: false};162163 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 lines
modified:readme.md+6 added-6 removed
436 unmodified lines
437#### isTerminated438439Type: `boolean`440441Whether 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).441Whether 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).444445#### signal446447Type: `string | undefined`448449The 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).449The 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).452453If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`.454455#### signalDescription
485 unmodified lines