Improve streams pipe logic (#885)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 6fda30f · Browse files · 9 files·+90 added−90 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+90 added−90 removed
- tests:+48 added−20 removed
- other:+42 added−70 removed
Provenance
- Commit
5abc429- Tree
cff59ae- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
6fda30f
9 files changed+90 added−90 removed
modified:lib/pipe/streaming.js+8 added-26 removed
123456784 unmodified lines1314151617181920212223242223242525262728292 unmodified lines323334353636373839404142434445464748495051383940554142435960616263644445464748495051import {finished} from 'node:stream/promises';import mergeStreams from '@sindresorhus/merge-streams';import {incrementMaxListeners} from '../utils.js';import {pipeStreams} from '../stdio/pipeline.js';
// The piping behavior is like Bash.// In particular, when one process exits, the other is not terminated by a signal.// Instead, its stdout (for the source) or stdin (for the destination) closes.4 unmodified lines const mergedStream = MERGED_STREAMS.has(destinationStream) ? pipeMoreProcessStream(sourceStream, destinationStream) : pipeFirstProcessStream(sourceStream, destinationStream); incrementMaxListeners(sourceStream, SOURCE_LISTENERS_PER_PIPE, maxListenersController.signal); incrementMaxListeners(destinationStream, DESTINATION_LISTENERS_PER_PIPE, maxListenersController.signal); cleanupMergedStreamsMap(destinationStream); return mergedStream;};
// We use `merge-streams` to allow for multiple sources to pipe to the same destination.const pipeFirstProcessStream = (sourceStream, destinationStream) => { const mergedStream = mergeStreams([sourceStream]); mergedStream.pipe(destinationStream, {end: false});
onSourceStreamFinish(mergedStream, destinationStream); pipeStreams(mergedStream, destinationStream); onDestinationStreamFinish(mergedStream, destinationStream); MERGED_STREAMS.set(destinationStream, mergedStream); return mergedStream;};
2 unmodified lines mergedStream.add(sourceStream); return mergedStream;};
const onSourceStreamFinish = async (mergedStream, destinationStream) => {const cleanupMergedStreamsMap = async destinationStream => { try { await finished(mergedStream, {cleanup: true, readable: true, writable: false}); } catch {}
endDestinationStream(destinationStream);};
export const endDestinationStream = destinationStream => { if (destinationStream.writable) { destinationStream.end(); }};
const onDestinationStreamFinish = async (mergedStream, destinationStream) => { try { await finished(destinationStream, {cleanup: true, readable: false, writable: true}); } catch {}
abortSourceStream(mergedStream); MERGED_STREAMS.delete(destinationStream);};
export const abortSourceStream = mergedStream => { if (mergedStream.readable) { mergedStream.destroy(); }};
const MERGED_STREAMS = new WeakMap();
// Number of listeners set up on `sourceStream` by each `sourceStream.pipe(destinationStream)`// Those are added by `merge-streams`const SOURCE_LISTENERS_PER_PIPE = 2;// Number of listeners set up on `destinationStream` by each `sourceStream.pipe(destinationStream)`// Those are added by `finished()` in `cleanupMergedStreamsMap()`const DESTINATION_LISTENERS_PER_PIPE = 1;modified:lib/pipe/throw.js+1 added-1 removed
122345636 unmodified linesimport {makeEarlyError} from '../return/error.js';import {abortSourceStream, endDestinationStream} from './streaming.js';import {abortSourceStream, endDestinationStream} from '../stdio/pipeline.js';
export const handlePipeArgumentsError = ({ sourceStream, sourceError,36 unmodified linesmodified:lib/stdio/async.js+4 added-2 removed
1 import {createReadStream, createWriteStream} from 'node:fs';2 import {Buffer} from 'node:buffer';3 import {Readable, Writable} from 'node:stream';4+import mergeStreams from '@sindresorhus/merge-streams';5 import {isStandardStream, incrementMaxListeners} from '../utils.js';6 import {handleInput} from './handle.js';7 import {pipeStreams} from './pipeline.js';8 import {TYPE_TO_MESSAGE} from './type.js';42 unmodified lines51 }52 }53 54 for (const [fdNumber, inputStreams] of Object.entries(inputStreamsGroups)) {55+ const inputStream = inputStreams.length === 1 ? inputStreams[0] : mergeStreams(inputStreams);54- pipeStreams(inputStreams, spawned.stdio[fdNumber]);56+ pipeStreams(inputStream, spawned.stdio[fdNumber]);57 }58 };59 60 const pipeStdioOption = (spawned, {type, value, direction, fdNumber}, inputStreamsGroups, controller) => {3 unmodified lines64 65 setStandardStreamMaxListeners(value, controller);66 67 if (direction === 'output') {66- pipeStreams([spawned.stdio[fdNumber]], value);68+ pipeStreams(spawned.stdio[fdNumber], value);69 } else {70 inputStreamsGroups[fdNumber] = [...(inputStreamsGroups[fdNumber] ?? []), value];71 }72 };25 unmodified linesmodified:lib/stdio/generator.js+2 added-2 removed
85 unmodified lines86 87 // `childProcess.stdin|stdout|stderr|stdio` is directly mutated.88 export const pipeGenerator = (spawned, {value, direction, fdNumber}) => {89 if (direction === 'output') {90- pipeStreams([spawned.stdio[fdNumber]], value);90+ pipeStreams(spawned.stdio[fdNumber], value);91 } else {92- pipeStreams([value], spawned.stdio[fdNumber]);92+ pipeStreams(value, spawned.stdio[fdNumber]);93 }94 95 const streamProperty = PROCESS_STREAM_PROPERTIES[fdNumber];96 if (streamProperty !== undefined) {7 unmodified linesmodified:lib/stdio/pipeline.js+26 added-38 removed
12323478910111213141516171819202122567891011122728291314151617183435363719202122232440414243444546252627282930505131323334353655565758373839404142434445464748import {finished} from 'node:stream/promises';import mergeStreams from '@sindresorhus/merge-streams';import {isStreamAbort} from '../stream/wait.js';import {isStandardStream} from '../utils.js';
// Like `Stream.pipeline(source, destination)`, but does not destroy standard streams.// `sources` might be a single stream, or multiple ones combined with `merge-stream`.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); handleStreamError(destination, mergedSource, finishedStreams); }
for (const source of sources) { handleStreamError(source, destination, finishedStreams); handleStreamError(destination, source, finishedStreams); }export const pipeStreams = (source, destination) => { source.pipe(destination); onSourceFinish(source, destination); onDestinationFinish(source, destination);};
// `source.pipe(destination)` makes `destination` end when `source` ends.// But it does not propagate aborts or errors. This function does it.// We do the same thing in the other direction as well.const handleStreamError = async (stream, otherStream, finishedStreams) => { if (isStandardStream(stream) || isStandardStream(otherStream)) {const onSourceFinish = async (source, destination) => { if (isStandardStream(source) || isStandardStream(destination)) { return; }
try { await onFinishedStream(stream, finishedStreams); } catch (error) { destroyStream(otherStream, finishedStreams, error); } await finished(source, {cleanup: true, readable: true, writable: false}); } catch {}
endDestinationStream(destination);};
// Both functions above call each other recursively.// `finishedStreams` prevents this cycle.const onFinishedStream = async (stream, finishedStreams) => { try { await finished(stream, {cleanup: true}); } finally { finishedStreams.add(stream);export const endDestinationStream = destination => { if (destination.writable) { destination.end(); }};
const destroyStream = (stream, finishedStreams, error) => { if (finishedStreams.has(stream)) {// We do the same thing in the other direction as well.const onDestinationFinish = async (source, destination) => { if (isStandardStream(source) || isStandardStream(destination)) { return; }
if (isStreamAbort(error)) { stream.destroy(); } else { stream.destroy(error); try { await finished(destination, {cleanup: true, readable: false, writable: true}); } catch {}
abortSourceStream(source);};
export const abortSourceStream = source => { if (source.readable) { source.destroy(); }};modified:lib/stream/wait.js+1 added-1 removed
52 unmodified lines53 54 // When `stream.destroy()` is called without an `error` argument, stream is aborted.55 // This is the only way to abort a readable stream, which can be useful in some instances.56 // Therefore, we ignore this error on readable streams.57-export const isStreamAbort = error => error?.code === 'ERR_STREAM_PREMATURE_CLOSE';57+const isStreamAbort = error => error?.code === 'ERR_STREAM_PREMATURE_CLOSE';58 59 // When `stream.write()` is called but the underlying source has been closed, `EPIPE` is emitted.60 // When piping processes, the source process usually decides when to stop piping.61 // However, there are some instances when the destination does instead, such as `... | head -n1`.3 unmodified linesmodified:test/helpers/stream.js+2 added-2 removed
112345667import {Readable, Writable, Duplex} from 'node:stream';import {Readable, Writable, PassThrough} from 'node:stream';import {foobarString} from './input.js';
export const noopReadable = () => new Readable({read() {}});export const noopWritable = () => new Writable({write() {}});export const noopDuplex = () => new Duplex({read() {}, write() {}});export const noopDuplex = () => new PassThrough().resume();export const simpleReadable = () => Readable.from([foobarString]);modified:test/stdio/node-stream.js+40 added
264 unmodified lines265 266 test('Can pass Duplex streams to stdout', testOutputDuplexStream, 1);267 test('Can pass Duplex streams to stderr', testOutputDuplexStream, 2);268 test('Can pass Duplex streams to output stdio[*]', testOutputDuplexStream, 3);269+270+const testInputStreamAbort = async (t, fdNumber) => {271+ const stream = new PassThrough();272+ stream.destroy();273+274+ const childProcess = execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, new Uint8Array()]));275+ await childProcess;276+ t.true(childProcess.stdio[fdNumber].writableEnded);277+};278+279+test('childProcess.stdin is ended when an input stream aborts', testInputStreamAbort, 0);280+test('childProcess.stdio[*] is ended when an input stream aborts', testInputStreamAbort, 3);281+282+const testInputStreamError = async (t, fdNumber) => {283+ const stream = new PassThrough();284+ const error = new Error(foobarString);285+ stream.destroy(error);286+287+ const childProcess = execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, new Uint8Array()]));288+ t.is(await t.throwsAsync(childProcess), error);289+ t.true(childProcess.stdio[fdNumber].writableEnded);290+};291+292+test('childProcess.stdin is ended when an input stream errors', testInputStreamError, 0);293+test('childProcess.stdio[*] is ended when an input stream errors', testInputStreamError, 3);294+295+const testOutputStreamError = async (t, fdNumber) => {296+ const stream = new PassThrough();297+ const error = new Error(foobarString);298+ stream.destroy(error);299+300+ const childProcess = execa('noop-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, 'pipe']));301+ t.is(await t.throwsAsync(childProcess), error);302+ t.true(childProcess.stdio[fdNumber].readableAborted);303+ t.is(childProcess.stdio[fdNumber].errored, null);304+};305+306+test('childProcess.stdout is aborted when an output stream errors', testOutputStreamError, 1);307+test('childProcess.stderr is aborted when an output stream errors', testOutputStreamError, 2);308+test('childProcess.stdio[*] is aborted when an output stream errors', testOutputStreamError, 3);modified:test/stream/wait.js+6 added-18 removed
115 unmodified lines116 test('Throws abort error when output stdio[*] option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, true);117 test('Throws abort error when output stdio[*] Duplex option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, true);118 119 // eslint-disable-next-line max-params120-const testStreamEpipeSuccess = async (t, streamMethod, stream, fdNumber, useTransform) => {121- const childProcess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));122- streamMethod({stream, childProcess, fdNumber});123- childProcess.stdin.end(foobarString);124-125- const {stdio} = await childProcess;126- t.is(stdio[fdNumber], foobarString);127- t.true(stream.destroyed);128-};129-130-test('Passes when stdout option ends with more writes', testStreamEpipeSuccess, endOptionStream, noopWritable(), 1, false);131-test('Passes when stderr option ends with more writes', testStreamEpipeSuccess, endOptionStream, noopWritable(), 2, false);132-test('Passes when output stdio[*] option ends with more writes', testStreamEpipeSuccess, endOptionStream, noopWritable(), 3, false);133-test('Passes when stdout option ends with more writes, with a transform', testStreamEpipeSuccess, endOptionStream, noopWritable(), 1, true);134-test('Passes when stderr option ends with more writes, with a transform', testStreamEpipeSuccess, endOptionStream, noopWritable(), 2, true);135-test('Passes when output stdio[*] option ends with more writes, with a transform', testStreamEpipeSuccess, endOptionStream, noopWritable(), 3, true);136-137-// eslint-disable-next-line max-params120 const testStreamEpipeFail = async (t, streamMethod, stream, fdNumber, useTransform) => {121 const childProcess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));122 streamMethod({stream, childProcess, fdNumber});123 await setImmediate();7 unmodified lines131 t.true(stderr.includes('EPIPE'));132 }133 };134 135+test('Throws EPIPE when stdout option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 1, false);136 test('Throws EPIPE when stdout option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, false);137 test('Throws EPIPE when stdout option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, false);138+test('Throws EPIPE when stderr option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 2, false);139 test('Throws EPIPE when stderr option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, false);140 test('Throws EPIPE when stderr option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, false);141+test('Throws EPIPE when output stdio[*] option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 3, false);142 test('Throws EPIPE when output stdio[*] option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, false);143 test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, false);144 test('Throws EPIPE when childProcess.stdout aborts with more writes', testStreamEpipeFail, destroyChildStream, noopWritable(), 1, false);145 test('Throws EPIPE when childProcess.stdout Duplex aborts with more writes', testStreamEpipeFail, destroyChildStream, noopDuplex(), 1, false);146 test('Throws EPIPE when childProcess.stderr aborts with more writes', testStreamEpipeFail, destroyChildStream, noopWritable(), 2, false);147 test('Throws EPIPE when childProcess.stderr Duplex aborts with more writes', testStreamEpipeFail, destroyChildStream, noopDuplex(), 2, false);148 test('Throws EPIPE when output childProcess.stdio[*] aborts with more writes', testStreamEpipeFail, destroyChildStream, noopWritable(), 3, false);149 test('Throws EPIPE when output childProcess.stdio[*] Duplex aborts with more writes', testStreamEpipeFail, destroyChildStream, noopDuplex(), 3, false);150+test('Throws EPIPE when stdout option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 1, true);151 test('Throws EPIPE when stdout option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, true);152 test('Throws EPIPE when stdout option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, true);153+test('Throws EPIPE when stderr option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 2, true);154 test('Throws EPIPE when stderr option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, true);155 test('Throws EPIPE when stderr option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, true);156+test('Throws EPIPE when output stdio[*] option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 3, true);157 test('Throws EPIPE when output stdio[*] option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, true);158 test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, true);159 test('Throws EPIPE when childProcess.stdout aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopWritable(), 1, true);160 test('Throws EPIPE when childProcess.stdout Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopDuplex(), 1, true);56 unmodified lines