Skip to content
Myr

Add `.kill(error)` (#811)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by ehmicky · committed by GitHub · parent 7ddf0a0 · Browse files · 9 files+138 added−8 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

9 files+138 added−8 removed

  • tests:+76 added−1 removed
  • other:+62 added−7 removed

9 files+138 added−8 removed

modified:lib/error.js+3 added-1 removed
modified:lib/kill.js+21 added-3 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';5import {normalizeExitPayload, getErrorPrefix, isErrorInstance} from './error.js';67const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;89// Monkey-patches `childProcess.kill()` to add `forceKillAfterDelay` behavior10export const spawnedKill = (kill, {forceKillAfterDelay, killSignal}, controller, signal = killSignal) => {9// Monkey-patches `childProcess.kill()` to add `forceKillAfterDelay` behavior and `.kill(error)`10export const spawnedKill = ({kill, spawned, options: {forceKillAfterDelay, killSignal}, controller}, signalOrError = killSignal) => {11 const signal = handleKillError(signalOrError, spawned, killSignal);12 const killResult = kill(signal);13 setKillTimeout({kill, signal, forceKillAfterDelay, killSignal, killResult, controller});14 return killResult;15};1617const handleKillError = (signalOrError, spawned, killSignal) => {18 if (typeof signalOrError === 'string' || typeof signalOrError === 'number') {19 return signalOrError;20 }2122 if (isErrorInstance(signalOrError)) {23 spawned.emit(errorSignal, signalOrError);24 return killSignal;25 }2627 throw new TypeError(`The first argument must be an error instance or a signal name string/number: ${signalOrError}`);28};2930// Like `error` signal but internal to Execa.31// E.g. does not make process crash when no `error` listener is set.32export const errorSignal = Symbol('error');3334const setKillTimeout = async ({kill, signal, forceKillAfterDelay, killSignal, killResult, controller}) => {35 if (!shouldForceKill(signal, forceKillAfterDelay, killSignal, killResult)) {36 return;37 }
81 unmodified lines
modified:lib/stream.js+7 added-1 removed
1 unmodified line
2import {finished} from 'node:stream/promises';3import {setImmediate} from 'node:timers/promises';4import getStream, {getStreamAsArrayBuffer, getStreamAsArray, MaxBufferError} from 'get-stream';5import mergeStreams from '@sindresorhus/merge-streams';6import {waitForSuccessfulExit, throwOnTimeout} from './kill.js';6import {waitForSuccessfulExit, throwOnTimeout, errorSignal} from './kill.js';7import {isStandardStream} from './stdio/utils.js';8import {generatorToDuplexStream} from './stdio/generator.js';910// `all` interleaves `stdout` and `stderr`
131 unmodified lines
142 const [error] = await once(spawned, 'error', {signal});143 throw error;144};145146const throwOnInternalError = async (spawned, {signal}) => {147 const [error] = await once(spawned, errorSignal, {signal});148 throw error;149};150151// If `error` is emitted before `spawn`, `exit` will never be emitted.152// However, `error` might be emitted after `spawn`, e.g. with the `signal` option.153// In that case, `exit` will still be emitted.154// Since the `exit` event contains the signal name, we want to make sure we are listening for it.
50 unmodified lines
205 ...originalPromises,206 ...customStreamsEndPromises,207 ]),208 throwOnProcessError(spawned, controller),209 throwOnInternalError(spawned, controller),210 ...throwOnTimeout(spawned, timeout, context, controller),211 ]);212 } catch (error) {213 return Promise.all([
9 unmodified lines
modified:test/kill.js+75 added
90 unmodified lines
91 test('`forceKillAfterDelay: undefined` should kill after a timeout', testForceKill, undefined);92 test('`forceKillAfterDelay` should kill after a timeout with SIGTERM', testForceKill, 50, 'SIGTERM');93 test('`forceKillAfterDelay` should kill after a timeout with the killSignal string', testForceKill, 50, 'SIGINT', {killSignal: 'SIGINT'});94 test('`forceKillAfterDelay` should kill after a timeout with the killSignal number', testForceKill, 50, constants.signals.SIGINT, {killSignal: constants.signals.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'});9798 test('`forceKillAfterDelay` works with the "signal" option', async t => {99 const abortController = new AbortController();100 const subprocess = spawnNoKillableSimple({signal: abortController.signal});
329 unmodified lines
430 t.is(thrownError, error);431 t.true(thrownError.isTerminated);432 t.is(thrownError.signal, 'SIGINT');433});434435const testInvalidKillArgument = async (t, killArgument) => {436 const subprocess = execa('empty.js');437 t.throws(() => {438 subprocess.kill(killArgument);439 }, {message: /error instance or a signal name/});440 await subprocess;441};442443test('Cannot call .kill(null)', testInvalidKillArgument, null);444test('Cannot call .kill(0n)', testInvalidKillArgument, 0n);445test('Cannot call .kill(true)', testInvalidKillArgument, true);446test('Cannot call .kill(errorObject)', testInvalidKillArgument, {name: '', message: '', stack: ''});447test('Cannot call .kill([error])', testInvalidKillArgument, [new Error('test')]);448449test('.kill(error) propagates error', async t => {450 const subprocess = execa('forever.js');451 const originalMessage = 'test';452 const error = new Error(originalMessage);453 t.true(subprocess.kill(error));454 t.is(await t.throwsAsync(subprocess), error);455 t.is(error.exitCode, undefined);456 t.is(error.signal, 'SIGTERM');457 t.true(error.isTerminated);458 t.is(error.originalMessage, originalMessage);459 t.true(error.message.includes(originalMessage));460 t.true(error.message.includes('was killed with SIGTERM'));461 t.true(error.stack.includes(import.meta.url));462});463464test('.kill(error) uses killSignal', async t => {465 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});466 subprocess.kill(new Error('test'));467 t.like(await t.throwsAsync(subprocess), {signal: 'SIGINT'});468});469470test('.kill(error) is a noop if process already exited', async t => {471 const subprocess = execa('empty.js');472 await subprocess;473 t.false(isRunning(subprocess.pid));474 t.false(subprocess.kill(new Error('test')));475});476477test('.kill(error) terminates but does not change the error if the process already errored but did not exit yet', async t => {478 const subprocess = execa('forever.js');479 const error = new Error('first');480 subprocess.stdout.destroy(error);481 await setImmediate();482 const secondError = new Error('second');483 t.true(subprocess.kill(secondError));484 t.is(await t.throwsAsync(subprocess), error);485 t.is(error.exitCode, undefined);486 t.is(error.signal, 'SIGTERM');487 t.true(error.isTerminated);488 t.false(error.message.includes(secondError.message));489});490491test('.kill(error) twice in a row', async t => {492 const subprocess = execa('forever.js');493 const error = new Error('first');494 subprocess.kill(error);495 const secondError = new Error('second');496 subprocess.kill(secondError);497 t.is(await t.throwsAsync(subprocess), error);498 t.false(error.message.includes(secondError.message));499});500501test('.kill(error) does not emit the "error" event', async t => {502 const subprocess = execa('forever.js');503 const error = new Error('test');504 subprocess.kill(error);505 t.is(await Promise.race([t.throwsAsync(subprocess), once(subprocess, 'error')]), error);506});
modified:test/stream.js+1 added-1 removed
459 unmodified lines
460test('childProcess.stdio[*] must be read right away', testBufferDestroyOnEnd, 3);461462const testProcessEventsCleanup = async (t, fixtureName) => {463 const childProcess = execa(fixtureName, {reject: false});464 t.deepEqual(childProcess.eventNames().sort(), ['error', 'exit', 'spawn']);464 t.deepEqual(childProcess.eventNames().map(String).sort(), ['Symbol(error)', 'error', 'exit', 'spawn']);465 await childProcess;466 t.deepEqual(childProcess.eventNames(), []);467};468
2 unmodified lines
modified:index.d.ts+11 added
830 unmodified lines
831832 Returns `execaChildProcess`, which allows chaining `.pipe()` then `await`ing the final result.833 */834 pipe<Target extends ExecaChildProcess>(target: Target, streamName?: 'stdout' | 'stderr' | 'all' | number): Target;835836 /**837 Sends a [signal](https://nodejs.org/api/os.html#signal-constants) to the child process. The default signal is the `killSignal` option. `killSignal` defaults to `SIGTERM`, which terminates the child process.838839 This returns `false` when the signal could not be sent, for example when the child process has already exited.840841 When an error is passed as argument, its message and stack trace are kept in the child process' error. The child process is then terminated with the default signal. This does not emit the [`error` event](https://nodejs.org/api/child_process.html#event-error).842843 [More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)844 */845 kill(signalOrError: Parameters<ChildProcess['kill']>[0] | Error): ReturnType<ChildProcess['kill']>;846};847848export type ExecaChildProcess<OptionsType extends Options = Options> = ChildProcess &849ExecaChildPromise<OptionsType> &
464 unmodified lines
modified:index.js+1 added-1 removed
154 unmodified lines
155 const originalStreams = [...spawned.stdio];156 pipeOutputAsync(spawned, stdioStreamsGroups, controller);157 cleanupOnExit(spawned, options, controller);158159 spawned.kill = spawnedKill.bind(undefined, spawned.kill.bind(spawned), options, controller);159 spawned.kill = spawnedKill.bind(undefined, {kill: spawned.kill.bind(spawned), spawned, options, controller});160 spawned.all = makeAllStream(spawned, options);161 spawned.pipe = pipeToProcess.bind(undefined, {spawned, stdioStreamsGroups, options});162163 const promise = handlePromise({spawned, options, stdioStreamsGroups, originalStreams, command, escapedCommand, controller});
190 unmodified lines
modified:index.test-d.ts+6 added-1 removed
1280 unmodified lines
1281execaSync('unicorns', {windowsHide: false});1282execa('unicorns', {verbose: false});1283execaSync('unicorns', {verbose: false});1284/* eslint-enable @typescript-eslint/no-floating-promises */1285execa('unicorns').kill();1285expectType<boolean>(execa('unicorns').kill());1286execa('unicorns').kill('SIGKILL');1287execa('unicorns').kill(undefined);1288execa('unicorns').kill(new Error('test'));1289expectError(execa('unicorns').kill('SIGKILL', {}));1290expectError(execa('unicorns').kill(null));1291expectError(execa('unicorns').kill(0n));1292expectError(execa('unicorns').kill([new Error('test')]));1293expectError(execa('unicorns').kill({message: 'test'}));12941295expectError(execa(['unicorns', 'arg']));1296expectType<ExecaChildProcess>(execa('unicorns'));1297expectType<ExecaChildProcess>(execa(fileUrl));
99 unmodified lines
modified:readme.md+13 added
323 unmodified lines
324[`childProcess.stdout`](#stdout) (and/or [`childProcess.stderr`](#stderr) depending on `streamName`) must not be `undefined`. When `streamName` is `"all"`, the [`all` option](#all-2) must be set to `true`.325326Returns `execaChildProcess`, which allows chaining `.pipe()` then `await`ing the [final result](#childprocessresult).327328#### kill(signalOrError?)329330`signalOrError`: `string | number | Error`\331_Returns_: `boolean`332333Sends a [signal](https://nodejs.org/api/os.html#signal-constants) to the child process. The default signal is the [`killSignal`](#killsignal) option. `killSignal` defaults to `SIGTERM`, which [terminates](#isterminated) the child process.334335This returns `false` when the signal could not be sent, for example when the child process has already exited.336337When an error is passed as argument, its message and stack trace are kept in the [child process' error](#childprocessresult). The child process is then terminated with the default signal. This does not emit the [`error` event](https://nodejs.org/api/child_process.html#event-error).338339[More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)340341### childProcessResult342343Type: `object`344
622 unmodified lines