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
Provenance
- Commit
9cbb817- Tree
da95194- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
7ddf0a0
9 files changed+138 added−8 removed
modified:lib/error.js+3 added-1 removed
85 unmodified lines8687888990909192939433 unmodified lines12812913013113213313413513613718 unmodified lines85 unmodified lines .map(messagePart => stripFinalNewline(serializeMessagePart(messagePart))) .filter(Boolean) .join('\n\n');
if (Object.prototype.toString.call(error) !== '[object Error]') { if (!isErrorInstance(error)) { error = new Error(message); } else if (previousErrors.has(error)) { const newError = new Error(message); copyErrorProperties(newError, error);33 unmodified lines
return error;};
export const isErrorInstance = value => Object.prototype.toString.call(value) === '[object Error]';
const copyErrorProperties = (newError, previousError) => { for (const propertyName of COPIED_ERROR_PROPERTIES) { const descriptor = Object.getOwnPropertyDescriptor(previousError, propertyName); if (descriptor !== undefined) {18 unmodified linesmodified:lib/kill.js+21 added-3 removed
1 import {addAbortListener} from 'node:events';2 import os from 'node:os';3 import {setTimeout} from 'node:timers/promises';4 import {onExit} from 'signal-exit';5-import {normalizeExitPayload, getErrorPrefix} from './error.js';5+import {normalizeExitPayload, getErrorPrefix, isErrorInstance} from './error.js';6 7 const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;8 9-// Monkey-patches `childProcess.kill()` to add `forceKillAfterDelay` behavior10-export const spawnedKill = (kill, {forceKillAfterDelay, killSignal}, controller, signal = killSignal) => {9+// Monkey-patches `childProcess.kill()` to add `forceKillAfterDelay` behavior and `.kill(error)`10+export 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 };16 17+const handleKillError = (signalOrError, spawned, killSignal) => {18+ if (typeof signalOrError === 'string' || typeof signalOrError === 'number') {19+ return signalOrError;20+ }21+22+ if (isErrorInstance(signalOrError)) {23+ spawned.emit(errorSignal, signalOrError);24+ return killSignal;25+ }26+27+ throw new TypeError(`The first argument must be an error instance or a signal name string/number: ${signalOrError}`);28+};29+30+// Like `error` signal but internal to Execa.31+// E.g. does not make process crash when no `error` listener is set.32+export const errorSignal = Symbol('error');33+34 const setKillTimeout = async ({kill, signal, forceKillAfterDelay, killSignal, killResult, controller}) => {35 if (!shouldForceKill(signal, forceKillAfterDelay, killSignal, killResult)) {36 return;37 }81 unmodified linesmodified:lib/stream.js+7 added-1 removed
1 unmodified line2 import {finished} from 'node:stream/promises';3 import {setImmediate} from 'node:timers/promises';4 import getStream, {getStreamAsArrayBuffer, getStreamAsArray, MaxBufferError} from 'get-stream';5 import mergeStreams from '@sindresorhus/merge-streams';6-import {waitForSuccessfulExit, throwOnTimeout} from './kill.js';6+import {waitForSuccessfulExit, throwOnTimeout, errorSignal} from './kill.js';7 import {isStandardStream} from './stdio/utils.js';8 import {generatorToDuplexStream} from './stdio/generator.js';9 10 // `all` interleaves `stdout` and `stderr`131 unmodified lines142 const [error] = await once(spawned, 'error', {signal});143 throw error;144 };145 146+const throwOnInternalError = async (spawned, {signal}) => {147+ const [error] = await once(spawned, errorSignal, {signal});148+ throw error;149+};150+151 // 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 lines205 ...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 linesmodified:test/kill.js+75 added
90 unmodified lines91 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'});97 98 test('`forceKillAfterDelay` works with the "signal" option', async t => {99 const abortController = new AbortController();100 const subprocess = spawnNoKillableSimple({signal: abortController.signal});329 unmodified lines430 t.is(thrownError, error);431 t.true(thrownError.isTerminated);432 t.is(thrownError.signal, 'SIGINT');433 });434+435+const 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+};442+443+test('Cannot call .kill(null)', testInvalidKillArgument, null);444+test('Cannot call .kill(0n)', testInvalidKillArgument, 0n);445+test('Cannot call .kill(true)', testInvalidKillArgument, true);446+test('Cannot call .kill(errorObject)', testInvalidKillArgument, {name: '', message: '', stack: ''});447+test('Cannot call .kill([error])', testInvalidKillArgument, [new Error('test')]);448+449+test('.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+});463+464+test('.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+});469+470+test('.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+});476+477+test('.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+});490+491+test('.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+});500+501+test('.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 lines460 test('childProcess.stdio[*] must be read right away', testBufferDestroyOnEnd, 3);461 462 const 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 linesmodified:index.d.ts+11 added
830 unmodified lines831 832 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;835+836+ /**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.838+839+ This returns `false` when the signal could not be sent, for example when the child process has already exited.840+841+ 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).842+843+ [More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)844+ */845+ kill(signalOrError: Parameters<ChildProcess['kill']>[0] | Error): ReturnType<ChildProcess['kill']>;846 };847 848 export type ExecaChildProcess<OptionsType extends Options = Options> = ChildProcess &849 ExecaChildPromise<OptionsType> &464 unmodified linesmodified:index.js+1 added-1 removed
154 unmodified lines155 const originalStreams = [...spawned.stdio];156 pipeOutputAsync(spawned, stdioStreamsGroups, controller);157 cleanupOnExit(spawned, options, controller);158 159- 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});162 163 const promise = handlePromise({spawned, options, stdioStreamsGroups, originalStreams, command, escapedCommand, controller});190 unmodified linesmodified:index.test-d.ts+6 added-1 removed
1280 unmodified lines1281 execaSync('unicorns', {windowsHide: false});1282 execa('unicorns', {verbose: false});1283 execaSync('unicorns', {verbose: false});1284 /* eslint-enable @typescript-eslint/no-floating-promises */1285-execa('unicorns').kill();1285+expectType<boolean>(execa('unicorns').kill());1286 execa('unicorns').kill('SIGKILL');1287 execa('unicorns').kill(undefined);1288+execa('unicorns').kill(new Error('test'));1289 expectError(execa('unicorns').kill('SIGKILL', {}));1290+expectError(execa('unicorns').kill(null));1291+expectError(execa('unicorns').kill(0n));1292+expectError(execa('unicorns').kill([new Error('test')]));1293+expectError(execa('unicorns').kill({message: 'test'}));1294 1295 expectError(execa(['unicorns', 'arg']));1296 expectType<ExecaChildProcess>(execa('unicorns'));1297 expectType<ExecaChildProcess>(execa(fileUrl));99 unmodified linesmodified:readme.md+13 added
323 unmodified lines324 [`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`.325 326 Returns `execaChildProcess`, which allows chaining `.pipe()` then `await`ing the [final result](#childprocessresult).327 328+#### kill(signalOrError?)329+330+`signalOrError`: `string | number | Error`\331+_Returns_: `boolean`332+333+Sends 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.334+335+This returns `false` when the signal could not be sent, for example when the child process has already exited.336+337+When 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).338+339+[More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)340+341 ### childProcessResult342 343 Type: `object`344 622 unmodified lines