Fix child process not handling multiple `error` events (#790)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 81f0b2d · Browse files · 5 files·+81 added−50 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+81 added−50 removed
- tests:+37 added−4 removed
- other:+44 added−46 removed
Provenance
- Commit
4080212- Tree
1e314e2- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
81f0b2d
5 files changed+81 added−50 removed
modified:lib/kill.js+2 added-2 removed
46 unmodified lines47484950515251525354555624 unmodified lines46 unmodified lines
return forceKillAfterDelay;};
const killAfterTimeout = async (timeout, context, controller) => { await setTimeout(timeout, undefined, {signal: controller.signal});const killAfterTimeout = async (timeout, context, {signal}) => { await setTimeout(timeout, undefined, {signal}); context.timedOut = true; throw new Error('Timed out');};
24 unmodified linesmodified:lib/stream.js+41 added-43 removed
1-import {addAbortListener} from 'node:events';1+import {once} from 'node:events';2 import {finished} from 'node:stream/promises';3 import {setImmediate} from 'node:timers/promises';4 import getStream, {getStreamAsArrayBuffer, getStreamAsArray} from 'get-stream';5 import mergeStreams from '@sindresorhus/merge-streams';108 unmodified lines114 const waitForCustomStreamsEnd = (stdioStreamsGroups, waitForStream) => stdioStreamsGroups.flat()115 .filter(({type, value}) => type !== 'native' && !isStandardStream(value))116 .map(({value}) => waitForStream(value));117 118-// Like `once()` except it never rejects, especially not on `error` event.119-const pEvent = (eventEmitter, eventName, {signal}) => new Promise(resolve => {120- const listener = (...payload) => {121- resolve([eventName, ...payload]);122- };123-124- eventEmitter.once(eventName, listener);125- addAbortListener(signal, () => {126- eventEmitter.removeListener(eventName, listener);127- });128-});129-118 // Wraps `finished(stream)` to handle the following case:119 // - When the child process exits, Node.js automatically calls `childProcess.stdin.destroy()`, which we need to ignore.120 // - However, we still need to throw if `childProcess.stdin.destroy()` is called before child process exit.133-const onFinishedStream = async ([originalStdin], processExitPromise, stream) => {134- const finishedPromise = finished(stream, {cleanup: true});135- if (stream !== originalStdin) {136- await finishedPromise;137- return;138- }139-140- try {141- await finishedPromise;142- } catch {143- await Promise.race([processExitPromise, finishedPromise]);144- }121+const onFinishedStream = async ([originalStdin], exitPromise, stream) => {122+ await Promise.race([123+ ...(stream === originalStdin ? [exitPromise] : []),124+ finished(stream, {cleanup: true}),125+ ]);126 };127 147-const throwOnProcessError = async processErrorPromise => {148- const [, error] = await processErrorPromise;128+const throwOnProcessError = async (spawned, {signal}) => {129+ const [error] = await once(spawned, 'error', {signal});130 throw error;131 };132 152-// First the `spawn` event is emitted, then `exit`.153-// If the `error` event is emitted:154-// - before `spawn`: `exit` is never emitted.155-// - after `spawn`: `exit` is always emitted.156-// We only want to listen to `exit` if it will be emitted, i.e. if `spawn` has been emitted.157-// Therefore, the arguments order of `Promise.race()` is significant.158-const waitForFailedProcess = async (processSpawnPromise, processErrorPromise, processExitPromise) => {159- const [eventName] = await Promise.race([processSpawnPromise, processErrorPromise]);160- return eventName === 'spawn' ? processExitPromise : [];133+// If `error` is emitted before `spawn`, `exit` will never be emitted.134+// However, `error` might be emitted after `spawn`, e.g. with the `signal` option.135+// In that case, `exit` will still be emitted.136+// Since the `exit` event contains the signal name, we want to make sure we are listening for it.137+// This function also takes into account the following unlikely cases:138+// - `exit` being emitted in the same microtask as `spawn`139+// - `error` being emitted multiple times140+const waitForExit = async spawned => {141+ const [spawnPayload, exitPayload] = await Promise.allSettled([142+ once(spawned, 'spawn'),143+ once(spawned, 'exit'),144+ ]);145+146+ if (spawnPayload.status === 'rejected') {147+ return [];148+ }149+150+ return exitPayload.status === 'rejected'151+ ? waitForProcessExit(spawned)152+ : exitPayload.value;153 };154 155+const waitForProcessExit = async spawned => {156+ try {157+ return await once(spawned, 'exit');158+ } catch {159+ return waitForProcessExit(spawned);160+ }161+};162+163 // Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)164 export const getSpawnedResult = async ({165 spawned,166 options: {encoding, buffer, maxBuffer, timeoutDuration: timeout},1 unmodified line168 stdioStreamsGroups,169 originalStreams,170 controller,171 }) => {172- const processSpawnPromise = pEvent(spawned, 'spawn', controller);173- const processErrorPromise = pEvent(spawned, 'error', controller);174- const processExitPromise = pEvent(spawned, 'exit', controller);175- const waitForStream = onFinishedStream.bind(undefined, originalStreams, processExitPromise);172+ const exitPromise = waitForExit(spawned);173+ const waitForStream = onFinishedStream.bind(undefined, originalStreams, exitPromise);174 175 const stdioPromises = waitForChildStreams({spawned, stdioStreamsGroups, encoding, buffer, maxBuffer, waitForStream});176 const allPromise = waitForAllStream({spawned, encoding, buffer, maxBuffer, waitForStream});177 const originalPromises = waitForOriginalStreams(originalStreams, spawned, waitForStream);2 unmodified lines180 try {181 return await Promise.race([182 Promise.all([183 undefined,186- processExitPromise,184+ exitPromise,185 Promise.all(stdioPromises),186 allPromise,187 ...originalPromises,188 ...customStreamsEndPromises,189 ]),192- throwOnProcessError(processErrorPromise),190+ throwOnProcessError(spawned, controller),191 ...throwOnTimeout(timeout, context, controller),192 ]);193 } catch (error) {194 spawned.kill();195 return Promise.all([196 error,199- waitForFailedProcess(processSpawnPromise, processErrorPromise, processExitPromise),197+ exitPromise,198 Promise.all(stdioPromises.map(stdioPromise => getBufferedData(stdioPromise, encoding))),199 getBufferedData(allPromise, encoding),200 Promise.allSettled(originalPromises),201 Promise.allSettled(customStreamsEndPromises),3 unmodified linesmodified:test/stdio/async.js+1 added
63 unmodified lines64656667686970717218 unmodified lines63 unmodified lines const results = await Promise.all( Array.from({length: processesCount}, () => execa('empty.js', getComplexStdio(isMultiple))), ); await setImmediate(); await setImmediate(); t.true(results.every(({exitCode}) => exitCode === 0)); t.is(warning, undefined); } finally { for (const standardStream of STANDARD_STREAMS) {18 unmodified linesmodified:test/kill.js+36 added-4 removed
1 import process from 'node:process';2 import {once, defaultMaxListeners} from 'node:events';3 import {constants} from 'node:os';4-import {setTimeout} from 'node:timers/promises';4+import {setTimeout, setImmediate} from 'node:timers/promises';5 import test from 'ava';6 import {pEvent} from 'p-event';7 import isRunning from 'is-running';8 import {execa, execaSync} from '../index.js';373 unmodified lines382 abortController.abort();383 t.false(result.isCanceled);384 });385 386-test('child process errors are handled', async t => {386+test('child process errors are handled before spawn', async t => {387 const subprocess = execa('forever.js');388- subprocess.emit('error', new Error('test'));389- await t.throwsAsync(subprocess, {message: 'Command failed: forever.js\ntest'});388+ const error = new Error('test');389+ subprocess.emit('error', error);390+ const thrownError = await t.throwsAsync(subprocess);391+ t.is(thrownError, error);392+ t.is(thrownError.exitCode, undefined);393+ t.is(thrownError.signal, undefined);394+ t.false(thrownError.isTerminated);395 });396 397+test('child process errors are handled after spawn', async t => {398+ const subprocess = execa('forever.js');399+ await once(subprocess, 'spawn');400+ const error = new Error('test');401+ subprocess.emit('error', error);402+ const thrownError = await t.throwsAsync(subprocess);403+ t.is(thrownError, error);404+ t.is(thrownError.exitCode, undefined);405+ t.is(thrownError.signal, 'SIGTERM');406+ t.true(thrownError.isTerminated);407+});408+409+test('child process double errors are handled after spawn', async t => {410+ const abortController = new AbortController();411+ const subprocess = execa('forever.js', {signal: abortController.signal});412+ await once(subprocess, 'spawn');413+ const error = new Error('test');414+ subprocess.emit('error', error);415+ await setImmediate();416+ abortController.abort();417+ const thrownError = await t.throwsAsync(subprocess);418+ t.is(thrownError, error);419+ t.is(thrownError.exitCode, undefined);420+ t.is(thrownError.signal, 'SIGTERM');421+ t.true(thrownError.isTerminated);422+});423+424 test('child process errors use killSignal', async t => {425 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});426 await once(subprocess, 'spawn');427 const error = new Error('test');6 unmodified linesmodified:index.js+1 added-1 removed
173 unmodified lines174 const context = {timedOut: false};175 176 const [177 error,178- [, exitCode, signal],178+ [exitCode, signal],179 stdioResults,180 allResult,181 ] = await getSpawnedResult({spawned, options, context, stdioStreamsGroups, originalStreams, controller});182 controller.abort();183 unmodified lines