Skip to content
Myr

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

8 files+157 added−82 removed

modified:lib/stdio/async.js+4 added-5 removed
modified:lib/stdio/generator.js+3 added-3 removed
110 unmodified lines
111 }112};113114// `childProcess.stdin|stdout|stderr|stdio` is directly mutated.115export const pipeGenerator = (spawned, {value, direction, index}, controller) => {115export 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 }121122 const streamProperty = PROCESS_STREAM_PROPERTIES[index];123 if (streamProperty !== undefined) {
7 unmodified lines
modified:lib/stdio/pipeline.js+32 added-24 removed
modified:lib/stream.js+59 added-20 removed
1import {once, addAbortListener} from 'node:events';1import {addAbortListener} from 'node:events';2import {finished} from 'node:stream/promises';3import {setImmediate} from 'node:timers/promises';4import getStream, {getStreamAsArrayBuffer, getStreamAsArray} from 'get-stream';5import mergeStreams from '@sindresorhus/merge-streams';
19 unmodified lines
25 : applyEncoding(error.bufferedData, encoding);26 }27};2829const 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 completion30const 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}));3833const 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 completion40const 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});4849// 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 Uint8Array
10 unmodified lines
62 writableObjectMode: true,63 readableObjectMode: true,64};6552const getStreamPromise = async ({stream, encoding, buffer, maxBuffer}) => {66const waitForChildStream = async ({stream, direction, encoding, buffer, maxBuffer, waitForStream}) => {67 if (!stream) {68 return;69 }7071 if (direction === 'input') {72 await waitForStream(stream);73 return;74 }7576 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 lines
101};102103const applyEncoding = (contents, encoding) => encoding === 'buffer' ? new Uint8Array(contents) : contents;104105// Transforms replace `childProcess.std*`, which means they are not exposed to users.106// However, we still want to wait for their completion.107const waitForOriginalStreams = (originalStreams, spawned, waitForStream) => originalStreams108 .filter((stream, index) => stream !== spawned.stdio[index])109 .map(stream => waitForStream(stream));110111// 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.89const waitForCustomStreamsEnd = stdioStreamsGroups => stdioStreamsGroups.flat()114const 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));11793const throwIfStreamError = stream => stream === null ? [] : [throwOnStreamError(stream)];9495const throwOnStreamError = async stream => {96 const [error] = await once(stream, 'error');97 throw error;98};99118// Like `once()` except it never rejects, especially not on `error` event.119const pEvent = (eventEmitter, eventName, {signal}) => new Promise(resolve => {120 const listener = (...payload) => {121 resolve([eventName, ...payload]);
4 unmodified lines
126 eventEmitter.removeListener(eventName, listener);127 });128});129130// 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.133const onFinishedStream = async ([originalStdin], processExitPromise, stream) => {134 const finishedPromise = finished(stream, {cleanup: true});135 if (stream !== originalStdin) {136 await finishedPromise;137 return;138 }139140 try {141 await finishedPromise;142 } catch {143 await Promise.race([processExitPromise, finishedPromise]);144 }145};146147const throwOnProcessError = async processErrorPromise => {148 const [, error] = await processErrorPromise;149 throw error;150};
14 unmodified lines
165 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);176140 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);181182 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 line
198 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
1import {once, defaultMaxListeners} from 'node:events';2import process from 'node:process';3import {setTimeout} from 'node:timers/promises';3import {setImmediate} from 'node:timers/promises';4import test from 'ava';5import {execa} from '../../index.js';6import {STANDARD_STREAMS} from '../helpers/stdio.js';7import {foobarString} from '../helpers/input.js';
19 unmodified lines
27 once(childProcess.stdin, 'unpipe'),28 once(process.stdout, 'unpipe'),29 once(process.stderr, 'unpipe'),30 ]);31 await setImmediate();3233 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 lines
63 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 lines
modified:test/kill.js+6 added-4 removed
390 unmodified lines
391392test('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 lines
7import {execa, execaSync} from '../index.js';8import {setFixtureDir} from './helpers/fixtures-dir.js';9import {fullStdio, getStdio} from './helpers/stdio.js';10import {foobarString} from './helpers/input.js';11import {infiniteGenerator} from './helpers/generator.js';1213setFixtureDir();1415test.serial('result.all shows both `stdout` and `stderr` intermixed', async t => {
131 unmodified lines
147148const 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};155156test('Listen to stdout errors even when `buffer` is `false`', testNoBufferStreamError, 1, false);157test('Listen to stderr errors even when `buffer` is `false`', testNoBufferStreamError, 2, false);
153 unmodified lines
311test('Process buffers stderr, which does not prevent exit if read and buffer is false', testBufferRead, 2, false);312test('Process buffers stdio[*], which does not prevent exit if read and buffer is false', testBufferRead, 3, false);313test('Process buffers all, which does not prevent exit if read and buffer is false', testBufferRead, 1, true);314315const getStreamDestroyOptions = (index, isInput) => {316 if (index !== 3) {317 return {};318 }319320 return getStdio(3, isInput ? [new Uint8Array(), infiniteGenerator] : 'pipe');321};322323const 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};328329test('Aborting stdin should make the process exit', testStreamAbort, 0, true);330test('Aborting stdout should make the process exit', testStreamAbort, 1, false);331test('Aborting stderr should make the process exit', testStreamAbort, 2, false);332test('Aborting output stdio[*] should make the process exit', testStreamAbort, 3, false);333test('Aborting input stdio[*] should make the process exit', testStreamAbort, 3, true);334313const testStreamDestroy = async (t, index) => {314 const childProcess = execa('forever.js', fullStdio);335const 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};341320test('Destroying stdin should make the process exit', testStreamDestroy, 0);321test('Destroying stdout should make the process exit', testStreamDestroy, 1);322test('Destroying stderr should make the process exit', testStreamDestroy, 2);323test('Destroying stdio[*] should make the process exit', testStreamDestroy, 3);342test('Destroying stdin should make the process exit', testStreamDestroy, 0, true);343test('Destroying stdout should make the process exit', testStreamDestroy, 1, false);344test('Destroying stderr should make the process exit', testStreamDestroy, 2, false);345test('Destroying output stdio[*] should make the process exit', testStreamDestroy, 3, false);346test('Destroying input stdio[*] should make the process exit', testStreamDestroy, 3, true);347325const testStreamError = async (t, index) => {326 const childProcess = execa('forever.js', fullStdio);327 await setImmediate();348const 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};354333test('Errors on stdin should make the process exit', testStreamError, 0);334test('Errors on stdout should make the process exit', testStreamError, 1);335test('Errors on stderr should make the process exit', testStreamError, 2);336test('Errors on stdio[*] should make the process exit', testStreamError, 3);355test('Errors on stdin should make the process exit', testStreamError, 0, true);356test('Errors on stdout should make the process exit', testStreamError, 1, false);357test('Errors on stderr should make the process exit', testStreamError, 2, false);358test('Errors on output stdio[*] should make the process exit', testStreamError, 3, false);359test('Errors on input stdio[*] should make the process exit', testStreamError, 3, true);360361test('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});370371const testWaitOnStreamEnd = async (t, index) => {372 const childProcess = execa('stdin-fd.js', [`${index}`], fullStdio);
58 unmodified lines
modified:index.js+4 added-3 removed
153 unmodified lines
154155 const controller = new AbortController();156 setMaxListeners(Number.POSITIVE_INFINITY, controller.signal);157158 const originalStreams = [...spawned.stdio];159 pipeOutputAsync(spawned, stdioStreamsGroups, controller);160 cleanupOnExit(spawned, options, controller);161162 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});165165 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}170170const handlePromise = async ({spawned, options, stdioStreamsGroups, command, escapedCommand, controller}) => {171const handlePromise = async ({spawned, options, stdioStreamsGroups, originalStreams, command, escapedCommand, controller}) => {172 const context = {timedOut: false};173174 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();181182 const stdio = stdioResults.map(stdioResult => handleOutput(options, stdioResult));183 const all = handleOutput(options, allResult);
180 unmodified lines