Fix error handling of `stdin` (#787)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent d50c4cc · Browse files · 8 files·+157 added−82 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+157 added−82 removed
- tests:+55 added−27 removed
- other:+102 added−55 removed
Provenance
- Commit
4328670- Tree
091a88a- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
d50c4cc
8 files changed+157 added−82 removed
modified:lib/stdio/async.js+4 added-5 removed
40 unmodified lines41424344454546474849505152535454555657583 unmodified lines6263646566666768697016 unmodified lines878889909191929493949596978 unmodified lines40 unmodified lines const inputStreamsGroups = {};
for (const stdioStreams of stdioStreamsGroups) { for (const generatorStream of stdioStreams.filter(({type}) => type === 'generator')) { pipeGenerator(spawned, generatorStream, controller); pipeGenerator(spawned, generatorStream); }
for (const nonGeneratorStream of stdioStreams.filter(({type}) => type !== 'generator')) { pipeStdioOption(spawned, nonGeneratorStream, inputStreamsGroups, controller); } }
for (const [index, inputStreams] of Object.entries(inputStreamsGroups)) { pipeStreams(inputStreams, spawned.stdio[index], controller); pipeStreams(inputStreams, spawned.stdio[index]); }};
const pipeStdioOption = (spawned, {type, value, direction, index}, inputStreamsGroups, controller) => {3 unmodified lines
setStandardStreamMaxListeners(value, controller);
if (direction === 'output') { pipeStreams([spawned.stdio[index]], value, controller); pipeStreams([spawned.stdio[index]], value); } else { inputStreamsGroups[index] = [...(inputStreamsGroups[index] ?? []), value]; }};16 unmodified lines });};
// `source.pipe(destination)` adds at most 1 listener for each event.// We also listen for the stream's completion using `finished()`, which adds 1 more listener.// If `stdin` option is an array, the values might be combined with `merge-streams`.// That library also listens for `source` end, which adds 1 more listener.const maxListenersIncrement = 3;const maxListenersIncrement = 2;
// The stream error handling is performed by the piping logic above, which cannot be performed before process spawning.// If the process spawning fails (e.g. due to an invalid command), the streams need to be manually destroyed.// We need to create those streams before process spawning, in case their creation fails, e.g. when passing an invalid generator as argument.8 unmodified linesmodified:lib/stdio/generator.js+3 added-3 removed
110 unmodified lines111 }112 };113 114 // `childProcess.stdin|stdout|stderr|stdio` is directly mutated.115-export const pipeGenerator = (spawned, {value, direction, index}, controller) => {115+export const pipeGenerator = (spawned, {value, direction, index}) => {116 if (direction === 'output') {117- pipeStreams([spawned.stdio[index]], value, controller);117+ pipeStreams([spawned.stdio[index]], value);118 } else {119- pipeStreams([value], spawned.stdio[index], controller);119+ pipeStreams([value], spawned.stdio[index]);120 }121 122 const streamProperty = PROCESS_STREAM_PROPERTIES[index];123 if (streamProperty !== undefined) {7 unmodified linesmodified:lib/stdio/pipeline.js+32 added-24 removed
12234576978910111213141515161718192019202122232425262726272829303132333432333435363738394041394041424344454647484647484950515252535455565758535455565758596061626364656667import {finished} from 'node:stream/promises';import {setImmediate} from 'node:timers/promises';import mergeStreams from '@sindresorhus/merge-streams';import {isStandardStream} from './utils.js';
// Like `Stream.pipeline(source, destination)`, but does not destroy standard streams.// Also, it prevents some race conditions described below.// `sources` might be a single stream, or multiple ones combined with `merge-stream`.export const pipeStreams = (sources, destination, controller) => {export const pipeStreams = (sources, destination) => { const finishedStreams = new Set();
if (sources.length === 1) { sources[0].pipe(destination); } else { const mergedSource = mergeStreams(sources); mergedSource.pipe(destination); handleDestinationComplete(mergedSource, destination, controller); handleDestinationComplete(mergedSource, destination, finishedStreams); }
for (const source of sources) { handleSourceAbortOrError(source, destination, controller); handleDestinationComplete(source, destination, controller); handleSourceAbortOrError(source, destination, finishedStreams); handleDestinationComplete(source, destination, finishedStreams); }};
// `source.pipe(destination)` makes `destination` end when `source` ends.// But it does not propagate aborts or errors. This function does it.const handleSourceAbortOrError = async (source, destination, {signal}) => { if (isStandardStream(destination)) {const handleSourceAbortOrError = async (source, destination, finishedStreams) => { if (isStandardStream(source) || isStandardStream(destination)) { return; }
try { await finished(source, {cleanup: true, signal}); } catch { await destroyStream(destination); await onFinishedStream(source, finishedStreams); } catch (error) { destroyStream(destination, finishedStreams, error); }};
// The `destination` should never complete before the `source`.// If it does, this indicates something abnormal, so we abort `source`.const handleDestinationComplete = async (source, destination, {signal}) => { if (isStandardStream(source)) {// If it does, this indicates something abnormal, so we abort or error `source`.const handleDestinationComplete = async (source, destination, finishedStreams) => { if (isStandardStream(source) || isStandardStream(destination)) { return; }
try { await finished(destination, {cleanup: true, signal}); } catch {} finally { await destroyStream(source); await onFinishedStream(destination, finishedStreams); destroyStream(source, finishedStreams); } catch (error) { destroyStream(source, finishedStreams, error); }};
// Propagating errors across different streams in the same pipeline can create race conditions.// For example, a `Duplex` stream might propagate an error on its writable side and another on its readable side.// This leads to different errors being thrown at the top-level based on the result of that race condition.// We solve this by waiting for one macrotask with `setImmediate()`.const destroyStream = async stream => { await setImmediate(); stream.destroy();// Both functions above call each other recursively.// `finishedStreams` prevents this cycle.const onFinishedStream = async (stream, finishedStreams) => { try { return await finished(stream, {cleanup: true}); } finally { finishedStreams.add(stream); }};
const destroyStream = (stream, finishedStreams, error) => { if (!finishedStreams.has(stream)) { stream.destroy(error); }};modified:lib/stream.js+59 added-20 removed
1-import {once, addAbortListener} from 'node:events';1+import {addAbortListener} 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';19 unmodified lines25 : applyEncoding(error.bufferedData, encoding);26 }27 };28 29-const getStdioPromise = ({stream, stdioStreams, encoding, buffer, maxBuffer}) => stdioStreams[0].direction === 'output'30- ? getStreamPromise({stream, encoding, buffer, maxBuffer})31- : undefined;29+// Read the contents of `childProcess.std*` and|or wait for its completion30+const waitForChildStreams = ({spawned, stdioStreamsGroups, encoding, buffer, maxBuffer, waitForStream}) => spawned.stdio.map((stream, index) => waitForChildStream({31+ stream,32+ direction: stdioStreamsGroups[index][0].direction,33+ encoding,34+ buffer,35+ maxBuffer,36+ waitForStream,37+}));38 33-const getAllPromise = ({spawned, encoding, buffer, maxBuffer}) => getStreamPromise({stream: getAllStream(spawned, encoding), encoding, buffer, maxBuffer: maxBuffer * 2});39+// Read the contents of `childProcess.all` and|or wait for its completion40+const waitForAllStream = ({spawned, encoding, buffer, maxBuffer, waitForStream}) => waitForChildStream({41+ stream: getAllStream(spawned, encoding),42+ direction: 'output',43+ encoding,44+ buffer,45+ maxBuffer: maxBuffer * 2,46+ waitForStream,47+});48 49 // When `childProcess.stdout` is in objectMode but not `childProcess.stderr` (or the opposite), we need to use both:50 // - `getStreamAsArray()` for the chunks in objectMode, to return as an array without changing each chunk51 // - `getStreamAsArrayBuffer()` or `getStream()` for the chunks not in objectMode, to convert them from Buffers to string or Uint8Array10 unmodified lines62 writableObjectMode: true,63 readableObjectMode: true,64 };65 52-const getStreamPromise = async ({stream, encoding, buffer, maxBuffer}) => {66+const waitForChildStream = async ({stream, direction, encoding, buffer, maxBuffer, waitForStream}) => {67 if (!stream) {68 return;69 }70 71+ if (direction === 'input') {72+ await waitForStream(stream);73+ return;74+ }75+76 if (!buffer) {77 await Promise.all([59- finished(stream, {cleanup: true, readable: true, writable: false}),78+ waitForStream(stream),79 resumeStream(stream),80 ]);81 return;82 }18 unmodified lines101 };102 103 const applyEncoding = (contents, encoding) => encoding === 'buffer' ? new Uint8Array(contents) : contents;104 105+// Transforms replace `childProcess.std*`, which means they are not exposed to users.106+// However, we still want to wait for their completion.107+const waitForOriginalStreams = (originalStreams, spawned, waitForStream) => originalStreams108+ .filter((stream, index) => stream !== spawned.stdio[index])109+ .map(stream => waitForStream(stream));110+111 // Some `stdin`/`stdout`/`stderr` options create a stream, e.g. when passing a file path.112 // The `.pipe()` method automatically ends that stream when `childProcess` ends.113 // This makes sure we wait for the completion of those streams, in order to catch any error.89-const waitForCustomStreamsEnd = stdioStreamsGroups => stdioStreamsGroups.flat()114+const waitForCustomStreamsEnd = (stdioStreamsGroups, waitForStream) => stdioStreamsGroups.flat()115 .filter(({type, value}) => type !== 'native' && !isStandardStream(value))91- .map(({value}) => finished(value, {cleanup: true}));116+ .map(({value}) => waitForStream(value));117 93-const throwIfStreamError = stream => stream === null ? [] : [throwOnStreamError(stream)];94-95-const throwOnStreamError = async stream => {96- const [error] = await once(stream, 'error');97- throw error;98-};99-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]);4 unmodified lines126 eventEmitter.removeListener(eventName, listener);127 });128 });129 130+// Wraps `finished(stream)` to handle the following case:131+// - When the child process exits, Node.js automatically calls `childProcess.stdin.destroy()`, which we need to ignore.132+// - 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+ }145+};146+147 const throwOnProcessError = async processErrorPromise => {148 const [, error] = await processErrorPromise;149 throw error;150 };14 unmodified lines165 spawned,166 options: {encoding, buffer, maxBuffer, timeoutDuration: timeout},167 context,168 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);176 140- const stdioPromises = spawned.stdio.map((stream, index) => getStdioPromise({stream, stdioStreams: stdioStreamsGroups[index], encoding, buffer, maxBuffer}));141- const allPromise = getAllPromise({spawned, encoding, buffer, maxBuffer});142- const customStreamsEndPromises = waitForCustomStreamsEnd(stdioStreamsGroups);177+ const stdioPromises = waitForChildStreams({spawned, stdioStreamsGroups, encoding, buffer, maxBuffer, waitForStream});178+ const allPromise = waitForAllStream({spawned, encoding, buffer, maxBuffer, waitForStream});179+ const originalPromises = waitForOriginalStreams(originalStreams, spawned, waitForStream);180+ const customStreamsEndPromises = waitForCustomStreamsEnd(stdioStreamsGroups, waitForStream);181 182 try {183 return await Promise.race([184 Promise.all([185 undefined,186 processExitPromise,187 Promise.all(stdioPromises),188 allPromise,189+ ...originalPromises,190 ...customStreamsEndPromises,191 ]),192 throwOnProcessError(processErrorPromise),154- ...throwIfStreamError(spawned.stdin),193 ...throwOnTimeout(timeout, context, controller),194 ]);195 } catch (error) {196 spawned.kill();1 unmodified line198 error,199 waitForFailedProcess(processSpawnPromise, processErrorPromise, processExitPromise),200 Promise.all(stdioPromises.map(stdioPromise => getBufferedData(stdioPromise, encoding))),201 getBufferedData(allPromise, encoding),202+ Promise.allSettled(originalPromises),203 Promise.allSettled(customStreamsEndPromises),204 ]);205 }206 };modified:test/stdio/async.js+3 added-2 removed
1 import {once, defaultMaxListeners} from 'node:events';2 import process from 'node:process';3-import {setTimeout} from 'node:timers/promises';3+import {setImmediate} from 'node:timers/promises';4 import test from 'ava';5 import {execa} from '../../index.js';6 import {STANDARD_STREAMS} from '../helpers/stdio.js';7 import {foobarString} from '../helpers/input.js';19 unmodified lines27 once(childProcess.stdin, 'unpipe'),28 once(process.stdout, 'unpipe'),29 once(process.stderr, 'unpipe'),30 ]);31+ await setImmediate();32 33 for (const [index, streamNewListeners] of Object.entries(getStandardStreamsListeners())) {34 const defaultListeners = Object.fromEntries(Reflect.ownKeys(streamNewListeners).map(eventName => [eventName, []]));35 t.deepEqual(streamNewListeners, {...defaultListeners, ...streamsPreviousListeners[index]});27 unmodified lines63 try {64 const results = await Promise.all(65 Array.from({length: processesCount}, () => execa('empty.js', getComplexStdio(isMultiple))),66 );66- await setTimeout(0);67+ await setImmediate();68 t.true(results.every(({exitCode}) => exitCode === 0));69 t.is(warning, undefined);70 } finally {71 for (const standardStream of STANDARD_STREAMS) {18 unmodified linesmodified:test/kill.js+6 added-4 removed
390 unmodified lines391 392 test('child process errors use killSignal', async t => {393 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});394 await once(subprocess, 'spawn');395- subprocess.emit('error', new Error('test'));396- const {isTerminated, signal} = await t.throwsAsync(subprocess, {message: /test/});397- t.true(isTerminated);398- t.is(signal, 'SIGINT');395+ const error = new Error('test');396+ subprocess.emit('error', error);397+ const thrownError = await t.throwsAsync(subprocess);398+ t.is(thrownError, error);399+ t.true(thrownError.isTerminated);400+ t.is(thrownError.signal, 'SIGINT');401 });modified:test/stream.js+46 added-21 removed
6 unmodified lines7 import {execa, execaSync} from '../index.js';8 import {setFixtureDir} from './helpers/fixtures-dir.js';9 import {fullStdio, getStdio} from './helpers/stdio.js';10 import {foobarString} from './helpers/input.js';11+import {infiniteGenerator} from './helpers/generator.js';12 13 setFixtureDir();14 15 test.serial('result.all shows both `stdout` and `stderr` intermixed', async t => {131 unmodified lines147 148 const testNoBufferStreamError = async (t, index, all) => {149 const subprocess = execa('noop-fd.js', [`${index}`], {...fullStdio, buffer: false, all});150 const stream = all ? subprocess.all : subprocess.stdio[index];150- stream.destroy(new Error('test'));151- await t.throwsAsync(subprocess, {message: /test/});151+ const error = new Error('test');152+ stream.destroy(error);153+ t.is(await t.throwsAsync(subprocess), error);154 };155 156 test('Listen to stdout errors even when `buffer` is `false`', testNoBufferStreamError, 1, false);157 test('Listen to stderr errors even when `buffer` is `false`', testNoBufferStreamError, 2, false);153 unmodified lines311 test('Process buffers stderr, which does not prevent exit if read and buffer is false', testBufferRead, 2, false);312 test('Process buffers stdio[*], which does not prevent exit if read and buffer is false', testBufferRead, 3, false);313 test('Process buffers all, which does not prevent exit if read and buffer is false', testBufferRead, 1, true);314 315+const getStreamDestroyOptions = (index, isInput) => {316+ if (index !== 3) {317+ return {};318+ }319+320+ return getStdio(3, isInput ? [new Uint8Array(), infiniteGenerator] : 'pipe');321+};322+323+const testStreamAbort = async (t, index, isInput) => {324+ const childProcess = execa('forever.js', getStreamDestroyOptions(index, isInput));325+ childProcess.stdio[index].destroy();326+ await t.throwsAsync(childProcess, {code: 'ERR_STREAM_PREMATURE_CLOSE'});327+};328+329+test('Aborting stdin should make the process exit', testStreamAbort, 0, true);330+test('Aborting stdout should make the process exit', testStreamAbort, 1, false);331+test('Aborting stderr should make the process exit', testStreamAbort, 2, false);332+test('Aborting output stdio[*] should make the process exit', testStreamAbort, 3, false);333+test('Aborting input stdio[*] should make the process exit', testStreamAbort, 3, true);334+313-const testStreamDestroy = async (t, index) => {314- const childProcess = execa('forever.js', fullStdio);335+const testStreamDestroy = async (t, index, isInput) => {336+ const childProcess = execa('forever.js', getStreamDestroyOptions(index, isInput));337 const error = new Error('test');338 childProcess.stdio[index].destroy(error);317- await t.throwsAsync(childProcess, {message: /test/});339+ t.is(await t.throwsAsync(childProcess), error);340 };341 320-test('Destroying stdin should make the process exit', testStreamDestroy, 0);321-test('Destroying stdout should make the process exit', testStreamDestroy, 1);322-test('Destroying stderr should make the process exit', testStreamDestroy, 2);323-test('Destroying stdio[*] should make the process exit', testStreamDestroy, 3);342+test('Destroying stdin should make the process exit', testStreamDestroy, 0, true);343+test('Destroying stdout should make the process exit', testStreamDestroy, 1, false);344+test('Destroying stderr should make the process exit', testStreamDestroy, 2, false);345+test('Destroying output stdio[*] should make the process exit', testStreamDestroy, 3, false);346+test('Destroying input stdio[*] should make the process exit', testStreamDestroy, 3, true);347 325-const testStreamError = async (t, index) => {326- const childProcess = execa('forever.js', fullStdio);327- await setImmediate();348+const testStreamError = async (t, index, isInput) => {349+ const childProcess = execa('forever.js', getStreamDestroyOptions(index, isInput));350 const error = new Error('test');351 childProcess.stdio[index].emit('error', error);330- await t.throwsAsync(childProcess, {message: /test/});352+ t.is(await t.throwsAsync(childProcess), error);353 };354 333-test('Errors on stdin should make the process exit', testStreamError, 0);334-test('Errors on stdout should make the process exit', testStreamError, 1);335-test('Errors on stderr should make the process exit', testStreamError, 2);336-test('Errors on stdio[*] should make the process exit', testStreamError, 3);355+test('Errors on stdin should make the process exit', testStreamError, 0, true);356+test('Errors on stdout should make the process exit', testStreamError, 1, false);357+test('Errors on stderr should make the process exit', testStreamError, 2, false);358+test('Errors on output stdio[*] should make the process exit', testStreamError, 3, false);359+test('Errors on input stdio[*] should make the process exit', testStreamError, 3, true);360 361 test('Errors on streams use killSignal', async t => {362 const childProcess = execa('forever.js', {killSignal: 'SIGINT'});340- childProcess.stdout.destroy(new Error('test'));341- const {isTerminated, signal} = await t.throwsAsync(childProcess, {message: /test/});342- t.true(isTerminated);343- t.is(signal, 'SIGINT');363+ const error = new Error('test');364+ childProcess.stdout.destroy(error);365+ const thrownError = await t.throwsAsync(childProcess);366+ t.is(thrownError, error);367+ t.true(error.isTerminated);368+ t.is(error.signal, 'SIGINT');369 });370 371 const testWaitOnStreamEnd = async (t, index) => {372 const childProcess = execa('stdin-fd.js', [`${index}`], fullStdio);58 unmodified linesmodified:index.js+4 added-3 removed
153 unmodified lines154 155 const controller = new AbortController();156 setMaxListeners(Number.POSITIVE_INFINITY, controller.signal);157 158+ const originalStreams = [...spawned.stdio];159 pipeOutputAsync(spawned, stdioStreamsGroups, controller);160 cleanupOnExit(spawned, options, controller);161 162 spawned.kill = spawnedKill.bind(undefined, spawned.kill.bind(spawned), options, controller);163 spawned.all = makeAllStream(spawned, options);164 spawned.pipe = pipeToProcess.bind(undefined, {spawned, stdioStreamsGroups, options});165 165- const promise = handlePromise({spawned, options, stdioStreamsGroups, command, escapedCommand, controller});166+ const promise = handlePromise({spawned, options, stdioStreamsGroups, originalStreams, command, escapedCommand, controller});167 mergePromise(spawned, promise);168 return spawned;169 }170 170-const handlePromise = async ({spawned, options, stdioStreamsGroups, command, escapedCommand, controller}) => {171+const handlePromise = async ({spawned, options, stdioStreamsGroups, originalStreams, command, escapedCommand, controller}) => {172 const context = {timedOut: false};173 174 const [175 error,176 [, exitCode, signal],177 stdioResults,178 allResult,178- ] = await getSpawnedResult({spawned, options, context, stdioStreamsGroups, controller});179+ ] = await getSpawnedResult({spawned, options, context, stdioStreamsGroups, originalStreams, controller});180 controller.abort();181 182 const stdio = stdioResults.map(stdioResult => handleOutput(options, stdioResult));183 const all = handleOutput(options, allResult);180 unmodified lines