Add `gracefulCancel` option (#1109)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent a5a4d69 · Browse files · 57 files·+1163 added−95 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
57 files+1163 added−95 removed
- tests:+556 added−20 removed
- other:+607 added−75 removed
Provenance
- Commit
d8190e5- Tree
948dcc5- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
a5a4d69
57 files changed+1163 added−95 removed
modified:docs/api.md+37 added-4 removed
171 unmodified lines172 Keep the subprocess alive while `getEachMessage()` is waiting.173 174 [More info.](ipc.md#keeping-the-subprocess-alive)175 176+### getCancelSignal()177+178+_Returns_: [`Promise<AbortSignal>`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)179+180+Retrieves the [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) shared by the [`cancelSignal`](#optionscancelsignal) option.181+182+This can only be called inside a subprocess. This requires the [`gracefulCancel`](#optionsgracefulcancel) option to be `true`.183+184+[More info.](termination.md#graceful-termination)185+186 ## Return value187 188 _TypeScript:_ [`ResultPromise`](typescript.md)\189 _Type:_ `Promise<object> | Subprocess`470 unmodified lines660 Whether the subprocess was canceled using the [`cancelSignal`](#optionscancelsignal) option.661 662 [More info.](termination.md#canceling)663 664+### error.isGracefullyCanceled665+666+_Type:_ `boolean`667+668+Whether the subprocess was canceled using both the [`cancelSignal`](#optionscancelsignal) and the [`gracefulCancel`](#optionsgracefulcancel) options.669+670+[More info.](termination.md#graceful-termination)671+672 ### error.isMaxBuffer673 674 _Type:_ `boolean`675 284 unmodified lines960 Largest amount of data allowed on [`stdout`](#resultstdout), [`stderr`](#resultstderr) and [`stdio`](#resultstdio).961 962 By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](output.md#stdoutstderr-specific-options).963 964+When reached, [`error.isMaxBuffer`](#errorismaxbuffer) becomes `true`.965+966 [More info.](output.md#big-output)967 968 ### options.buffer969 8 unmodified lines978 979 ### options.ipc980 981 _Type:_ `boolean`\962-_Default:_ `true` if either the [`node`](#optionsnode) option or the [`ipcInput`](#optionsipcinput) is set, `false` otherwise982+_Default:_ `true` if the [`node`](#optionsnode), [`ipcInput`](#optionsipcinput) or [`gracefulCancel`](#optionsgracefulcancel) option is set, `false` otherwise983 984 Enables exchanging messages with the subprocess using [`subprocess.sendMessage(message)`](#subprocesssendmessagemessage-sendmessageoptions), [`subprocess.getOneMessage()`](#subprocessgetonemessagegetonemessageoptions) and [`subprocess.getEachMessage()`](#subprocessgeteachmessage).985 986 The subprocess must be a Node.js file.47 unmodified lines1034 _Default:_ `0`1035 1036 If `timeout` is greater than `0`, the subprocess will be [terminated](#optionskillsignal) if it runs for longer than that amount of milliseconds.1037 1018-On timeout, [`result.timedOut`](#errortimedout) becomes `true`.1038+On timeout, [`error.timedOut`](#errortimedout) becomes `true`.1039 1040 [More info.](termination.md#timeout)1041 1042 ### options.cancelSignal1043 1044 _Type:_ [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)1045 1026-You can abort the subprocess using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).1046+When the `cancelSignal` is [aborted](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort), terminate the subprocess using a `SIGTERM` signal.1047 1028-When `AbortController.abort()` is called, [`result.isCanceled`](#erroriscanceled) becomes `true`.1048+When aborted, [`error.isCanceled`](#erroriscanceled) becomes `true`.1049 1050 [More info.](termination.md#canceling)1051 1052+### options.gracefulCancel1053+1054+_Type:_ `boolean`\1055+_Default:_: `false`1056+1057+When the [`cancelSignal`](#optionscancelsignal) option is [aborted](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort), do not send any [`SIGTERM`](termination.md#canceling). Instead, abort the [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) returned by [`getCancelSignal()`](#getcancelsignal). The subprocess should use it to terminate gracefully.1058+1059+The subprocess must be a [Node.js file](#optionsnode).1060+1061+When aborted, [`error.isGracefullyCanceled`](#errorisgracefullycanceled) becomes `true`.1062+1063+[More info.](termination.md#graceful-termination)1064+1065 ### options.forceKillAfterDelay1066 1067 _Type:_ `number | false`\1068 _Default:_ `5000`134 unmodified linesmodified:docs/bash.md+33 added-1 removed
8 unmodified lines9 This page describes the differences between [Bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell)), Execa, and [zx](https://github.com/google/zx). Execa intends to be more:10 - [Simple](#simplicity): minimalistic API, no [globals](#global-variables), no [binary](#main-binary), no builtin CLI utilities.11 - [Cross-platform](#shell): [no shell](shell.md) is used, only JavaScript.12 - [Secure](#escaping): no shell injection.13-- [Featureful](#simplicity): all Execa features are available ([text lines iteration](#iterate-over-output-lines), [advanced piping](#piping-stdout-to-another-command), [simple IPC](#ipc), [passing any input type](#pass-any-input-type), [returning any output type](#return-any-output-type), [transforms](#transforms), [web streams](#web-streams), [convert to Duplex stream](#convert-to-duplex-stream), [cleanup on exit](termination.md#current-process-exit), [forceful termination](termination.md#forceful-termination), and [more](../readme.md#documentation)).13+- [Featureful](#simplicity): all Execa features are available ([text lines iteration](#iterate-over-output-lines), [advanced piping](#piping-stdout-to-another-command), [simple IPC](#ipc), [passing any input type](#pass-any-input-type), [returning any output type](#return-any-output-type), [transforms](#transforms), [web streams](#web-streams), [convert to Duplex stream](#convert-to-duplex-stream), [cleanup on exit](termination.md#current-process-exit), [graceful termination](#graceful-termination), [forceful termination](termination.md#forceful-termination), and [more](../readme.md#documentation)).14 - [Easy to debug](#debugging): [verbose mode](#verbose-mode-single-command), [detailed errors](#detailed-errors), [messages and stack traces](#cancelation), stateless API.15 - [Performant](#performance)16 17 ## Flexibility1023 unmodified lines1041 ```1042 1043 [More info.](termination.md#canceling)1044 1045+### Graceful termination1046+1047+```sh1048+# Bash1049+trap cleanup SIGTERM1050+```1051+1052+```js1053+// zx1054+// This does not work on Windows1055+process.on('SIGTERM', () => {1056+ // ...1057+});1058+```1059+1060+```js1061+// Execa - main.js1062+const controller = new AbortController();1063+await $({1064+ cancelSignal: controller.signal,1065+ gracefulCancel: true,1066+})`node build.js`;1067+```1068+1069+```js1070+// Execa - build.js1071+import {getCancelSignal} from 'execa';1072+1073+const cancelSignal = await getCancelSignal();1074+await fetch('https://example.com', {signal: cancelSignal});1075+```1076+1077 ### Interleaved output1078 1079 ```sh1080 # Bash prints stdout and stderr interleaved194 unmodified linesmodified:docs/errors.md+2 added-1 removed
50 unmodified lines51525354555656575859606149 unmodified lines50 unmodified lines
The subprocess can fail for other reasons. Some of them can be detected using a specific boolean property:- [`error.timedOut`](api.md#errortimedout): [`timeout`](termination.md#timeout) option.- [`error.isCanceled`](api.md#erroriscanceled): [`cancelSignal`](termination.md#canceling) option.- [`error.isGracefullyCanceled`](api.md#errorisgracefullycanceled): `cancelSignal` option, if the [`gracefulCancel`](termination.md#graceful-termination) option is `true`.- [`error.isMaxBuffer`](api.md#errorismaxbuffer): [`maxBuffer`](output.md#big-output) option.- [`error.isTerminated`](api.md#erroristerminated): [signal termination](termination.md#signal-termination). This includes the [`timeout`](termination.md#timeout) and [`cancelSignal`](termination.md#canceling) options since those terminate the subprocess with a [signal](termination.md#default-signal). However, this does not include the [`maxBuffer`](output.md#big-output) option.- [`error.isTerminated`](api.md#erroristerminated): [signal termination](termination.md#signal-termination). This includes the [`timeout`](termination.md#timeout) and [`forceKillAfterDelay`](termination.md#forceful-termination) options since those terminate the subprocess with a [signal](termination.md#default-signal). This also includes the [`cancelSignal`](termination.md#canceling) option unless the [`gracefulCancel`](termination.md#graceful-termination) option is `true`. This does not include the [`maxBuffer`](output.md#big-output) option.
Otherwise, the subprocess failed because either:- An exception was thrown in a [stream](streams.md) or [transform](transform.md).- The command's executable file was not found.49 unmodified linesmodified:docs/termination.md+97 added-10 removed
6 unmodified lines7 # 🏁 Termination8 9 ## Alternatives10 11-Terminating a subprocess ends it abruptly. This prevents rolling back the subprocess' operations and leaves them incomplete. When possible, graceful exits should be preferred, such as:12-- Letting the subprocess end on its own.13-- [Performing cleanup](#sigterm) in termination [signal handlers](https://nodejs.org/api/process.html#process_signal_events).14-- [Sending a message](ipc.md) to the subprocess so it aborts its operations and cleans up.11+Terminating a subprocess ends it abruptly. This prevents rolling back the subprocess' operations and leaves them incomplete.12 13+Ideally subprocesses should end on their own. If that's not possible, [graceful termination](#graceful-termination) should be preferred.14+15 ## Canceling16 18-The [`cancelSignal`](api.md#optionscancelsignal) option can be used to cancel a subprocess. When [`abortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) is [aborted](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort), a [`SIGTERM` signal](#default-signal) is sent to the subprocess.17+The [`cancelSignal`](api.md#optionscancelsignal) option can be used to cancel a subprocess. When it is [aborted](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort), a [`SIGTERM` signal](#default-signal) is sent to the subprocess.18 19 ```js21-import {execa} from 'execa';20+import {execaNode} from 'execa';21 23-const abortController = new AbortController();22+const controller = new AbortController();23+const cancelSignal = controller.signal;24 25 setTimeout(() => {26- abortController.abort();26+ controller.abort();27 }, 5000);28 29 try {30- await execa({cancelSignal: abortController.signal})`npm run build`;30+ await execaNode({cancelSignal})`build.js`;31 } catch (error) {32 if (error.isCanceled) {33- console.error('Aborted by cancelSignal.');33+ console.error('Canceled by cancelSignal.');34 }35 36 throw error;37 }38 ```39 40+## Graceful termination41+42+### Share a `cancelSignal`43+44+When the [`gracefulCancel`](api.md#optionsgracefulcancel) option is `true`, the [`cancelSignal`](api.md#optionscancelsignal) option does not send any [`SIGTERM`](#sigterm). Instead, the subprocess calls [`getCancelSignal()`](api.md#getcancelsignal) to retrieve and handle the [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal). This allows the subprocess to properly clean up and abort operations.45+46+This option only works with Node.js files.47+48+This is cross-platform. If you do not need to support Windows, [signal handlers](#handling-signals) can also be used.49+50+```js51+// main.js52+import {execaNode} from 'execa';53+54+const controller = new AbortController();55+const cancelSignal = controller.signal;56+57+setTimeout(() => {58+ controller.abort();59+}, 5000);60+61+try {62+ await execaNode({cancelSignal, gracefulCancel: true})`build.js`;63+} catch (error) {64+ if (error.isGracefullyCanceled) {65+ console.error('Cancelled gracefully.');66+ }67+68+ throw error;69+}70+```71+72+```js73+// build.js74+import {getCancelSignal} from 'execa';75+76+const cancelSignal = await getCancelSignal();77+```78+79+### Abort operations80+81+The [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) returned by [`getCancelSignal()`](api.md#getcancelsignal) can be passed to most long-running Node.js methods: [`setTimeout()`](https://nodejs.org/api/timers.html#timerspromisessettimeoutdelay-value-options), [`setInterval()`](https://nodejs.org/api/timers.html#timerspromisessetintervaldelay-value-options), [events](https://nodejs.org/api/events.html#eventsonemitter-eventname-options), [streams](https://nodejs.org/api/stream.html#new-streamreadableoptions), [REPL](https://nodejs.org/api/readline.html#rlquestionquery-options), HTTP/TCP [requests](https://nodejs.org/api/http.html#httprequesturl-options-callback) or [servers](https://nodejs.org/api/net.html#serverlistenoptions-callback), [reading](https://nodejs.org/api/fs.html#fspromisesreadfilepath-options) / [writing](https://nodejs.org/api/fs.html#fspromiseswritefilefile-data-options) / [watching](https://nodejs.org/api/fs.html#fspromiseswatchfilename-options) files, or spawning another subprocess.82+83+When aborted, those methods throw the `Error` instance which was passed to [`abortController.abort(error)`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort). Since those methods keep the subprocess alive, aborting them makes the subprocess end on its own.84+85+```js86+import {getCancelSignal} from 'execa';87+import {watch} from 'node:fs/promises';88+89+const cancelSignal = await getCancelSignal();90+91+try {92+ for await (const fileChange of watch('./src', {signal: cancelSignal})) {93+ onFileChange(fileChange);94+ }95+} catch (error) {96+ if (error.isGracefullyCanceled) {97+ console.log(error.cause === cancelSignal.reason); // true98+ }99+}100+```101+102+### Cleanup logic103+104+For other kinds of operations, the [`abort`](https://nodejs.org/api/globals.html#event-abort) event should be listened to. Although [`cancelSignal.addEventListener('abort')`](https://nodejs.org/api/events.html#eventtargetaddeventlistenertype-listener-options) can be used, [`events.addAbortListener(cancelSignal)`](https://nodejs.org/api/events.html#eventsaddabortlistenersignal-listener) is preferred since it works even if the `cancelSignal` is already aborted.105+106+### Graceful exit107+108+We recommend explicitly [stopping](#abort-operations) each pending operation when the subprocess is aborted. This allows it to end on its own.109+110+```js111+import {getCancelSignal} from 'execa';112+import {addAbortListener} from 'node:events';113+114+const cancelSignal = await getCancelSignal();115+addAbortListener(cancelSignal, async () => {116+ await cleanup();117+ process.exitCode = 1;118+});119+```120+121+However, if any operation is still ongoing, the subprocess will keep running. It can be forcefully ended using [`process.exit(exitCode)`](https://nodejs.org/api/process.html#processexitcode) instead of [`process.exitCode`](https://nodejs.org/api/process.html#processexitcode_1).122+123+If the subprocess is still alive after 5 seconds, it is forcefully terminated with [`SIGKILL`](#sigkill). This can be [configured or disabled](#forceful-termination) using the [`forceKillAfterDelay`](api.md#optionsforcekillafterdelay) option.124+125 ## Timeout126 127 If the subprocess lasts longer than the [`timeout`](api.md#optionstimeout) option, a [`SIGTERM` signal](#default-signal) is sent to it.128 82 unmodified lines211 ```212 213 Unfortunately this [usually does not work](https://github.com/ehmicky/cross-platform-node-guide/blob/main/docs/6_networking_ipc/signals.md#cross-platform-signals) on Windows. The only signal that is somewhat cross-platform is [`SIGINT`](#sigint): on Windows, its handler is triggered when the user types `CTRL-C` in the terminal. However `subprocess.kill('SIGINT')` is only handled on Unix.214 215+Execa provides the [`gracefulCancel`](#graceful-termination) option as a cross-platform alternative to signal handlers.216+217 ### Signal name and description218 219 When a subprocess was terminated by a signal, [`error.isTerminated`](api.md#erroristerminated) is `true`.220 91 unmodified linesmodified:lib/arguments/options.js+5 added-1 removed
3 unmodified lines4 import {npmRunPathEnv} from 'npm-run-path';5 import {normalizeForceKillAfterDelay} from '../terminate/kill.js';6 import {normalizeKillSignal} from '../terminate/signal.js';7 import {validateCancelSignal} from '../terminate/cancel.js';8+import {validateGracefulCancel} from '../terminate/graceful.js';9 import {validateTimeout} from '../terminate/timeout.js';10 import {handleNodeOption} from '../methods/node.js';11 import {validateIpcInputOption} from '../ipc/ipc-input.js';12 import {validateEncoding, BINARY_ENCODINGS} from './encoding-option.js';14 unmodified lines27 validateTimeout(options);28 validateEncoding(options);29 validateIpcInputOption(options);30 validateCancelSignal(options);31+ validateGracefulCancel(options);32 options.shell = normalizeFileUrl(options.shell);33 options.env = getEnv(options);34 options.killSignal = normalizeKillSignal(options.killSignal);35 options.forceKillAfterDelay = normalizeForceKillAfterDelay(options.forceKillAfterDelay);18 unmodified lines54 all = false,55 windowsHide = true,56 killSignal = 'SIGTERM',57 forceKillAfterDelay = true,58+ gracefulCancel = false,59 ipcInput,57- ipc = ipcInput !== undefined,60+ ipc = ipcInput !== undefined || gracefulCancel,61 serialization = 'advanced',62 ...options63 }) => ({64 ...options,7 unmodified lines72 all,73 windowsHide,74 killSignal,75 forceKillAfterDelay,76+ gracefulCancel,77 ipcInput,78 ipc,79 serialization,80 });16 unmodified linesadded:lib/ipc/graceful.js+72 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172import {scheduler} from 'node:timers/promises';import {sendOneMessage} from './send.js';import {getIpcEmitter} from './forward.js';import {validateConnection, getAbortDisconnectError, throwOnMissingParent} from './validation.js';
// Send an IPC message so the subprocess performs a graceful terminationexport const sendAbort = (subprocess, message) => { const methodName = 'cancelSignal'; validateConnection(methodName, false, subprocess.connected); return sendOneMessage({ anyProcess: subprocess, methodName, isSubprocess: false, wrappedMessage: {type: GRACEFUL_CANCEL_TYPE, message}, message, });};
// When the signal is being used, start listening for incoming messages.// Unbuffering messages takes one microtask to complete, so this must be async.export const getCancelSignal = async ({anyProcess, channel, isSubprocess, ipc}) => { await startIpc({ anyProcess, channel, isSubprocess, ipc, }); return cancelController.signal;};
const startIpc = async ({anyProcess, channel, isSubprocess, ipc}) => { if (cancelListening) { return; }
cancelListening = true;
if (!ipc) { throwOnMissingParent(); return; }
if (channel === null) { abortOnDisconnect(); return; }
getIpcEmitter(anyProcess, channel, isSubprocess); await scheduler.yield();};
let cancelListening = false;
// Reception of IPC message to perform a graceful terminationexport const handleAbort = wrappedMessage => { if (wrappedMessage?.type !== GRACEFUL_CANCEL_TYPE) { return false; }
cancelController.abort(wrappedMessage.message); return true;};
const GRACEFUL_CANCEL_TYPE = 'execa:ipc:cancel';
// When the current process disconnects early, the subprocess `cancelSignal` is aborted.// Otherwise, the signal would never be able to be aborted later on.export const abortOnDisconnect = () => { cancelController.abort(getAbortDisconnectError());};
const cancelController = new AbortController();modified:lib/ipc/incoming.js+4 added-1 removed
1 unmodified line2 import {scheduler} from 'node:timers/promises';3 import {waitForOutgoingMessages} from './outgoing.js';4 import {redoAddedReferences} from './reference.js';5 import {handleStrictRequest, handleStrictResponse} from './strict.js';6+import {handleAbort, abortOnDisconnect} from './graceful.js';7 8 // By default, Node.js buffers `message` events.9 // - Buffering happens when there is a `message` event is emitted but there is no handler.10 // - As soon as a `message` event handler is set, all buffered `message` events are emitted, emptying the buffer.12 unmodified lines23 // The default behavior does not allow users to realize they made that mistake.24 // To solve those problems, instead of buffering messages, we debounce them.25 // The `message` event so it is emitted at most once per macrotask.26 export const onMessage = async ({anyProcess, channel, isSubprocess, ipcEmitter}, wrappedMessage) => {26- if (handleStrictResponse(wrappedMessage)) {27+ if (handleStrictResponse(wrappedMessage) || handleAbort(wrappedMessage)) {28 return;29 }30 31 if (!INCOMING_MESSAGES.has(anyProcess)) {29 unmodified lines61 };62 63 // If the `message` event is currently debounced, the `disconnect` event must wait for it64 export const onDisconnect = async ({anyProcess, channel, isSubprocess, ipcEmitter, boundOnMessage}) => {65+ abortOnDisconnect();66+67 const incomingMessages = INCOMING_MESSAGES.get(anyProcess);68 while (incomingMessages?.length > 0) {69 // eslint-disable-next-line no-await-in-loop70 await once(ipcEmitter, 'message:done');9 unmodified linesmodified:lib/ipc/methods.js+16 added-1 removed
12345678910111212131415161718192021222324252627282930313217 unmodified linesimport process from 'node:process';import {sendMessage} from './send.js';import {getOneMessage} from './get-one.js';import {getEachMessage} from './get-each.js';import {getCancelSignal} from './graceful.js';
// Add promise-based IPC methods in current processexport const addIpcMethods = (subprocess, {ipc}) => { Object.assign(subprocess, getIpcMethods(subprocess, false, ipc));};
// Get promise-based IPC in the subprocessexport const getIpcExport = () => getIpcMethods(process, true, process.channel !== undefined);export const getIpcExport = () => { const anyProcess = process; const isSubprocess = true; const ipc = process.channel !== undefined;
return { ...getIpcMethods(anyProcess, isSubprocess, ipc), getCancelSignal: getCancelSignal.bind(undefined, { anyProcess, channel: anyProcess.channel, isSubprocess, ipc, }), };};
// Retrieve the `ipc` shared by both the current process and the subprocessconst getIpcMethods = (anyProcess, isSubprocess, ipc) => ({ sendMessage: sendMessage.bind(undefined, { anyProcess,17 unmodified linesmodified:lib/ipc/send.js+30 added-8 removed
11 unmodified lines12 // We do not `await subprocess` during `.sendMessage()` nor `.getOneMessage()` since those methods are transient.13 // Users would still need to `await subprocess` after the method is done.14 // Also, this would prevent `unhandledRejection` event from being emitted, making it silent.15 export const sendMessage = ({anyProcess, channel, isSubprocess, ipc}, message, {strict = false} = {}) => {16+ const methodName = 'sendMessage';17 validateIpcMethod({17- methodName: 'sendMessage',18+ methodName,19 isSubprocess,20 ipc,21 isConnected: anyProcess.connected,22 });23 24 return sendMessageAsync({25 anyProcess,26 channel,27+ methodName,28 isSubprocess,29 message,30 strict,31 });32 };33 32-const sendMessageAsync = async ({anyProcess, channel, isSubprocess, message, strict}) => {33- const sendMethod = getSendMethod(anyProcess);34+const sendMessageAsync = async ({anyProcess, channel, methodName, isSubprocess, message, strict}) => {35 const wrappedMessage = handleSendStrict({36 anyProcess,37 channel,38 isSubprocess,39 message,40 strict,41 });42 const outgoingMessagesState = startSendMessage(anyProcess, wrappedMessage, strict);43+ try {44+ await sendOneMessage({45+ anyProcess,46+ methodName,47+ isSubprocess,48+ wrappedMessage,49+ message,50+ });51+ } catch (error) {52+ disconnect(anyProcess);53+ throw error;54+ } finally {55+ endSendMessage(outgoingMessagesState);56+ }57+};58 59+// Used internally by `cancelSignal`60+export const sendOneMessage = async ({anyProcess, methodName, isSubprocess, wrappedMessage, message}) => {61+ const sendMethod = getSendMethod(anyProcess);62+63 try {64 await Promise.all([65 waitForStrictResponse(wrappedMessage, anyProcess, isSubprocess),66 sendMethod(wrappedMessage),67 ]);68 } catch (error) {49- disconnect(anyProcess);50- handleEpipeError(error, isSubprocess);51- handleSerializationError(error, isSubprocess, message);69+ handleEpipeError({error, methodName, isSubprocess});70+ handleSerializationError({71+ error,72+ methodName,73+ isSubprocess,74+ message,75+ });76 throw error;53- } finally {54- endSendMessage(outgoingMessagesState);77 }78 };79 80 // [sub]process.send() promisified, memoized11 unmodified linesmodified:lib/ipc/validation.js+29 added-16 removed
5 unmodified lines6 7 // Better error message when forgetting to set `ipc: true` and using the IPC methods8 const validateIpcOption = (methodName, isSubprocess, ipc) => {9 if (!ipc) {10- throw new Error(`${getNamespaceName(isSubprocess)}${methodName}() can only be used if the \`ipc\` option is \`true\`.`);10+ throw new Error(`${getMethodName(methodName, isSubprocess)} can only be used if the \`ipc\` option is \`true\`.`);11 }12 };13 14 // Better error message when one process does not send/receive messages once the other process has disconnected.15 // This also makes it clear that any buffered messages are lost once either process has disconnected.16+// Also when aborting `cancelSignal` after disconnecting the IPC.16-const validateConnection = (methodName, isSubprocess, isConnected) => {17+export const validateConnection = (methodName, isSubprocess, isConnected) => {18 if (!isConnected) {18- throw new Error(`${getNamespaceName(isSubprocess)}${methodName}() cannot be used: the ${getOtherProcessName(isSubprocess)} has already exited or disconnected.`);19+ throw new Error(`${getMethodName(methodName, isSubprocess)} cannot be used: the ${getOtherProcessName(isSubprocess)} has already exited or disconnected.`);20 }21 };22 23 // When `getOneMessage()` could not complete due to an early disconnection24 export const throwOnEarlyDisconnect = isSubprocess => {24- throw new Error(`${getNamespaceName(isSubprocess)}getOneMessage() could not complete: the ${getOtherProcessName(isSubprocess)} exited or disconnected.`);25+ throw new Error(`${getMethodName('getOneMessage', isSubprocess)} could not complete: the ${getOtherProcessName(isSubprocess)} exited or disconnected.`);26 };27 28 // When both processes use `sendMessage()` with `strict` at the same time29 export const throwOnStrictDeadlockError = isSubprocess => {29- throw new Error(`${getNamespaceName(isSubprocess)}sendMessage() failed: the ${getOtherProcessName(isSubprocess)} is sending a message too, instead of listening to incoming messages.30+ throw new Error(`${getMethodName('sendMessage', isSubprocess)} failed: the ${getOtherProcessName(isSubprocess)} is sending a message too, instead of listening to incoming messages.31 This can be fixed by both sending a message and listening to incoming messages at the same time:32 33 const [receivedMessage] = await Promise.all([33- ${getNamespaceName(isSubprocess)}getOneMessage(),34- ${getNamespaceName(isSubprocess)}sendMessage(message, {strict: true}),34+ ${getMethodName('getOneMessage', isSubprocess)},35+ ${getMethodName('sendMessage', isSubprocess, 'message, {strict: true}')},36 ]);`);37 };38 39 // When the other process used `strict` but the current process had I/O error calling `sendMessage()` for the response39-export const getStrictResponseError = (error, isSubprocess) => new Error(`${getNamespaceName(isSubprocess)}sendMessage() failed when sending an acknowledgment response to the ${getOtherProcessName(isSubprocess)}.`, {cause: error});40+export const getStrictResponseError = (error, isSubprocess) => new Error(`${getMethodName('sendMessage', isSubprocess)} failed when sending an acknowledgment response to the ${getOtherProcessName(isSubprocess)}.`, {cause: error});41 42 // When using `strict` but the other process was not listening for messages43 export const throwOnMissingStrict = isSubprocess => {43- throw new Error(`${getNamespaceName(isSubprocess)}sendMessage() failed: the ${getOtherProcessName(isSubprocess)} is not listening to incoming messages.`);44+ throw new Error(`${getMethodName('sendMessage', isSubprocess)} failed: the ${getOtherProcessName(isSubprocess)} is not listening to incoming messages.`);45 };46 47 // When using `strict` but the other process disconnected before receiving the message48 export const throwOnStrictDisconnect = isSubprocess => {48- throw new Error(`${getNamespaceName(isSubprocess)}sendMessage() failed: the ${getOtherProcessName(isSubprocess)} exited without listening to incoming messages.`);49+ throw new Error(`${getMethodName('sendMessage', isSubprocess)} failed: the ${getOtherProcessName(isSubprocess)} exited without listening to incoming messages.`);50 };51 51-const getNamespaceName = isSubprocess => isSubprocess ? '' : 'subprocess.';52+// When the current process disconnects while the subprocess is listening to `cancelSignal`53+export const getAbortDisconnectError = () => new Error(`\`cancelSignal\` aborted: the ${getOtherProcessName(true)} disconnected.`);54 53-const getOtherProcessName = isSubprocess => isSubprocess ? 'parent process' : 'subprocess';55+// When the subprocess uses `cancelSignal` but not the current process56+export const throwOnMissingParent = () => {57+ throw new Error('`getCancelSignal()` cannot be used without setting the `cancelSignal` subprocess option.');58+};59 60 // EPIPE can happen when sending a message to a subprocess that is closing but has not disconnected yet56-export const handleEpipeError = (error, isSubprocess) => {61+export const handleEpipeError = ({error, methodName, isSubprocess}) => {62 if (error.code === 'EPIPE') {58- throw new Error(`${getNamespaceName(isSubprocess)}sendMessage() cannot be used: the ${getOtherProcessName(isSubprocess)} is disconnecting.`, {cause: error});63+ throw new Error(`${getMethodName(methodName, isSubprocess)} cannot be used: the ${getOtherProcessName(isSubprocess)} is disconnecting.`, {cause: error});64 }65 };66 67 // Better error message when sending messages which cannot be serialized.68 // Works with both `serialization: 'advanced'` and `serialization: 'json'`.64-export const handleSerializationError = (error, isSubprocess, message) => {69+export const handleSerializationError = ({error, methodName, isSubprocess, message}) => {70 if (isSerializationError(error)) {66- throw new Error(`${getNamespaceName(isSubprocess)}sendMessage()'s argument type is invalid: the message cannot be serialized: ${String(message)}.`, {cause: error});71+ throw new Error(`${getMethodName(methodName, isSubprocess)}'s argument type is invalid: the message cannot be serialized: ${String(message)}.`, {cause: error});72 }73 };74 75 const isSerializationError = ({code, message}) => SERIALIZATION_ERROR_CODES.has(code)16 unmodified lines92 // Message has cycles inside toJSON(), with `serialization: 'json'`93 'call stack size exceeded',94 ];95 96+const getMethodName = (methodName, isSubprocess, parameters = '') => methodName === 'cancelSignal'97+ ? '`cancelSignal`\'s `controller.abort()`'98+ : `${getNamespaceName(isSubprocess)}${methodName}(${parameters})`;99+100+const getNamespaceName = isSubprocess => isSubprocess ? '' : 'subprocess.';101+102+const getOtherProcessName = isSubprocess => isSubprocess ? 'parent process' : 'subprocess';103+104 // When any error arises, we disconnect the IPC.105 // Otherwise, it is likely that one of the processes will stop sending/receiving messages.106 // This would leave the other process hanging.107 export const disconnect = anyProcess => {4 unmodified linesmodified:lib/methods/main-async.js+4 added-3 removed
100 unmodified lines101 const originalStreams = [...subprocess.stdio];102 pipeOutputAsync(subprocess, fileDescriptors, controller);103 cleanupOnExit(subprocess, options, controller);104 105- const context = {timedOut: false, isCanceled: false};105+ const context = {};106 const onInternalError = createDeferred();107 subprocess.kill = subprocessKill.bind(undefined, {108 kill: subprocess.kill.bind(subprocess),109 options,64 unmodified lines174 ? makeError({175 error: errorInfo.error,176 command,177 escapedCommand,178- timedOut: context.timedOut,179- isCanceled: context.isCanceled,178+ timedOut: context.terminationReason === 'timeout',179+ isCanceled: context.terminationReason === 'cancel' || context.terminationReason === 'gracefulCancel',180+ isGracefullyCanceled: context.terminationReason === 'gracefulCancel',181 isMaxBuffer: errorInfo.error instanceof MaxBufferError,182 isForcefullyTerminated: context.isForcefullyTerminated,183 exitCode,184 signal,16 unmodified linesmodified:lib/methods/main-sync.js+1 added
153 unmodified lines154 command,155 escapedCommand,156 timedOut,157 isCanceled: false,158+ isGracefullyCanceled: false,159 isMaxBuffer,160 isForcefullyTerminated: false,161 exitCode,162 signal,7 unmodified linesmodified:lib/resolve/wait-subprocess.js+19 added-1 removed
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 {throwOnGracefulCancel} from '../terminate/graceful.js';6 import {isStandardStream} from '../utils/standard-stream.js';7 import {TRANSFORM_TYPES} from '../stdio/type.js';8 import {getBufferedData} from '../io/contents.js';9 import {waitForIpcOutput, getBufferedIpcOutput} from '../ipc/buffer-messages.js';12 unmodified lines22 maxBuffer,23 lines,24 timeoutDuration: timeout,25 cancelSignal,26+ gracefulCancel,27+ forceKillAfterDelay,28 stripFinalNewline,29 ipc,30 ipcInput,31 },59 unmodified lines91 ]),92 onInternalError,93 throwOnSubprocessError(subprocess, controller),94 ...throwOnTimeout(subprocess, timeout, context, controller),92- ...throwOnCancel(subprocess, cancelSignal, context, controller),95+ ...throwOnCancel({96+ subprocess,97+ cancelSignal,98+ gracefulCancel,99+ context,100+ controller,101+ }),102+ ...throwOnGracefulCancel({103+ subprocess,104+ cancelSignal,105+ gracefulCancel,106+ forceKillAfterDelay,107+ context,108+ controller,109+ }),110 ]);111 } catch (error) {112+ context.terminationReason ??= 'other';113 return Promise.all([114 {error},115 exitPromise,116 Promise.all(stdioPromises.map(stdioPromise => getBufferedData(stdioPromise))),30 unmodified linesmodified:lib/return/message.js+13 added
17 unmodified lines18 exitCode,19 escapedCommand,20 timedOut,21 isCanceled,22+ isGracefullyCanceled,23 isMaxBuffer,24 isForcefullyTerminated,25 forceKillAfterDelay,26 killSignal,12 unmodified lines39 signal,40 signalDescription,41 exitCode,42 isCanceled,43+ isGracefullyCanceled,44 isForcefullyTerminated,45 forceKillAfterDelay,46 killSignal,47 });23 unmodified lines71 signal,72 signalDescription,73 exitCode,74 isCanceled,75+ isGracefullyCanceled,76 isForcefullyTerminated,77 forceKillAfterDelay,78 killSignal,79 }) => {2 unmodified lines82 if (timedOut) {83 return `Command timed out after ${timeout} milliseconds${forcefulSuffix}`;84 }85 86+ if (isGracefullyCanceled) {87+ if (signal === undefined) {88+ return `Command was gracefully canceled with exit code ${exitCode}`;89+ }90+91+ return isForcefullyTerminated92+ ? `Command was gracefully canceled${forcefulSuffix}`93+ : `Command was gracefully canceled with ${signal} (${signalDescription})`;94+ }95+96 if (isCanceled) {97 return `Command was canceled${forcefulSuffix}`;98 }99 58 unmodified linesmodified:lib/return/result.js+7 added
18 unmodified lines19 durationMs: getDurationMs(startTime),20 failed: false,21 timedOut: false,22 isCanceled: false,23+ isGracefullyCanceled: false,24 isTerminated: false,25 isMaxBuffer: false,26 isForcefullyTerminated: false,27 exitCode: 0,20 unmodified lines48 escapedCommand,49 startTime,50 timedOut: false,51 isCanceled: false,52+ isGracefullyCanceled: false,53 isMaxBuffer: false,54 isForcefullyTerminated: false,55 stdio: Array.from({length: fileDescriptors.length}),56 ipcOutput: [],8 unmodified lines65 escapedCommand,66 startTime,67 timedOut,68 isCanceled,69+ isGracefullyCanceled,70 isMaxBuffer,71 isForcefullyTerminated,72 exitCode: rawExitCode,73 signal: rawSignal,21 unmodified lines95 exitCode,96 escapedCommand,97 timedOut,98 isCanceled,99+ isGracefullyCanceled,100 isMaxBuffer,101 isForcefullyTerminated,102 forceKillAfterDelay,103 killSignal,8 unmodified lines112 escapedCommand,113 startTime,114 timedOut,115 isCanceled,116+ isGracefullyCanceled,117 isMaxBuffer,118 isForcefullyTerminated,119 exitCode,120 signal,14 unmodified lines135 escapedCommand,136 startTime,137 timedOut,138 isCanceled,139+ isGracefullyCanceled,140 isMaxBuffer,141 isForcefullyTerminated,142 exitCode,143 signal,13 unmodified lines157 durationMs: getDurationMs(startTime),158 failed: true,159 timedOut,160 isCanceled,161+ isGracefullyCanceled,162 isTerminated: signal !== undefined,163 isMaxBuffer,164 isForcefullyTerminated,165 exitCode,21 unmodified linesmodified:lib/terminate/cancel.js+4 added-10 removed
1-import {once} from 'node:events';1+import {onAbortedSignal} from '../utils/abort-signal.js';2 3 // Validate the `cancelSignal` option4 export const validateCancelSignal = ({cancelSignal}) => {5 if (cancelSignal !== undefined && Object.prototype.toString.call(cancelSignal) !== '[object AbortSignal]') {6 throw new Error(`The \`cancelSignal\` option must be an AbortSignal: ${String(cancelSignal)}`);7 }8 };9 10-// Terminate the subprocess when aborting the `cancelSignal` option11-export const throwOnCancel = (subprocess, cancelSignal, context, controller) => cancelSignal === undefined10+// Terminate the subprocess when aborting the `cancelSignal` option and `gracefulSignal` is `false`11+export const throwOnCancel = ({subprocess, cancelSignal, gracefulCancel, context, controller}) => cancelSignal === undefined || gracefulCancel12 ? []13 : [terminateOnCancel(subprocess, cancelSignal, context, controller)];14 15 const terminateOnCancel = async (subprocess, cancelSignal, context, {signal}) => {16 await onAbortedSignal(cancelSignal, signal);17- context.isCanceled = true;17+ context.terminationReason ??= 'cancel';18 subprocess.kill();19 throw cancelSignal.reason;20 };21-22-const onAbortedSignal = async (cancelSignal, signal) => {23- if (!cancelSignal.aborted) {24- await once(cancelSignal, 'abort', {signal});25- }26-};added:lib/terminate/graceful.js+71 added
1+import {onAbortedSignal} from '../utils/abort-signal.js';2+import {sendAbort} from '../ipc/graceful.js';3+import {killOnTimeout} from './kill.js';4+5+// Validate the `gracefulCancel` option6+export const validateGracefulCancel = ({gracefulCancel, cancelSignal, ipc, serialization}) => {7+ if (!gracefulCancel) {8+ return;9+ }10+11+ if (cancelSignal === undefined) {12+ throw new Error('The `cancelSignal` option must be defined when setting the `gracefulCancel` option.');13+ }14+15+ if (!ipc) {16+ throw new Error('The `ipc` option cannot be false when setting the `gracefulCancel` option.');17+ }18+19+ if (serialization === 'json') {20+ throw new Error('The `serialization` option cannot be \'json\' when setting the `gracefulCancel` option.');21+ }22+};23+24+// Send abort reason to the subprocess when aborting the `cancelSignal` option and `gracefulCancel` is `true`25+export const throwOnGracefulCancel = ({26+ subprocess,27+ cancelSignal,28+ gracefulCancel,29+ forceKillAfterDelay,30+ context,31+ controller,32+}) => gracefulCancel33+ ? [sendOnAbort({34+ subprocess,35+ cancelSignal,36+ forceKillAfterDelay,37+ context,38+ controller,39+ })]40+ : [];41+42+const sendOnAbort = async ({subprocess, cancelSignal, forceKillAfterDelay, context, controller: {signal}}) => {43+ await onAbortedSignal(cancelSignal, signal);44+ const reason = getReason(cancelSignal);45+ await sendAbort(subprocess, reason);46+ killOnTimeout({47+ kill: subprocess.kill,48+ forceKillAfterDelay,49+ context,50+ controllerSignal: signal,51+ });52+ context.terminationReason ??= 'gracefulCancel';53+ throw cancelSignal.reason;54+};55+56+// The default `reason` is a DOMException, which is not serializable with V857+// See https://github.com/nodejs/node/issues/5322558+const getReason = ({reason}) => {59+ if (!(reason instanceof DOMException)) {60+ return reason;61+ }62+63+ const error = new Error(reason.message);64+ Object.defineProperty(error, 'stack', {65+ value: reason.stack,66+ enumerable: false,67+ configurable: true,68+ writable: true,69+ });70+ return error;71+};modified:lib/terminate/kill.js-1 removed
89 unmodified lines90 context.isForcefullyTerminated ??= true;91 }92 } catch {}93 };94-modified:lib/terminate/timeout.js+1 added-1 removed
13 unmodified lines14 : [killAfterTimeout(subprocess, timeout, context, controller)];15 16 const killAfterTimeout = async (subprocess, timeout, context, {signal}) => {17 await setTimeout(timeout, undefined, {signal});18- context.timedOut = true;18+ context.terminationReason ??= 'timeout';19 subprocess.kill();20 throw new DiscardedError();21 };added:lib/utils/abort-signal.js+8 added
1+import {once} from 'node:events';2+3+// Combines `util.aborted()` and `events.addAbortListener()`: promise-based and cleaned up with a stop signal4+export const onAbortedSignal = async (mainSignal, stopSignal) => {5+ if (!mainSignal.aborted) {6+ await once(mainSignal, 'abort', {signal: stopSignal});7+ }8+};added:test/fixtures/graceful-disconnect.js+12 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {once} from 'node:events';4+import {getCancelSignal, sendMessage} from 'execa';5+import {onAbortedSignal} from '../helpers/graceful.js';6+7+const cancelSignal = await getCancelSignal();8+await onAbortedSignal(cancelSignal);9+await Promise.all([10+ once(process, 'disconnect'),11+ sendMessage(cancelSignal.reason),12+]);added:test/fixtures/graceful-echo.js+5 added
1+#!/usr/bin/env node2+import {getCancelSignal, sendMessage, getOneMessage} from 'execa';3+4+await getCancelSignal();5+await sendMessage(await getOneMessage());added:test/fixtures/graceful-listener.js+12 added
1+#!/usr/bin/env node2+import {getCancelSignal, sendMessage} from 'execa';3+4+const id = setTimeout(() => {}, 1e8);5+const cancelSignal = await getCancelSignal();6+// eslint-disable-next-line unicorn/prefer-add-event-listener7+cancelSignal.onabort = async () => {8+ await sendMessage(cancelSignal.reason);9+ clearTimeout(id);10+};11+12+await sendMessage('.');added:test/fixtures/graceful-none.js+4 added
1+#!/usr/bin/env node2+import {getCancelSignal} from 'execa';3+4+await getCancelSignal();added:test/fixtures/graceful-print.js+7 added
1+#!/usr/bin/env node2+import {getCancelSignal} from 'execa';3+import {onAbortedSignal} from '../helpers/graceful.js';4+5+const cancelSignal = await getCancelSignal();6+await onAbortedSignal(cancelSignal);7+console.log(cancelSignal.reason);added:test/fixtures/graceful-ref.js+6 added
1+#!/usr/bin/env node2+import {once} from 'node:events';3+import {getCancelSignal} from 'execa';4+5+const cancelSignal = await getCancelSignal();6+once(cancelSignal, 'abort');added:test/fixtures/graceful-send-echo.js+9 added
1+#!/usr/bin/env node2+import {getCancelSignal, getOneMessage, sendMessage} from 'execa';3+import {onAbortedSignal} from '../helpers/graceful.js';4+5+const message = await getOneMessage();6+const cancelSignal = await getCancelSignal();7+await sendMessage(message);8+await onAbortedSignal(cancelSignal);9+await sendMessage(cancelSignal.reason);added:test/fixtures/graceful-send-fast.js+5 added
1+#!/usr/bin/env node2+import {getCancelSignal, sendMessage} from 'execa';3+4+const cancelSignal = await getCancelSignal();5+await sendMessage(cancelSignal.aborted);added:test/fixtures/graceful-send-print.js+8 added
1+#!/usr/bin/env node2+import {getCancelSignal, sendMessage} from 'execa';3+import {onAbortedSignal} from '../helpers/graceful.js';4+5+const cancelSignal = await getCancelSignal();6+await sendMessage(cancelSignal.aborted);7+await onAbortedSignal(cancelSignal);8+console.log(cancelSignal.reason);added:test/fixtures/graceful-send-string.js+6 added
1+#!/usr/bin/env node2+import {getCancelSignal, sendMessage} from 'execa';3+import {foobarString} from '../helpers/input.js';4+5+await getCancelSignal();6+await sendMessage(foobarString);added:test/fixtures/graceful-send-twice.js+8 added
1+#!/usr/bin/env node2+import {getCancelSignal, sendMessage} from 'execa';3+import {onAbortedSignal} from '../helpers/graceful.js';4+5+const cancelSignal = await getCancelSignal();6+await sendMessage(cancelSignal.aborted);7+await onAbortedSignal(cancelSignal);8+await sendMessage(cancelSignal.reason);added:test/fixtures/graceful-send.js+7 added
1+#!/usr/bin/env node2+import {getCancelSignal, sendMessage} from 'execa';3+import {onAbortedSignal} from '../helpers/graceful.js';4+5+const cancelSignal = await getCancelSignal();6+await onAbortedSignal(cancelSignal);7+await sendMessage(cancelSignal.reason);added:test/fixtures/graceful-twice.js+8 added
1+#!/usr/bin/env node2+import {getCancelSignal, sendMessage} from 'execa';3+import {onAbortedSignal} from '../helpers/graceful.js';4+5+await getCancelSignal();6+const cancelSignal = await getCancelSignal();7+await onAbortedSignal(cancelSignal);8+await sendMessage(cancelSignal.reason);added:test/fixtures/graceful-wait.js+6 added
1+#!/usr/bin/env node2+import {getCancelSignal} from 'execa';3+import {onAbortedSignal} from '../helpers/graceful.js';4+5+const cancelSignal = await getCancelSignal();6+await onAbortedSignal(cancelSignal);added:test/fixtures/ipc-get.js+4 added
1+#!/usr/bin/env node2+import {getOneMessage} from '../../index.js';3+4+await getOneMessage();added:test/fixtures/wait-fail.js+6 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {setTimeout} from 'node:timers/promises';4+5+await setTimeout(1e3);6+process.exitCode = 2;added:test/helpers/graceful.js+8 added
1+import {setTimeout} from 'node:timers/promises';2+3+// Combines `util.aborted()` and `events.addAbortListener()`: promise-based and cleaned up with a stop signal4+export const onAbortedSignal = async signal => {5+ try {6+ await setTimeout(1e8, undefined, {signal});7+ } catch {}8+};added:test/ipc/graceful.js+216 added
1+import {getEventListeners} from 'node:events';2+import {setTimeout} from 'node:timers/promises';3+import test from 'ava';4+import {execa, execaSync} from '../../index.js';5+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6+import {foobarString} from '../helpers/input.js';7+8+setFixtureDirectory();9+10+test('Graceful cancelSignal can be already aborted', async t => {11+ const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(execa('graceful-send.js', {cancelSignal: AbortSignal.abort(foobarString), gracefulCancel: true, forceKillAfterDelay: false}));12+ t.true(isCanceled);13+ t.true(isGracefullyCanceled);14+ t.false(isTerminated);15+ t.is(exitCode, 0);16+ t.deepEqual(ipcOutput, [foobarString]);17+});18+19+test('Graceful cancelSignal can be aborted', async t => {20+ const controller = new AbortController();21+ const subprocess = execa('graceful-send-twice.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});22+ t.false(await subprocess.getOneMessage());23+ controller.abort(foobarString);24+ const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);25+ t.true(isCanceled);26+ t.true(isGracefullyCanceled);27+ t.false(isTerminated);28+ t.is(exitCode, 0);29+ t.deepEqual(ipcOutput, [false, foobarString]);30+});31+32+test('Graceful cancelSignal can be never aborted', async t => {33+ const controller = new AbortController();34+ const subprocess = execa('graceful-send-fast.js', {cancelSignal: controller.signal, gracefulCancel: true});35+ t.false(await subprocess.getOneMessage());36+ await subprocess;37+});38+39+test('Graceful cancelSignal can be already aborted but not used', async t => {40+ const subprocess = execa('ipc-send-get.js', {cancelSignal: AbortSignal.abort(foobarString), gracefulCancel: true, forceKillAfterDelay: false});41+ t.is(await subprocess.getOneMessage(), foobarString);42+ await setTimeout(1e3);43+ await subprocess.sendMessage('.');44+ const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);45+ t.true(isCanceled);46+ t.true(isGracefullyCanceled);47+ t.false(isTerminated);48+ t.is(exitCode, 0);49+ t.deepEqual(ipcOutput, [foobarString]);50+});51+52+test('Graceful cancelSignal can be aborted but not used', async t => {53+ const controller = new AbortController();54+ const subprocess = execa('ipc-send-get.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});55+ t.is(await subprocess.getOneMessage(), foobarString);56+ controller.abort(foobarString);57+ await setTimeout(1e3);58+ await subprocess.sendMessage(foobarString);59+ const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);60+ t.true(isCanceled);61+ t.true(isGracefullyCanceled);62+ t.false(isTerminated);63+ t.is(exitCode, 0);64+ t.deepEqual(ipcOutput, [foobarString]);65+});66+67+test('Graceful cancelSignal can be never aborted nor used', async t => {68+ const controller = new AbortController();69+ const subprocess = execa('empty.js', {cancelSignal: controller.signal, gracefulCancel: true});70+ t.is(getEventListeners(controller.signal, 'abort').length, 1);71+ await subprocess;72+ t.is(getEventListeners(controller.signal, 'abort').length, 0);73+});74+75+test('Graceful cancelSignal can be aborted twice', async t => {76+ const controller = new AbortController();77+ const subprocess = execa('graceful-send-twice.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});78+ t.false(await subprocess.getOneMessage());79+ controller.abort(foobarString);80+ controller.abort('.');81+ const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);82+ t.true(isCanceled);83+ t.true(isGracefullyCanceled);84+ t.false(isTerminated);85+ t.is(exitCode, 0);86+ t.deepEqual(ipcOutput, [false, foobarString]);87+});88+89+test('Graceful cancelSignal cannot be manually aborted after disconnection', async t => {90+ const controller = new AbortController();91+ const subprocess = execa('empty.js', {cancelSignal: controller.signal, gracefulCancel: true});92+ subprocess.disconnect();93+ controller.abort(foobarString);94+ const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput, originalMessage} = await t.throwsAsync(subprocess);95+ t.false(isCanceled);96+ t.false(isGracefullyCanceled);97+ t.false(isTerminated);98+ t.is(exitCode, 0);99+ t.deepEqual(ipcOutput, []);100+ t.is(originalMessage, '`cancelSignal`\'s `controller.abort()` cannot be used: the subprocess has already exited or disconnected.');101+});102+103+test('Graceful cancelSignal can disconnect after being manually aborted', async t => {104+ const controller = new AbortController();105+ const subprocess = execa('graceful-disconnect.js', {cancelSignal: controller.signal, gracefulCancel: true});106+ controller.abort(foobarString);107+ t.is(await subprocess.getOneMessage(), foobarString);108+ subprocess.disconnect();109+ const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);110+ t.true(isCanceled);111+ t.true(isGracefullyCanceled);112+ t.false(isTerminated);113+ t.is(exitCode, 0);114+ t.deepEqual(ipcOutput, [foobarString]);115+});116+117+test('Graceful cancelSignal is automatically aborted on disconnection', async t => {118+ const controller = new AbortController();119+ const subprocess = execa('graceful-send-print.js', {cancelSignal: controller.signal, gracefulCancel: true});120+ t.false(await subprocess.getOneMessage());121+ subprocess.disconnect();122+ const {isCanceled, isGracefullyCanceled, ipcOutput, stdout} = await subprocess;123+ t.false(isCanceled);124+ t.false(isGracefullyCanceled);125+ t.deepEqual(ipcOutput, [false]);126+ t.true(stdout.includes('Error: `cancelSignal` aborted: the parent process disconnected.'));127+});128+129+test('getCancelSignal() aborts if already disconnected', async t => {130+ const controller = new AbortController();131+ const subprocess = execa('graceful-print.js', {cancelSignal: controller.signal, gracefulCancel: true});132+ subprocess.disconnect();133+ const {isCanceled, isGracefullyCanceled, ipcOutput, stdout} = await subprocess;134+ t.false(isCanceled);135+ t.false(isGracefullyCanceled);136+ t.deepEqual(ipcOutput, []);137+ t.true(stdout.includes('Error: `cancelSignal` aborted: the parent process disconnected.'));138+});139+140+test('getCancelSignal() fails if no IPC', async t => {141+ const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput, stderr} = await t.throwsAsync(execa('graceful-none.js'));142+ t.false(isCanceled);143+ t.false(isGracefullyCanceled);144+ t.false(isTerminated);145+ t.is(exitCode, 1);146+ t.deepEqual(ipcOutput, []);147+ t.true(stderr.includes('Error: `getCancelSignal()` cannot be used without setting the `cancelSignal` subprocess option.'));148+});149+150+test.serial('getCancelSignal() hangs if cancelSignal without gracefulCancel', async t => {151+ const controller = new AbortController();152+ const {timedOut, isCanceled, isGracefullyCanceled, signal, ipcOutput} = await t.throwsAsync(execa('graceful-wait.js', {ipc: true, cancelSignal: controller.signal, timeout: 1e3}));153+ t.true(timedOut);154+ t.false(isCanceled);155+ t.false(isGracefullyCanceled);156+ t.is(signal, 'SIGTERM');157+ t.deepEqual(ipcOutput, []);158+});159+160+test('Subprocess cancelSignal does not keep subprocess alive', async t => {161+ const controller = new AbortController();162+ const {ipcOutput} = await execa('graceful-ref.js', {cancelSignal: controller.signal, gracefulCancel: true});163+ t.deepEqual(ipcOutput, []);164+});165+166+test('Subprocess can send a message right away', async t => {167+ const controller = new AbortController();168+ const {ipcOutput} = await execa('graceful-send-string.js', {cancelSignal: controller.signal, gracefulCancel: true});169+ t.deepEqual(ipcOutput, [foobarString]);170+});171+172+test('Subprocess can receive a message right away', async t => {173+ const controller = new AbortController();174+ const {ipcOutput} = await execa('graceful-echo.js', {cancelSignal: controller.signal, gracefulCancel: true, ipcInput: foobarString});175+ t.deepEqual(ipcOutput, [foobarString]);176+});177+178+test('getCancelSignal() can be called twice', async t => {179+ const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(execa('graceful-twice.js', {cancelSignal: AbortSignal.abort(foobarString), gracefulCancel: true, forceKillAfterDelay: false}));180+ t.true(isCanceled);181+ t.true(isGracefullyCanceled);182+ t.false(isTerminated);183+ t.is(exitCode, 0);184+ t.deepEqual(ipcOutput, [foobarString]);185+});186+187+test('Graceful cancelSignal can use cancelSignal.onabort', async t => {188+ const controller = new AbortController();189+ const subprocess = execa('graceful-listener.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});190+ t.is(await subprocess.getOneMessage(), '.');191+ controller.abort(foobarString);192+ const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);193+ t.true(isCanceled);194+ t.true(isGracefullyCanceled);195+ t.false(isTerminated);196+ t.is(exitCode, 0);197+ t.deepEqual(ipcOutput, ['.', foobarString]);198+});199+200+test('Graceful cancelSignal abort reason cannot be directly received', async t => {201+ const subprocess = execa('graceful-send-echo.js', {cancelSignal: AbortSignal.abort(foobarString), gracefulCancel: true, forceKillAfterDelay: false});202+ await setTimeout(0);203+ await subprocess.sendMessage('.');204+ const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);205+ t.true(isCanceled);206+ t.true(isGracefullyCanceled);207+ t.false(isTerminated);208+ t.is(exitCode, 0);209+ t.deepEqual(ipcOutput, ['.', foobarString]);210+});211+212+test('error.isGracefullyCanceled is always false with execaSync()', t => {213+ const {isCanceled, isGracefullyCanceled} = execaSync('empty.js');214+ t.false(isCanceled);215+ t.false(isGracefullyCanceled);216+});modified:test/return/result.js+2 added
16 unmodified lines17 'durationMs',18 'failed',19 'timedOut',20 'isCanceled',21+ 'isGracefullyCanceled',22 'isTerminated',23 'isMaxBuffer',24 'isForcefullyTerminated',25 'exitCode',22 unmodified lines48 'durationMs',49 'failed',50 'timedOut',51 'isCanceled',52+ 'isGracefullyCanceled',53 'isTerminated',54 'isMaxBuffer',55 'isForcefullyTerminated',56 'exitCode',91 unmodified linesmodified:test/terminate/cancel.js+35 added-17 removed
16 unmodified lines17 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');21+ const {isCanceled, isGracefullyCanceled} = await execa('noop.js');22 t.false(isCanceled);23+ t.false(isGracefullyCanceled);24 });25 26 test('result.isCanceled is false when abort isn\'t called (failure)', async t => {26- const {isCanceled} = await t.throwsAsync(execa('fail.js'));27+ const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(execa('fail.js'));28 t.false(isCanceled);29+ t.false(isGracefullyCanceled);30 });31 32 test('result.isCanceled is false when abort isn\'t called in sync mode (success)', t => {31- const {isCanceled} = execaSync('noop.js');33+ const {isCanceled, isGracefullyCanceled} = execaSync('noop.js');34 t.false(isCanceled);35+ t.false(isGracefullyCanceled);36 });37 38 test('result.isCanceled is false when abort isn\'t called in sync mode (failure)', t => {36- const {isCanceled} = t.throws(() => {39+ const {isCanceled, isGracefullyCanceled} = t.throws(() => {40 execaSync('fail.js');41 });42 t.false(isCanceled);43+ t.false(isGracefullyCanceled);44 });45 42-test('error.isCanceled is true when abort is used', async t => {46+const testCancelSuccess = async (t, options) => {47 const abortController = new AbortController();44- const subprocess = execa('noop.js', {cancelSignal: abortController.signal});48+ const subprocess = execa('noop.js', {cancelSignal: abortController.signal, ...options});49 abortController.abort();46- const {isCanceled} = await t.throwsAsync(subprocess);50+ const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(subprocess);51 t.true(isCanceled);52+ t.false(isGracefullyCanceled);48-});53+};54 55+test('error.isCanceled is true when abort is used', testCancelSuccess, {});56+test('gracefulCancel can be false with cancelSignal', testCancelSuccess, {gracefulCancel: false});57+test('ipc can be false with cancelSignal', testCancelSuccess, {ipc: false});58+test('serialization can be "json" with cancelSignal', testCancelSuccess, {ipc: true, serialization: 'json'});59+60 test('error.isCanceled is false when kill method is used', async t => {61 const abortController = new AbortController();62 const subprocess = execa('noop.js', {cancelSignal: abortController.signal});63 subprocess.kill();54- const {isCanceled} = await t.throwsAsync(subprocess);64+ const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(subprocess);65 t.false(isCanceled);66+ t.false(isGracefullyCanceled);67 });68 69 test('calling abort is considered a signal termination', async t => {70 const abortController = new AbortController();71 const subprocess = execa('forever.js', {cancelSignal: abortController.signal});72 await once(subprocess, 'spawn');73 abortController.abort();63- const {isCanceled, isTerminated, signal} = await t.throwsAsync(subprocess);74+ const {isCanceled, isGracefullyCanceled, isTerminated, signal} = await t.throwsAsync(subprocess);75 t.true(isCanceled);76+ t.false(isGracefullyCanceled);77 t.true(isTerminated);78 t.is(signal, 'SIGTERM');79 });80 81 test('cancelSignal can already be aborted', async t => {82 const cancelSignal = AbortSignal.abort();71- const {isCanceled, isTerminated, signal} = await t.throwsAsync(execa('forever.js', {cancelSignal}));83+ const {isCanceled, isGracefullyCanceled, isTerminated, signal} = await t.throwsAsync(execa('forever.js', {cancelSignal}));84 t.true(isCanceled);85+ t.false(isGracefullyCanceled);86 t.true(isTerminated);87 t.is(signal, 'SIGTERM');88 t.deepEqual(getEventListeners(cancelSignal, 'abort'), []);89 });5 unmodified lines95 subprocess.once('error', errorArgument => {96 error = errorArgument;97 });98 abortController.abort();86- const {isCanceled} = await t.throwsAsync(subprocess);99+ const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(subprocess);100 t.true(isCanceled);101+ t.false(isGracefullyCanceled);102 t.is(error, undefined);103 });104 105 test('calling abort cleans up listeners on cancelSignal, called', async t => {106 const abortController = new AbortController();107 const subprocess = execa('forever.js', {cancelSignal: abortController.signal});108 t.is(getEventListeners(abortController.signal, 'abort').length, 1);109 abortController.abort();96- const {isCanceled} = await t.throwsAsync(subprocess);110+ const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(subprocess);111 t.true(isCanceled);112+ t.false(isGracefullyCanceled);113 t.is(getEventListeners(abortController.signal, 'abort').length, 0);114 });115 116 test('calling abort cleans up listeners on cancelSignal, not called', async t => {7 unmodified lines124 test('calling abort cleans up listeners on cancelSignal, already aborted', async t => {125 const cancelSignal = AbortSignal.abort();126 const subprocess = execa('noop.js', {cancelSignal});127 t.is(getEventListeners(cancelSignal, 'abort').length, 0);113- const {isCanceled} = await t.throwsAsync(subprocess);128+ const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(subprocess);129 t.true(isCanceled);130+ t.false(isGracefullyCanceled);131 t.is(getEventListeners(cancelSignal, 'abort').length, 0);132 });133 134 test('calling abort throws an error with message "Command was canceled"', async t => {44 unmodified lines179 const abortController = new AbortController();180 const subprocess = execa('noop.js', {cancelSignal: abortController.signal});181 abortController.abort();182 abortController.abort();167- const {isCanceled} = await t.throwsAsync(subprocess);183+ const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(subprocess);184 t.true(isCanceled);185+ t.false(isGracefullyCanceled);186 });187 188 test('calling abort on a successfully completed subprocess does not make result.isCanceled true', async t => {189 const abortController = new AbortController();190 const subprocess = execa('noop.js', {cancelSignal: abortController.signal});174- const result = await subprocess;191+ const {isCanceled, isGracefullyCanceled} = await subprocess;192 abortController.abort();176- t.false(result.isCanceled);193+ t.false(isCanceled);194+ t.false(isGracefullyCanceled);195 });196 197 test('Throws when using the former "signal" option name', t => {198 const abortController = new AbortController();11 unmodified linesadded:test/terminate/graceful.js+178 added
1+import {setTimeout} from 'node:timers/promises';2+import test from 'ava';3+import {execa} from '../../index.js';4+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5+import {foobarString} from '../helpers/input.js';6+import {mockSendIoError} from '../helpers/ipc.js';7+8+setFixtureDirectory();9+10+test('cancelSignal cannot be undefined with gracefulCancel', t => {11+ t.throws(() => {12+ execa('empty.js', {gracefulCancel: true});13+ }, {message: /The `cancelSignal` option must be defined/});14+});15+16+test('ipc cannot be false with gracefulCancel', t => {17+ t.throws(() => {18+ execa('empty.js', {gracefulCancel: true, cancelSignal: AbortSignal.abort(), ipc: false});19+ }, {message: /The `ipc` option cannot be false/});20+});21+22+test('serialization cannot be "json" with gracefulCancel', t => {23+ t.throws(() => {24+ execa('empty.js', {gracefulCancel: true, cancelSignal: AbortSignal.abort(), serialization: 'json'});25+ }, {message: /The `serialization` option cannot be 'json'/});26+});27+28+test('Current process can send a message right away', async t => {29+ const controller = new AbortController();30+ const subprocess = execa('ipc-echo.js', {cancelSignal: controller.signal, gracefulCancel: true});31+ await subprocess.sendMessage(foobarString);32+ const {ipcOutput} = await subprocess;33+ t.deepEqual(ipcOutput, [foobarString]);34+});35+36+test('Current process can receive a message right away', async t => {37+ const controller = new AbortController();38+ const subprocess = execa('ipc-send.js', {cancelSignal: controller.signal, gracefulCancel: true});39+ t.is(await subprocess.getOneMessage(), foobarString);40+ const {ipcOutput} = await subprocess;41+ t.deepEqual(ipcOutput, [foobarString]);42+});43+44+test('Does not disconnect during I/O errors when sending the abort reason', async t => {45+ const controller = new AbortController();46+ const subprocess = execa('ipc-echo.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});47+ const error = mockSendIoError(subprocess);48+ controller.abort(foobarString);49+ await setTimeout(0);50+ t.true(subprocess.connected);51+ subprocess.kill();52+ const {isCanceled, isGracefullyCanceled, signal, ipcOutput, cause} = await t.throwsAsync(subprocess);53+ t.false(isCanceled);54+ t.false(isGracefullyCanceled);55+ t.is(signal, 'SIGTERM');56+ t.deepEqual(ipcOutput, []);57+ t.is(cause, error);58+});59+60+class AbortError extends Error {61+ name = 'AbortError';62+}63+64+test('Abort reason is sent to the subprocess', async t => {65+ const controller = new AbortController();66+ const subprocess = execa('graceful-send.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});67+ const error = new AbortError(foobarString);68+ controller.abort(error);69+ const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, cause, ipcOutput} = await t.throwsAsync(subprocess);70+ t.true(isCanceled);71+ t.true(isGracefullyCanceled);72+ t.false(isTerminated);73+ t.is(exitCode, 0);74+ t.is(cause, error);75+ t.is(ipcOutput[0].message, error.message);76+ t.is(ipcOutput[0].stack, error.stack);77+ t.is(ipcOutput[0].name, 'Error');78+});79+80+test('Abort default reason is sent to the subprocess', async t => {81+ const controller = new AbortController();82+ const subprocess = execa('graceful-send.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});83+ controller.abort();84+ const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, cause, ipcOutput} = await t.throwsAsync(subprocess);85+ t.true(isCanceled);86+ t.true(isGracefullyCanceled);87+ t.false(isTerminated);88+ t.is(exitCode, 0);89+ const {reason} = controller.signal;90+ t.is(cause.stack, reason.stack);91+ t.is(ipcOutput[0].message, reason.message);92+ t.is(ipcOutput[0].stack, reason.stack);93+});94+95+test('Fail when sending non-serializable abort reason', async t => {96+ const controller = new AbortController();97+ const subprocess = execa('ipc-echo.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});98+ controller.abort(() => {});99+ await setTimeout(0);100+ t.true(subprocess.connected);101+ await subprocess.sendMessage(foobarString);102+ const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, cause, ipcOutput} = await t.throwsAsync(subprocess);103+ t.false(isCanceled);104+ t.false(isGracefullyCanceled);105+ t.false(isTerminated);106+ t.is(exitCode, 0);107+ t.deepEqual(ipcOutput, [foobarString]);108+ t.is(cause.message, '`cancelSignal`\'s `controller.abort()`\'s argument type is invalid: the message cannot be serialized: () => {}.');109+ t.is(cause.cause.message, '() => {} could not be cloned.');110+});111+112+test('timeout does not use graceful cancelSignal', async t => {113+ const controller = new AbortController();114+ const {timedOut, isCanceled, isGracefullyCanceled, isTerminated, signal, exitCode, shortMessage, ipcOutput} = await t.throwsAsync(execa('graceful-send.js', {cancelSignal: controller.signal, gracefulCancel: true, timeout: 1}));115+ t.true(timedOut);116+ t.false(isCanceled);117+ t.false(isGracefullyCanceled);118+ t.true(isTerminated);119+ t.is(signal, 'SIGTERM');120+ t.is(exitCode, undefined);121+ t.is(shortMessage, 'Command timed out after 1 milliseconds: graceful-send.js');122+ t.deepEqual(ipcOutput, []);123+});124+125+test('error on graceful cancelSignal on non-0 exit code', async t => {126+ const {isCanceled, isGracefullyCanceled, isTerminated, isForcefullyTerminated, exitCode, shortMessage} = await t.throwsAsync(execa('wait-fail.js', {cancelSignal: AbortSignal.abort(''), gracefulCancel: true, forceKillAfterDelay: false}));127+ t.true(isCanceled);128+ t.true(isGracefullyCanceled);129+ t.false(isTerminated);130+ t.false(isForcefullyTerminated);131+ t.is(exitCode, 2);132+ t.is(shortMessage, 'Command was gracefully canceled with exit code 2: wait-fail.js');133+});134+135+test('error on graceful cancelSignal on forceful termination', async t => {136+ const {isCanceled, isGracefullyCanceled, isTerminated, signal, isForcefullyTerminated, exitCode, shortMessage} = await t.throwsAsync(execa('forever.js', {cancelSignal: AbortSignal.abort(''), gracefulCancel: true, forceKillAfterDelay: 1}));137+ t.true(isCanceled);138+ t.true(isGracefullyCanceled);139+ t.true(isTerminated);140+ t.is(signal, 'SIGKILL');141+ t.true(isForcefullyTerminated);142+ t.is(exitCode, undefined);143+ t.is(shortMessage, 'Command was gracefully canceled and was forcefully terminated after 1 milliseconds: forever.js');144+});145+146+test('error on graceful cancelSignal on non-forceful termination', async t => {147+ const subprocess = execa('ipc-send-get.js', {cancelSignal: AbortSignal.abort(''), gracefulCancel: true, forceKillAfterDelay: 1e6});148+ t.is(await subprocess.getOneMessage(), foobarString);149+ subprocess.kill();150+ const {isCanceled, isGracefullyCanceled, isTerminated, signal, isForcefullyTerminated, exitCode, shortMessage} = await t.throwsAsync(subprocess);151+ t.true(isCanceled);152+ t.true(isGracefullyCanceled);153+ t.true(isTerminated);154+ t.is(signal, 'SIGTERM');155+ t.false(isForcefullyTerminated);156+ t.is(exitCode, undefined);157+ t.is(shortMessage, 'Command was gracefully canceled with SIGTERM (Termination): ipc-send-get.js');158+});159+160+test('`forceKillAfterDelay: false` with the "cancelSignal" option when graceful', async t => {161+ const subprocess = execa('forever.js', {cancelSignal: AbortSignal.abort(''), gracefulCancel: true, forceKillAfterDelay: false});162+ await setTimeout(6e3);163+ subprocess.kill('SIGKILL');164+ const {isCanceled, isGracefullyCanceled, isTerminated, signal, isForcefullyTerminated, exitCode, shortMessage} = await t.throwsAsync(subprocess);165+ t.true(isCanceled);166+ t.true(isGracefullyCanceled);167+ t.true(isTerminated);168+ t.is(signal, 'SIGKILL');169+ t.false(isForcefullyTerminated);170+ t.is(exitCode, undefined);171+ t.is(shortMessage, 'Command was gracefully canceled with SIGKILL (Forced termination): forever.js');172+});173+174+test('subprocess.getCancelSignal() is not defined', async t => {175+ const subprocess = execa('empty.js', {cancelSignal: AbortSignal.abort(''), gracefulCancel: true});176+ t.is(subprocess.getCancelSignal, undefined);177+ await t.throwsAsync(subprocess);178+});modified:test/terminate/kill-force.js+2 added-1 removed
111 unmodified lines112 const abortController = new AbortController();113 const subprocess = spawnNoKillableSimple({cancelSignal: abortController.signal});114 await once(subprocess, 'spawn');115 abortController.abort('');116- const {isTerminated, signal, isCanceled, isForcefullyTerminated, shortMessage} = await t.throwsAsync(subprocess);116+ const {isTerminated, signal, isCanceled, isGracefullyCanceled, isForcefullyTerminated, shortMessage} = await t.throwsAsync(subprocess);117 t.true(isTerminated);118 t.is(signal, 'SIGKILL');119 t.true(isCanceled);120+ t.false(isGracefullyCanceled);121 t.true(isForcefullyTerminated);122 t.is(shortMessage, 'Command was canceled and was forcefully terminated after 1 milliseconds: forever.js');123 });124 94 unmodified linesmodified:test/terminate/timeout.js+2 added-2 removed
64 unmodified lines65 const {timedOut} = execaSync('noop.js');66 t.false(timedOut);67 });68 69-test('timedOut is true if the timeout happened after a different error occurred', async t => {69+test('timedOut is false if the timeout happened after a different error occurred', async t => {70 const subprocess = execa('forever.js', {timeout: 1e3});71 const cause = new Error('test');72 subprocess.emit('error', cause);73 const error = await t.throwsAsync(subprocess);74 t.is(error.cause, cause);75- t.true(error.timedOut);75+ t.false(error.timedOut);76 });modified:test-d/arguments/options.test-d.ts+7 added-2 removed
213 unmodified lines214 expectError(execaSync('unicorns', {detached: true}));215 expectError(await execa('unicorns', {detached: 'true'}));216 expectError(execaSync('unicorns', {detached: 'true'}));217 218-await execa('unicorns', {cancelSignal: new AbortController().signal});219-expectError(execaSync('unicorns', {cancelSignal: new AbortController().signal}));218+await execa('unicorns', {cancelSignal: AbortSignal.abort()});219+expectError(execaSync('unicorns', {cancelSignal: AbortSignal.abort()}));220 expectError(await execa('unicorns', {cancelSignal: false}));221 expectError(execaSync('unicorns', {cancelSignal: false}));222+223+await execa('unicorns', {gracefulCancel: true, cancelSignal: AbortSignal.abort()});224+expectError(execaSync('unicorns', {gracefulCancel: true, cancelSignal: AbortSignal.abort()}));225+expectError(await execa('unicorns', {gracefulCancel: 'true', cancelSignal: AbortSignal.abort()}));226+expectError(execaSync('unicorns', {gracefulCancel: 'true', cancelSignal: AbortSignal.abort()}));modified:test-d/ipc/get-each.test-d.ts+5 added
23 unmodified lines24 expectError(getEachMessage(''));25 26 execa('test', {ipcInput: ''}).getEachMessage();27 execa('test', {ipcInput: '' as Message}).getEachMessage();28+execa('test', {gracefulCancel: true, cancelSignal: AbortSignal.abort()}).getEachMessage();29 execa('test', {} as Options).getEachMessage?.();30 execa('test', {ipc: true as boolean}).getEachMessage?.();31 execa('test', {ipcInput: '' as '' | undefined}).getEachMessage?.();32+execa('test', {gracefulCancel: true as boolean | undefined, cancelSignal: AbortSignal.abort()}).getEachMessage?.();33 34 expectType<undefined>(execa('test').getEachMessage);35 expectType<undefined>(execa('test', {}).getEachMessage);36 expectType<undefined>(execa('test', {ipc: false}).getEachMessage);37 expectType<undefined>(execa('test', {ipcInput: undefined}).getEachMessage);38+expectType<undefined>(execa('test', {gracefulCancel: undefined}).getEachMessage);39+expectType<undefined>(execa('test', {gracefulCancel: false}).getEachMessage);40 expectType<undefined>(execa('test', {ipc: false, ipcInput: ''}).getEachMessage);41+expectType<undefined>(execa('test', {ipc: false, gracefulCancel: true, cancelSignal: AbortSignal.abort()}).getEachMessage);42 43 subprocess.getEachMessage({reference: true} as const);44 getEachMessage({reference: true} as const);45 expectError(subprocess.getEachMessage({reference: 'true'} as const));1 unmodified linemodified:test-d/ipc/get-one.test-d.ts+5 added
17 unmodified lines18 expectError(await getOneMessage({}, ''));19 20 await execa('test', {ipcInput: ''}).getOneMessage();21 await execa('test', {ipcInput: '' as Message}).getOneMessage();22+await execa('test', {gracefulCancel: true, cancelSignal: AbortSignal.abort()}).getOneMessage();23 await execa('test', {} as Options).getOneMessage?.();24 await execa('test', {ipc: true as boolean}).getOneMessage?.();25 await execa('test', {ipcInput: '' as '' | undefined}).getOneMessage?.();26+await execa('test', {gracefulCancel: true as boolean | undefined, cancelSignal: AbortSignal.abort()}).getOneMessage?.();27 28 expectType<undefined>(execa('test').getOneMessage);29 expectType<undefined>(execa('test', {}).getOneMessage);30 expectType<undefined>(execa('test', {ipc: false}).getOneMessage);31 expectType<undefined>(execa('test', {ipcInput: undefined}).getOneMessage);32+expectType<undefined>(execa('test', {gracefulCancel: undefined}).getOneMessage);33+expectType<undefined>(execa('test', {gracefulCancel: false}).getOneMessage);34 expectType<undefined>(execa('test', {ipc: false, ipcInput: ''}).getOneMessage);35+expectType<undefined>(execa('test', {ipc: false, gracefulCancel: true, cancelSignal: AbortSignal.abort()}).getOneMessage);36 37 await subprocess.getOneMessage({filter: undefined} as const);38 await subprocess.getOneMessage({filter: (message: Message<'advanced'>) => true} as const);39 await jsonSubprocess.getOneMessage({filter: (message: Message<'json'>) => true} as const);29 unmodified linesadded:test-d/ipc/graceful.ts+8 added
1+import {expectType, expectError} from 'tsd';2+import {getCancelSignal, execa} from '../../index.js';3+4+expectType<Promise<AbortSignal>>(getCancelSignal());5+6+expectError(await getCancelSignal(''));7+8+expectError(execa('test').getCancelSignal);modified:test-d/ipc/send.test-d.ts+5 added
19 unmodified lines20 expectError(await sendMessage(Symbol('test')));21 22 await execa('test', {ipcInput: ''}).sendMessage('');23 await execa('test', {ipcInput: '' as Message}).sendMessage('');24+await execa('test', {gracefulCancel: true, cancelSignal: AbortSignal.abort()}).sendMessage('');25 await execa('test', {} as Options).sendMessage?.('');26 await execa('test', {ipc: true as boolean}).sendMessage?.('');27 await execa('test', {ipcInput: '' as '' | undefined}).sendMessage?.('');28+await execa('test', {gracefulCancel: true as boolean | undefined, cancelSignal: AbortSignal.abort()}).sendMessage?.('');29 30 expectType<undefined>(execa('test').sendMessage);31 expectType<undefined>(execa('test', {}).sendMessage);32 expectType<undefined>(execa('test', {ipc: false}).sendMessage);33 expectType<undefined>(execa('test', {ipcInput: undefined}).sendMessage);34+expectType<undefined>(execa('test', {gracefulCancel: undefined}).sendMessage);35+expectType<undefined>(execa('test', {gracefulCancel: false}).sendMessage);36 expectType<undefined>(execa('test', {ipc: false, ipcInput: ''}).sendMessage);37+expectType<undefined>(execa('test', {ipc: false, gracefulCancel: true, cancelSignal: AbortSignal.abort()}).sendMessage);38 39 await subprocess.sendMessage('', {} as const);40 await sendMessage('', {} as const);41 await subprocess.sendMessage('', {strict: true} as const);9 unmodified linesmodified:test-d/return/result-ipc.ts+15 added
26 unmodified lines27 28 const genericInputResult = await execa('unicorns', {ipcInput: '' as Message});29 expectType<Array<Message<'advanced'>>>(genericInputResult.ipcOutput);30 31+const gracefulResult = await execa('unicorns', {gracefulCancel: true, cancelSignal: AbortSignal.abort()});32+expectType<Array<Message<'advanced'>>>(gracefulResult.ipcOutput);33+34 const genericResult = await execa('unicorns', {} as Options);35 expectType<Message[] | []>(genericResult.ipcOutput);36 37 const genericIpc = await execa('unicorns', {ipc: true as boolean});1 unmodified line39 40 const maybeInputResult = await execa('unicorns', {ipcInput: '' as '' | undefined});41 expectType<Array<Message<'advanced'>> | []>(maybeInputResult.ipcOutput);42 43+const maybeGracefulResult = await execa('unicorns', {gracefulCancel: true as boolean | undefined, cancelSignal: AbortSignal.abort()});44+expectType<Array<Message<'advanced'>> | []>(maybeGracefulResult.ipcOutput);45+46 const falseIpcResult = await execa('unicorns', {ipc: false});47 expectType<[]>(falseIpcResult.ipcOutput);48 49 const noIpcResult = await execa('unicorns');7 unmodified lines57 58 const inputNoIpcResult = await execa('unicorns', {ipc: false, ipcInput: ''});59 expectType<[]>(inputNoIpcResult.ipcOutput);60 61+const undefinedGracefulResult = await execa('unicorns', {gracefulCancel: undefined});62+expectType<[]>(undefinedGracefulResult.ipcOutput);63+64+const falseGracefulResult = await execa('unicorns', {gracefulCancel: false});65+expectType<[]>(falseGracefulResult.ipcOutput);66+67+const gracefulNoIpcResult = await execa('unicorns', {ipc: false, gracefulCancel: true, cancelSignal: AbortSignal.abort()});68+expectType<[]>(gracefulNoIpcResult.ipcOutput);69+70 const noBufferResult = await execa('unicorns', {ipc: true, buffer: false});71 expectType<[]>(noBufferResult.ipcOutput);72 73 const noBufferFdResult = await execa('unicorns', {ipc: true, buffer: {ipc: false}});21 unmodified linesmodified:test-d/return/result-main.test-d.ts+4 added
25 unmodified lines26 expectType<number | undefined>(unicornsResult.exitCode);27 expectType<boolean>(unicornsResult.failed);28 expectType<boolean>(unicornsResult.timedOut);29 expectType<boolean>(unicornsResult.isCanceled);30+expectType<boolean>(unicornsResult.isGracefullyCanceled);31 expectType<boolean>(unicornsResult.isTerminated);32 expectType<boolean>(unicornsResult.isMaxBuffer);33 expectType<boolean>(unicornsResult.isForcefullyTerminated);34 expectType<keyof SignalConstants | undefined>(unicornsResult.signal);9 unmodified lines44 expectType<number | undefined>(unicornsResultSync.exitCode);45 expectType<boolean>(unicornsResultSync.failed);46 expectType<boolean>(unicornsResultSync.timedOut);47 expectType<boolean>(unicornsResultSync.isCanceled);48+expectType<boolean>(unicornsResultSync.isGracefullyCanceled);49 expectType<boolean>(unicornsResultSync.isTerminated);50 expectType<boolean>(unicornsResultSync.isMaxBuffer);51 expectType<boolean>(unicornsResultSync.isForcefullyTerminated);52 expectType<keyof SignalConstants | undefined>(unicornsResultSync.signal);10 unmodified lines63 expectType<number | undefined>(error.exitCode);64 expectType<boolean>(error.failed);65 expectType<boolean>(error.timedOut);66 expectType<boolean>(error.isCanceled);67+ expectType<boolean>(error.isGracefullyCanceled);68 expectType<boolean>(error.isTerminated);69 expectType<boolean>(error.isMaxBuffer);70 expectType<boolean>(error.isForcefullyTerminated);71 expectType<keyof SignalConstants | undefined>(error.signal);15 unmodified lines87 expectType<number | undefined>(errorSync.exitCode);88 expectType<boolean>(errorSync.failed);89 expectType<boolean>(errorSync.timedOut);90 expectType<boolean>(errorSync.isCanceled);91+ expectType<boolean>(errorSync.isGracefullyCanceled);92 expectType<boolean>(errorSync.isTerminated);93 expectType<boolean>(errorSync.isMaxBuffer);94 expectType<boolean>(errorSync.isForcefullyTerminated);95 expectType<keyof SignalConstants | undefined>(errorSync.signal);9 unmodified linesmodified:types/arguments/options.d.ts+23 added-9 removed
183 unmodified lines184 Largest amount of data allowed on `stdout`, `stderr` and `stdio`.185 186 By default, this applies to both `stdout` and `stderr`, but different values can also be passed.187 188+ When reached, `error.isMaxBuffer` becomes `true`.189+190 @default 100_000_000191 */192 readonly maxBuffer?: FdGenericOption<number>;193 10 unmodified lines204 Enables exchanging messages with the subprocess using `subprocess.sendMessage(message)`, `subprocess.getOneMessage()` and `subprocess.getEachMessage()`.205 206 The subprocess must be a Node.js file.207 206- @default `true` if either the `node` option or the `ipcInput` option is set, `false` otherwise208+ @default `true` if the `node`, `ipcInput` or `gracefulCancel` option is set, `false` otherwise209 */210 readonly ipc?: Unless<IsSync, boolean>;211 212 /**30 unmodified lines243 244 /**245 If `timeout` is greater than `0`, the subprocess will be terminated if it runs for longer than that amount of milliseconds.246 245- On timeout, `result.timedOut` becomes `true`.247+ On timeout, `error.timedOut` becomes `true`.248 249 @default 0250 */251 readonly timeout?: number;252 253 /**252- You can abort the subprocess using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).254+ When the `cancelSignal` is [aborted](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort), terminate the subprocess using a `SIGTERM` signal.255 254- When `AbortController.abort()` is called, `result.isCanceled` becomes `true`.256+ When aborted, `error.isCanceled` becomes `true`.257 258 @example259 ```258- import {execa} from 'execa';260+ import {execaNode} from 'execa';261 260- const abortController = new AbortController();262+ const controller = new AbortController();263+ const cancelSignal = controller.signal;264 265 setTimeout(() => {263- abortController.abort();266+ controller.abort();267 }, 5000);268 269 try {267- await execa({cancelSignal: abortController.signal})`npm run build`;270+ await execaNode({cancelSignal})`build.js`;271 } catch (error) {272 if (error.isCanceled) {270- console.error('Aborted by cancelSignal.');273+ console.error('Canceled by cancelSignal.');274 }275 276 throw error;277 }1 unmodified line279 */280 readonly cancelSignal?: Unless<IsSync, AbortSignal>;281 282 /**283+ When the `cancelSignal` option is [aborted](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort), do not send any `SIGTERM`. Instead, abort the [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) returned by `getCancelSignal()`. The subprocess should use it to terminate gracefully.284+285+ The subprocess must be a Node.js file.286+287+ When aborted, `error.isGracefullyCanceled` becomes `true`.288+289+ @default false290+ */291+ readonly gracefulCancel?: Unless<IsSync, boolean>;292+293+ /**294 If the subprocess is terminated but does not exit, forcefully exit it by sending [`SIGKILL`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGKILL).295 296 When this happens, `error.isForcefullyTerminated` becomes `true`.297 101 unmodified linesmodified:types/methods/main-async.d.ts+29 added
106 unmodified lines107 108 @example <caption>Simple input</caption>109 110 ```111+const getInputString = () => { /* ... *\/ };112 const {stdout} = await execa({input: getInputString()})`sort`;113 console.log(stdout);114 ```115 120 unmodified lines236 ```237 // build.js238 import {sendMessage} from 'execa';239 240+const runBuild = () => { /* ... *\/ };241+242 await sendMessage({kind: 'start', timestamp: new Date()});243 await runBuild();244 await sendMessage({kind: 'stop', timestamp: new Date()});245 ```246 247+@example <caption>Graceful termination</caption>248+249+```250+// main.js251+import {execaNode} from 'execa';252+253+const controller = new AbortController();254+setTimeout(() => {255+ controller.abort();256+}, 5000);257+258+await execaNode({259+ cancelSignal: controller.signal,260+ gracefulCancel: true,261+})`build.js`;262+```263+264+```265+// build.js266+import {getCancelSignal} from 'execa';267+268+const cancelSignal = await getCancelSignal();269+const url = 'https://example.com/build/info';270+const response = await fetch(url, {signal: cancelSignal});271+```272+273 @example <caption>Detailed error</caption>274 275 ```276 import {execa, ExecaError} from 'execa';63 unmodified linesmodified:types/return/result.d.ts+5 added
99 unmodified lines100 */101 isCanceled: boolean;102 103 /**104+ Whether the subprocess was canceled using both the `cancelSignal` and the `gracefulCancel` options.105+ */106+ isGracefullyCanceled: boolean;107+108+ /**109 Whether the subprocess failed because its output was larger than the `maxBuffer` option.110 */111 isMaxBuffer: boolean;112 91 unmodified linesmodified:types/ipc.d.ts+15 added-4 removed
89 unmodified lines90 This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.91 */92 export function getEachMessage(getEachMessageOptions?: GetEachMessageOptions): AsyncIterableIterator<Message>;93 94+/**95+Retrieves the [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) shared by the `cancelSignal` option.96+97+This can only be called inside a subprocess. This requires the `gracefulCancel` option to be `true`.98+*/99+export function getCancelSignal(): Promise<AbortSignal>;100+94-// IPC methods in the current process101+// IPC methods in the subprocess102 export type IpcMethods<103 IpcEnabled extends boolean,104 Serialization extends Options['serialization'],105 > = IpcEnabled extends true27 unmodified lines133 getOneMessage: undefined;134 getEachMessage: undefined;135 };136 130-// Whether IPC is enabled, based on the `ipc` and `ipcInput` options137+// Whether IPC is enabled, based on the `ipc`, `ipcInput` and `gracefulCancel` options138 export type HasIpc<OptionsType extends Options> = HasIpcOption<139 OptionsType['ipc'],133-'ipcInput' extends keyof OptionsType ? OptionsType['ipcInput'] : undefined140+'ipcInput' extends keyof OptionsType ? OptionsType['ipcInput'] : undefined,141+'gracefulCancel' extends keyof OptionsType ? OptionsType['gracefulCancel'] : undefined142 >;143 144 type HasIpcOption<145 IpcOption extends Options['ipc'],146 IpcInputOption extends Options['ipcInput'],147+ GracefulCancelOption extends Options['gracefulCancel'],148 > = IpcOption extends true149 ? true150 : IpcOption extends false151 ? false152 : IpcInputOption extends undefined153+ ? GracefulCancelOption extends true154+ ? true144- ? false155+ : false156 : true;modified:index.d.ts+1 added
19 unmodified lines20 export {21 sendMessage,22 getOneMessage,23 getEachMessage,24+ getCancelSignal,25 type Message,26 } from './types/ipc.js';modified:index.js+2 added
16 unmodified lines17 const {18 sendMessage,19 getOneMessage,20 getEachMessage,21+ getCancelSignal,22 } = getIpcExport();23 export {24 sendMessage,25 getOneMessage,26 getEachMessage,27+ getCancelSignal,28 };modified:readme.md+30 added-1 removed
55 unmodified lines56 - [Simple syntax](#simple-syntax): promises and [template strings](docs/execution.md#template-string-syntax), like [`zx`](docs/bash.md).57 - [Script](#script) interface.58 - [No escaping](docs/escaping.md) nor quoting needed. No risk of shell injection.59 - Execute [locally installed binaries](#local-binaries) without `npx`.60-- Improved [Windows support](docs/windows.md): [shebangs](docs/windows.md#shebang), [`PATHEXT`](https://ss64.com/nt/path.html#pathext), [and more](https://github.com/moxystudio/node-cross-spawn?tab=readme-ov-file#why).60+- Improved [Windows support](docs/windows.md): [shebangs](docs/windows.md#shebang), [`PATHEXT`](https://ss64.com/nt/path.html#pathext), [graceful termination](#graceful-termination), [and more](https://github.com/moxystudio/node-cross-spawn?tab=readme-ov-file#why).61 - [Detailed errors](#detailed-error) and [verbose mode](#verbose-mode), for [debugging](docs/debugging.md).62 - [Pipe multiple subprocesses](#pipe-multiple-subprocesses) better than in shells: retrieve [intermediate results](docs/pipe.md#result), use multiple [sources](docs/pipe.md#multiple-sources-1-destination)/[destinations](docs/pipe.md#1-source-multiple-destinations), [unpipe](docs/pipe.md#unpipe).63 - [Split](#split-into-text-lines) the output into text lines, or [iterate](#iterate-over-text-lines) progressively over them.64 - Strip [unnecessary newlines](docs/lines.md#newlines).121 unmodified lines186 187 #### Simple input188 189 ```js190+const getInputString = () => { /* ... */ };191 const {stdout} = await execa({input: getInputString()})`sort`;192 console.log(stdout);193 ```194 124 unmodified lines319 ```js320 // build.js321 import {sendMessage} from 'execa';322 323+const runBuild = () => { /* ... */ };324+325 await sendMessage({kind: 'start', timestamp: new Date()});326 await runBuild();327 await sendMessage({kind: 'stop', timestamp: new Date()});328 ```329 330+#### Graceful termination331+332+```js333+// main.js334+import {execaNode} from 'execa';335+336+const controller = new AbortController();337+setTimeout(() => {338+ controller.abort();339+}, 5000);340+341+await execaNode({342+ cancelSignal: controller.signal,343+ gracefulCancel: true,344+})`build.js`;345+```346+347+```js348+// build.js349+import {getCancelSignal} from 'execa';350+351+const cancelSignal = await getCancelSignal();352+const url = 'https://example.com/build/info';353+const response = await fetch(url, {signal: cancelSignal});354+```355+356 ### Debugging357 358 #### Detailed error359 62 unmodified lines