Fix error handling of transforms (#739)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent dd9c884 · Browse files · 6 files·+53 added−26 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+53 added−26 removed
- tests:+32 added−8 removed
- other:+21 added−18 removed
Provenance
- Commit
17993a8- Tree
778dc6f- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
dd9c884
6 files changed+53 added−26 removed
modified:lib/stdio/async.js+3 added-2 removed
3 unmodified lines45678910111237 unmodified lines5051525353545556575859606162636364656667683 unmodified linesimport mergeStreams from '@sindresorhus/merge-streams';import {handleInput} from './handle.js';import {TYPE_TO_MESSAGE} from './type.js';import {generatorToDuplexStream, pipeGenerator} from './generator.js';import {pipeStreams} from './utils.js';
// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async modeexport const handleInputAsync = options => handleInput(addPropertiesAsync, options, false);
37 unmodified lines }
for (const [index, inputStreams] of Object.entries(inputStreamsGroups)) { const value = inputStreams.length === 1 ? inputStreams[0] : mergeStreams(inputStreams); value.pipe(spawned.stdio[index]); pipeStreams(value, spawned.stdio[index]); }};
const pipeStdioOption = (spawned, {type, value, direction, index}, inputStreamsGroups) => { if (type === 'native') { return; }
if (direction === 'output') { spawned.stdio[index].pipe(value); pipeStreams(spawned.stdio[index], value); } else { inputStreamsGroups[index] = [...(inputStreamsGroups[index] ?? []), value]; }};modified:lib/stdio/generator.js+4 added-4 removed
123455678997 unmodified lines1071081091101111121131111121131141151161177 unmodified linesimport {generatorsToDuplex} from './duplex.js';import {getEncodingStartGenerator} from './encoding.js';import {getLinesGenerator} from './lines.js';import {isGeneratorOptions} from './type.js';import {isBinary} from './utils.js';import {isBinary, pipeStreams} from './utils.js';
export const normalizeGenerators = stdioStreams => { const nonGenerators = stdioStreams.filter(({type}) => type !== 'generator'); const generators = stdioStreams.filter(({type}) => type === 'generator');97 unmodified lines
// `childProcess.stdin|stdout|stderr|stdio` is directly mutated.export const pipeGenerator = (spawned, {value, direction, index}) => { if (direction === 'output') { spawned.stdio[index].pipe(value); } else { value.pipe(spawned.stdio[index]); pipeStreams(spawned.stdio[index], value); } else { pipeStreams(value, spawned.stdio[index]); }
const streamProperty = PROCESS_STREAM_PROPERTIES[index]; if (streamProperty !== undefined) {7 unmodified linesmodified:lib/stdio/utils.js+14 added
1 import {Buffer} from 'node:buffer';2+import {finished} from 'node:stream/promises';3 4 export const bufferToUint8Array = buffer => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);5 6 export const isUint8Array = value => Object.prototype.toString.call(value) === '[object Uint8Array]' && !Buffer.isBuffer(value);7 export const isBinary = value => isUint8Array(value) || Buffer.isBuffer(value);8 9 const textDecoder = new TextDecoder();10 export const binaryToString = uint8ArrayOrBuffer => textDecoder.decode(uint8ArrayOrBuffer);11+12+// Like `source.pipe(destination)`, if `source` ends, `destination` ends.13+// Like `Stream.pipeline(source, destination)`, if `source` aborts/errors, `destination` aborts.14+// Unlike `Stream.pipeline(source, destination)`, if `destination` ends/aborts/errors, `source` does not end/abort/error.15+export const pipeStreams = async (source, destination) => {16+ source.pipe(destination);17+18+ try {19+ await finished(source);20+ } catch {21+ destination.destroy();22+ }23+};modified:lib/stream.js-12 removed
113 unmodified lines114 const [error] = await once(stream, 'error');115 throw error;116 };117 118-// The streams created by the `std*` options are automatically ended by `.pipe()`.119-// However `.pipe()` only does so when the source stream ended, not when it errored.120-// Therefore, when `childProcess.stdin|stdout|stderr` errors, those streams must be manually destroyed.121-const cleanupStdioStreams = (customStreams, error) => {122- for (const {value} of customStreams) {123- if (!STANDARD_STREAMS.includes(value)) {124- value.destroy(error);125- }126- }127-};128-118 // Like `once()` except it never rejects, especially not on `error` event.119 const pEvent = (eventEmitter, eventName) => new Promise(resolve => {120 eventEmitter.once(eventName, (...payload) => {121 resolve([eventName, ...payload]);57 unmodified lines179 waitForFailedProcess(processSpawnPromise, processErrorPromise, processExitPromise),180 Promise.all(stdioPromises.map(stdioPromise => getBufferedData(stdioPromise, encoding))),181 getBufferedData(allPromise, encoding),182 ]);194- cleanupStdioStreams(customStreams, error);183 await Promise.allSettled(customStreamsEndPromises);184 return results;185 } finally {186 controller.abort();3 unmodified linesmodified:test/stdio/array.js+18 added-7 removed
240 unmodified lines241 test('stderr can be ["overlapped", "pipe"]', testOverlapped, 2);242 test('stdio[*] can be ["overlapped", "pipe"]', testOverlapped, 3);243 244 const testDestroyStandard = async (t, index) => {245- await t.throwsAsync(246- execa('forever.js', {...getStdio(index, [STANDARD_STREAMS[index], 'pipe']), timeout: 1}),247- {message: /timed out/},248- );245+ const childProcess = execa('forever.js', {...getStdio(index, [STANDARD_STREAMS[index], 'pipe']), timeout: 1});246+ await t.throwsAsync(childProcess, {message: /timed out/});247 t.false(STANDARD_STREAMS[index].destroyed);248 };249 252-test('Does not destroy process.stdin on errors', testDestroyStandard, 0);253-test('Does not destroy process.stdout on errors', testDestroyStandard, 1);254-test('Does not destroy process.stderr on errors', testDestroyStandard, 2);250+test('Does not destroy process.stdin on child process errors', testDestroyStandard, 0);251+test('Does not destroy process.stdout on child process errors', testDestroyStandard, 1);252+test('Does not destroy process.stderr on child process errors', testDestroyStandard, 2);253+254+const testDestroyStandardStream = async (t, index) => {255+ const childProcess = execa('forever.js', getStdio(index, [STANDARD_STREAMS[index], 'pipe']));256+ const error = new Error('test');257+ childProcess.stdio[index].destroy(error);258+ const thrownError = await t.throwsAsync(childProcess);259+ t.is(thrownError, error);260+ t.false(STANDARD_STREAMS[index].destroyed);261+};262+263+test('Does not destroy process.stdin on stream process errors', testDestroyStandardStream, 0);264+test('Does not destroy process.stdout on stream process errors', testDestroyStandardStream, 1);265+test('Does not destroy process.stderr on stream process errors', testDestroyStandardStream, 2);modified:test/stdio/generator.js+14 added-1 removed
633 unmodified lines634 {message: /Generator error foobar/},635 );636 });637 638+test('Generators errors make process fail even when other output generators do not throw', async t => {639+ await t.throwsAsync(640+ execa('noop-fd.js', ['1', foobarString], {stdout: [noopGenerator(false), throwingGenerator, noopGenerator(false)]}),641+ {message: /Generator error foobar/},642+ );643+});644+645+test('Generators errors make process fail even when other input generators do not throw', async t => {646+ const childProcess = execa('stdin-fd.js', ['0'], {stdin: [noopGenerator(false), throwingGenerator, noopGenerator(false)]});647+ childProcess.stdin.write('foobar\n');648+ await t.throwsAsync(childProcess, {message: /Generator error foobar/});649+});650+651 // eslint-disable-next-line require-yield652 const errorHandlerGenerator = async function * (state, lines) {653 try {654 // eslint-disable-next-line no-unused-vars4 unmodified lines659 state.error = error;660 }661 };662 650-test.serial('Process streams failures make generators throw', async t => {663+test('Process streams failures make generators throw', async t => {664 const state = {};665 const childProcess = execa('noop-fail.js', ['1'], {stdout: errorHandlerGenerator.bind(undefined, state)});666 const error = new Error('test');667 childProcess.stdout.emit('error', error);5 unmodified lines