Improve `cancelSignal` option (#1108)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 01a4b42 · Browse files · 9 files·+146 added−14 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+146 added−14 removed
- tests:+110 added−9 removed
- other:+36 added−5 removed
Provenance
- Commit
3b56977- Tree
e81808d- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
01a4b42
9 files changed+146 added−14 removed
modified:lib/arguments/options.js+2 added
2 unmodified lines3456789101113 unmodified lines25262728293031323359 unmodified lines2 unmodified linesimport crossSpawn from 'cross-spawn';import {npmRunPathEnv} from 'npm-run-path';import {normalizeForceKillAfterDelay} from '../terminate/kill.js';import {normalizeKillSignal} from '../terminate/signal.js';import {validateCancelSignal} from '../terminate/cancel.js';import {validateTimeout} from '../terminate/timeout.js';import {handleNodeOption} from '../methods/node.js';import {validateIpcInputOption} from '../ipc/ipc-input.js';import {validateEncoding, BINARY_ENCODINGS} from './encoding-option.js';13 unmodified lines const options = addDefaultOptions(fdOptions); validateTimeout(options); validateEncoding(options); validateIpcInputOption(options); validateCancelSignal(options); options.shell = normalizeFileUrl(options.shell); options.env = getEnv(options); options.killSignal = normalizeKillSignal(options.killSignal); options.forceKillAfterDelay = normalizeForceKillAfterDelay(options.forceKillAfterDelay);59 unmodified linesmodified:lib/methods/main-async.js+4 added-4 removed
69 unmodified lines70 };71 72 // Options normalization logic specific to async methods.73 // Prevent passing the `timeout` option directly to `child_process.spawn()`.74-const handleAsyncOptions = ({timeout, signal, cancelSignal, ...options}) => {74+const handleAsyncOptions = ({timeout, signal, ...options}) => {75 if (signal !== undefined) {76 throw new TypeError('The "signal" option has been renamed to "cancelSignal" instead.');77 }78 79- return {...options, timeoutDuration: timeout, signal: cancelSignal};79+ return {...options, timeoutDuration: timeout};80 };81 82 const spawnSubprocessAsync = ({file, commandArguments, options, startTime, verboseInfo, command, escapedCommand, fileDescriptors}) => {83 let subprocess;45 unmodified lines129 };130 131 // Asynchronous logic, as opposed to the previous logic which can be run synchronously, i.e. can be returned to user right away132 const handlePromise = async ({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, onInternalError, controller}) => {133- const context = {timedOut: false};133+ const context = {timedOut: false, isCanceled: false};134 135 const [136 errorInfo,137 [exitCode, signal],36 unmodified lines174 error: errorInfo.error,175 command,176 escapedCommand,177 timedOut: context.timedOut,178- isCanceled: options.signal?.aborted === true,178+ isCanceled: context.isCanceled,179 isMaxBuffer: errorInfo.error instanceof MaxBufferError,180 exitCode,181 signal,182 stdio,15 unmodified linesmodified:lib/resolve/exit-async.js+1 added-1 removed
123455678939 unmodified linesimport {once} from 'node:events';import {DiscardedError} from '../return/final-error.js';
// If `error` is emitted before `spawn`, `exit` will never be emitted.// However, `error` might be emitted after `spawn`, e.g. with the `cancelSignal` option.// However, `error` might be emitted after `spawn`.// In that case, `exit` will still be emitted.// Since the `exit` event contains the signal name, we want to make sure we are listening for it.// This function also takes into account the following unlikely cases:// - `exit` being emitted in the same microtask as `spawn`39 unmodified linesmodified:lib/resolve/wait-subprocess.js+3 added
1 import {once} from 'node:events';2 import {isStream as isNodeStream} from 'is-stream';3 import {throwOnTimeout} from '../terminate/timeout.js';4+import {throwOnCancel} from '../terminate/cancel.js';5 import {isStandardStream} from '../utils/standard-stream.js';6 import {TRANSFORM_TYPES} from '../stdio/type.js';7 import {getBufferedData} from '../io/contents.js';8 import {waitForIpcOutput, getBufferedIpcOutput} from '../ipc/buffer-messages.js';11 unmodified lines20 buffer,21 maxBuffer,22 lines,23 timeoutDuration: timeout,24+ cancelSignal,25 stripFinalNewline,26 ipc,27 ipcInput,28 },59 unmodified lines88 ]),89 onInternalError,90 throwOnSubprocessError(subprocess, controller),91 ...throwOnTimeout(subprocess, timeout, context, controller),92+ ...throwOnCancel(subprocess, cancelSignal, context, controller),93 ]);94 } catch (error) {95 return Promise.all([96 {error},32 unmodified linesadded:lib/terminate/cancel.js+26 added
1234567891011121314151617181920212223242526import {once} from 'node:events';
// Validate the `cancelSignal` optionexport const validateCancelSignal = ({cancelSignal}) => { if (cancelSignal !== undefined && Object.prototype.toString.call(cancelSignal) !== '[object AbortSignal]') { throw new Error(`The \`cancelSignal\` option must be an AbortSignal: ${String(cancelSignal)}`); }};
// Terminate the subprocess when aborting the `cancelSignal` optionexport const throwOnCancel = (subprocess, cancelSignal, context, controller) => cancelSignal === undefined ? [] : [terminateOnCancel(subprocess, cancelSignal, context, controller)];
const terminateOnCancel = async (subprocess, cancelSignal, context, {signal}) => { await onAbortedSignal(cancelSignal, signal); context.isCanceled = true; subprocess.kill(); throw cancelSignal.reason;};
const onAbortedSignal = async (cancelSignal, signal) => { if (!cancelSignal.aborted) { await once(cancelSignal, 'abort', {signal}); }};modified:test/helpers/early-error.js+1 added-1 removed
123345672 unmodified linesimport {execa, execaSync} from '../../index.js';
export const earlyErrorOptions = {cancelSignal: false};export const earlyErrorOptions = {detached: 'true'};export const getEarlyErrorSubprocess = options => execa('empty.js', {...earlyErrorOptions, ...options});export const earlyErrorOptionsSync = {maxBuffer: false};export const getEarlyErrorSubprocessSync = options => execaSync('empty.js', {...earlyErrorOptionsSync, ...options});
2 unmodified linesmodified:test/return/final-error.js+7 added-6 removed
97 unmodified lines98 99 test('error.cause is set if error.isCanceled', async t => {100 const controller = new AbortController();101 const subprocess = execa('forever.js', {cancelSignal: controller.signal});102- const error = new Error('test');103- controller.abort(error);104- const {isCanceled, isTerminated, cause} = await t.throwsAsync(subprocess);105- t.true(isCanceled);106- t.false(isTerminated);107- t.is(cause.cause, error);102+ const cause = new Error('test');103+ controller.abort(cause);104+ const error = await t.throwsAsync(subprocess);105+ t.true(error.isCanceled);106+ t.true(error.isTerminated);107+ t.is(error.signal, 'SIGTERM');108+ t.is(error.cause, cause);109 });110 111 test('error.cause is not set if error.isTerminated with .kill(error)', async t => {112 const subprocess = execa('forever.js');52 unmodified linesmodified:test/terminate/cancel.js+101 added-2 removed
1-import {once} from 'node:events';1+import {once, getEventListeners} from 'node:events';2 import test from 'ava';3 import {execa, execaSync} from '../../index.js';4 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5+import {foobarString} from '../helpers/input.js';6 7 setFixtureDirectory();8 9+const testValidCancelSignal = (t, cancelSignal) => {10+ t.throws(() => {11+ execa('empty.js', {cancelSignal});12+ }, {message: /must be an AbortSignal/});13+};14+15+test('cancelSignal option cannot be AbortController', testValidCancelSignal, new AbortController());16+test('cancelSignal option cannot be {}', testValidCancelSignal, {});17+test('cancelSignal option cannot be null', testValidCancelSignal, null);18+test('cancelSignal option cannot be a symbol', testValidCancelSignal, Symbol('test'));19+20 test('result.isCanceled is false when abort isn\'t called (success)', async t => {21 const {isCanceled} = await execa('noop.js');22 t.false(isCanceled);23 });35 unmodified lines59 const abortController = new AbortController();60 const subprocess = execa('forever.js', {cancelSignal: abortController.signal});61 await once(subprocess, 'spawn');62 abortController.abort();51- const {isTerminated, signal} = await t.throwsAsync(subprocess);63+ const {isCanceled, isTerminated, signal} = await t.throwsAsync(subprocess);64+ t.true(isCanceled);65 t.true(isTerminated);66 t.is(signal, 'SIGTERM');67 });68 69+test('cancelSignal can already be aborted', async t => {70+ const cancelSignal = AbortSignal.abort();71+ const {isCanceled, isTerminated, signal} = await t.throwsAsync(execa('forever.js', {cancelSignal}));72+ t.true(isCanceled);73+ t.true(isTerminated);74+ t.is(signal, 'SIGTERM');75+ t.deepEqual(getEventListeners(cancelSignal, 'abort'), []);76+});77+78+test('calling abort does not emit the "error" event', async t => {79+ const abortController = new AbortController();80+ const subprocess = execa('forever.js', {cancelSignal: abortController.signal});81+ let error;82+ subprocess.once('error', errorArgument => {83+ error = errorArgument;84+ });85+ abortController.abort();86+ const {isCanceled} = await t.throwsAsync(subprocess);87+ t.true(isCanceled);88+ t.is(error, undefined);89+});90+91+test('calling abort cleans up listeners on cancelSignal, called', async t => {92+ const abortController = new AbortController();93+ const subprocess = execa('forever.js', {cancelSignal: abortController.signal});94+ t.is(getEventListeners(abortController.signal, 'abort').length, 1);95+ abortController.abort();96+ const {isCanceled} = await t.throwsAsync(subprocess);97+ t.true(isCanceled);98+ t.is(getEventListeners(abortController.signal, 'abort').length, 0);99+});100+101+test('calling abort cleans up listeners on cancelSignal, not called', async t => {102+ const abortController = new AbortController();103+ const subprocess = execa('noop.js', {cancelSignal: abortController.signal});104+ t.is(getEventListeners(abortController.signal, 'abort').length, 1);105+ await subprocess;106+ t.is(getEventListeners(abortController.signal, 'abort').length, 0);107+});108+109+test('calling abort cleans up listeners on cancelSignal, already aborted', async t => {110+ const cancelSignal = AbortSignal.abort();111+ const subprocess = execa('noop.js', {cancelSignal});112+ t.is(getEventListeners(cancelSignal, 'abort').length, 0);113+ const {isCanceled} = await t.throwsAsync(subprocess);114+ t.true(isCanceled);115+ t.is(getEventListeners(cancelSignal, 'abort').length, 0);116+});117+118 test('calling abort throws an error with message "Command was canceled"', async t => {119 const abortController = new AbortController();120 const subprocess = execa('noop.js', {cancelSignal: abortController.signal});121 abortController.abort();122 await t.throwsAsync(subprocess, {message: /Command was canceled/});123 });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});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');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});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}`);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});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');160+});161+162 test('calling abort twice should show the same behaviour as calling it once', async t => {163 const abortController = new AbortController();164 const subprocess = execa('noop.js', {cancelSignal: abortController.signal});165 abortController.abort();26 unmodified linesmodified:test/terminate/kill-signal.js+1 added
132 unmodified lines133 const cause = new Error('test');134 subprocess.emit('error', cause);135 await setImmediate();136 abortController.abort();137+ subprocess.emit('error', cause);138 const error = await t.throwsAsync(subprocess);139 t.is(error.cause, cause);140 t.is(error.exitCode, undefined);141 t.is(error.signal, 'SIGTERM');14 unmodified lines