Refactor `subprocess.kill(error)` (#1023)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent c5bd9d8 · Browse files · 8 files·+26 added−30 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+26 added−30 removed
- tests:+1 added−1 removed
- other:+25 added−29 removed
Provenance
- Commit
9de7335- Tree
c456320- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
c5bd9d8
8 files changed+26 added−30 removed
modified:lib/convert/concurrent.js+1 added-1 removed
11234528 unmodified linesimport {createDeferred} from './shared.js';import {createDeferred} from '../utils/deferred.js';
// When using multiple `.readable()`/`.writable()`/`.duplex()`, `final` and `destroy` should wait for other streamsexport const initializeConcurrentStreams = () => ({ readableDestroy: new WeakMap(),28 unmodified linesmodified:lib/convert/readable.js+1 added-1 removed
1234567889101112101 unmodified linesExpand allimport {Readable} from 'node:stream';import {callbackify} from 'node:util';import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';import {getFromStream} from '../arguments/fd-options.js';import {iterateOnSubprocessStream, DEFAULT_OBJECT_HIGH_WATER_MARK} from '../io/iterate.js';import {createDeferred} from '../utils/deferred.js';import {addConcurrentStream, waitForConcurrentStreams} from './concurrent.js';import { createDeferred, safeWaitForSubprocessStdin, waitForSubprocessStdout, waitForSubprocess, destroyOtherStream,101 unmodified linesExpand allmodified:lib/convert/shared.js-8 removed
42 unmodified lines43444546474849505152535442 unmodified lines } else if (isOpen) { stream.destroy(); }};
export const createDeferred = () => { let resolve; const promise = new Promise(resolve_ => { resolve = resolve_; }); return Object.assign(promise, {resolve});};modified:lib/methods/main-async.js+7 added-2 removed
15 unmodified lines16 import {logEarlyResult} from '../verbose/complete.js';17 import {makeAllStream} from '../resolve/all-async.js';18 import {waitForSubprocessResult} from '../resolve/wait-subprocess.js';19 import {addConvertedStreams} from '../convert/add.js';20+import {createDeferred} from '../utils/deferred.js';21 import {mergePromise} from './promise.js';22 23 // Main shared logic for all async methods: `execa()`, `execaCommand()`, `$`, `execaNode()`24 export const execaCoreAsync = (rawFile, rawArguments, rawOptions, createNested) => {75 unmodified lines100 const originalStreams = [...subprocess.stdio];101 pipeOutputAsync(subprocess, fileDescriptors, controller);102 cleanupOnExit(subprocess, options, controller);103 104+ const onInternalError = createDeferred();105 subprocess.kill = subprocessKill.bind(undefined, {106 kill: subprocess.kill.bind(subprocess),105- subprocess,107 options,108+ onInternalError,109 controller,110 });111 subprocess.all = makeAllStream(subprocess, options);112 addConvertedStreams(subprocess, options);6 unmodified lines119 fileDescriptors,120 originalStreams,121 command,122 escapedCommand,123+ onInternalError,124 controller,125 });126 return {subprocess, promise};127 };128 129 // Asynchronous logic, as opposed to the previous logic which can be run synchronously, i.e. can be returned to user right away127-const handlePromise = async ({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, controller}) => {130+const handlePromise = async ({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, onInternalError, controller}) => {131 const context = {timedOut: false};132 133 const [errorInfo, [exitCode, signal], stdioResults, allResult] = await waitForSubprocessResult({134 subprocess,1 unmodified line136 context,137 verboseInfo,138 fileDescriptors,139 originalStreams,140+ onInternalError,141 controller,142 });143 controller.abort();144+ onInternalError.resolve();145 146 const stdio = stdioResults.map((stdioResult, fdNumber) => stripNewline(stdioResult, options, fdNumber));147 const all = stripNewline(allResult, options, 'all');148 const result = getAsyncResult({38 unmodified linesmodified:lib/resolve/wait-subprocess.js+2 added-9 removed
1 import {once} from 'node:events';2 import {isStream as isNodeStream} from 'is-stream';3-import {errorSignal} from '../terminate/kill.js';3 import {throwOnTimeout} from '../terminate/timeout.js';4 import {isStandardStream} from '../utils/standard-stream.js';5 import {TRANSFORM_TYPES} from '../stdio/type.js';6 import {getBufferedData} from '../io/contents.js';9 unmodified lines16 context,17 verboseInfo,18 fileDescriptors,19 originalStreams,20+ onInternalError,21 controller,22 }) => {23 const exitPromise = waitForExit(subprocess);24 const streamInfo = {36 unmodified lines61 allPromise,62 ...originalPromises,63 ...customStreamsEndPromises,64 ]),65+ onInternalError,66 throwOnSubprocessError(subprocess, controller),66- throwOnInternalError(subprocess, controller),67 ...throwOnTimeout(subprocess, timeout, context, controller),68 ]);69 } catch (error) {70 return Promise.all([28 unmodified lines99 const throwOnSubprocessError = async (subprocess, {signal}) => {100 const [error] = await once(subprocess, 'error', {signal});101 throw error;102 };103-104-// Fails right away when calling `subprocess.kill(error)`.105-// Does not wait for actual signal termination.106-const throwOnInternalError = async (subprocess, {signal}) => {107- const [error] = await once(subprocess, errorSignal, {signal});108- throw error;109-};modified:lib/terminate/kill.js+7 added-8 removed
21 unmodified lines22 const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;23 24 // Monkey-patches `subprocess.kill()` to add `forceKillAfterDelay` behavior and `.kill(error)`25 export const subprocessKill = (26- {kill, subprocess, options: {forceKillAfterDelay, killSignal}, controller},26+ {kill, options: {forceKillAfterDelay, killSignal}, onInternalError, controller},27 signalOrError,28 errorArgument,29 ) => {30 const {signal, error} = parseKillArguments(signalOrError, errorArgument, killSignal);31- emitKillError(subprocess, error);31+ emitKillError(error, onInternalError);32 const killResult = kill(signal);33 setKillTimeout({34 kill,35 signal,20 unmodified lines56 57 return {signal, error};58 };59 60+// Fails right away when calling `subprocess.kill(error)`.61+// Does not wait for actual signal termination.62+// Uses a deferred promise instead of the `error` event on the subprocess, as this is less intrusive.60-const emitKillError = (subprocess, error) => {63+const emitKillError = (error, onInternalError) => {64 if (error !== undefined) {62- subprocess.emit(errorSignal, error);65+ onInternalError.reject(error);66 }67 };68 66-// Like `error` signal but internal to Execa.67-// E.g. does not make subprocess crash when no `error` listener is set.68-export const errorSignal = Symbol('error');69-69 const setKillTimeout = async ({kill, signal, forceKillAfterDelay, killSignal, killResult, controller}) => {70 if (!shouldForceKill(signal, forceKillAfterDelay, killSignal, killResult)) {71 return;72 }15 unmodified linesadded:lib/utils/deferred.js+7 added
1+export const createDeferred = () => {2+ const methods = {};3+ const promise = new Promise((resolve, reject) => {4+ Object.assign(methods, {resolve, reject});5+ });6+ return Object.assign(promise, methods);7+};modified:test/resolve/wait-subprocess.js+1 added-1 removed
17 unmodified lines18 test('stdio[*] is undefined if ignored - sync', testIgnore, 3, execaSync);19 20 const testSubprocessEventsCleanup = async (t, fixtureName) => {21 const subprocess = execa(fixtureName, {reject: false});22- t.deepEqual(subprocess.eventNames().map(String).sort(), ['Symbol(error)', 'error', 'exit', 'spawn']);22+ t.deepEqual(subprocess.eventNames().map(String).sort(), ['error', 'exit', 'spawn']);23 await subprocess;24 t.deepEqual(subprocess.eventNames(), []);25 };26 23 unmodified lines