Improve stream cleanup and termination logic (#775)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 14f040e · Browse files · 10 files·+169 added−78 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+169 added−78 removed
- tests:+89 added−25 removed
- other:+80 added−53 removed
Provenance
- Commit
5aa90bd- Tree
900bc58- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
14f040e
10 files changed+169 added−78 removed
modified:lib/stdio/async.js+8 added-9 removed
1234456788910111222 unmodified lines3536373839394041424344444546474848495051525354535455565857585960616264636465666712 unmodified linesimport {createReadStream, createWriteStream} from 'node:fs';import {Buffer} from 'node:buffer';import {Readable, Writable} from 'node:stream';import mergeStreams from '@sindresorhus/merge-streams';import {handleInput} from './handle.js';import {pipeStreams} from './pipeline.js';import {TYPE_TO_MESSAGE} from './type.js';import {generatorToDuplexStream, pipeGenerator} from './generator.js';import {pipeStreams, isStandardStream} from './utils.js';import {isStandardStream} from './utils.js';
// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async modeexport const handleInputAsync = options => handleInput(addPropertiesAsync, options, false);
22 unmodified lines};
// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, after spawning, in async mode// When multiple input streams are used, we merge them to ensure the output stream ends only once each input stream has endedexport const pipeOutputAsync = (spawned, stdioStreamsGroups) => {export const pipeOutputAsync = (spawned, stdioStreamsGroups, controller) => { const inputStreamsGroups = {};
for (const stdioStreams of stdioStreamsGroups) { for (const generatorStream of stdioStreams.filter(({type}) => type === 'generator')) { pipeGenerator(spawned, generatorStream); pipeGenerator(spawned, generatorStream, controller); }
for (const nonGeneratorStream of stdioStreams.filter(({type}) => type !== 'generator')) { pipeStdioOption(spawned, nonGeneratorStream, inputStreamsGroups); pipeStdioOption(spawned, nonGeneratorStream, inputStreamsGroups, controller); } }
for (const [index, inputStreams] of Object.entries(inputStreamsGroups)) { const value = inputStreams.length === 1 ? inputStreams[0] : mergeStreams(inputStreams); pipeStreams(value, spawned.stdio[index]); pipeStreams(inputStreams, spawned.stdio[index], controller); }};
const pipeStdioOption = (spawned, {type, value, direction, index}, inputStreamsGroups) => {const pipeStdioOption = (spawned, {type, value, direction, index}, inputStreamsGroups, controller) => { if (type === 'native') { return; }
if (direction === 'output') { pipeStreams(spawned.stdio[index], value); pipeStreams([spawned.stdio[index]], value, controller); } else { inputStreamsGroups[index] = [...(inputStreamsGroups[index] ?? []), value]; }};12 unmodified linesmodified:lib/stdio/generator.js+5 added-4 removed
1 import {generatorsToTransform} from './transform.js';2 import {getEncodingStartGenerator} from './encoding.js';3 import {getLinesGenerator} from './lines.js';4+import {pipeStreams} from './pipeline.js';5 import {isGeneratorOptions, isAsyncGenerator} from './type.js';5-import {isBinary, pipeStreams} from './utils.js';6+import {isBinary} from './utils.js';7 8 export const normalizeGenerators = stdioStreams => {9 const nonGenerators = stdioStreams.filter(({type}) => type !== 'generator');10 const generators = stdioStreams.filter(({type}) => type === 'generator');100 unmodified lines111 }112 };113 114 // `childProcess.stdin|stdout|stderr|stdio` is directly mutated.114-export const pipeGenerator = (spawned, {value, direction, index}) => {115+export const pipeGenerator = (spawned, {value, direction, index}, controller) => {116 if (direction === 'output') {116- pipeStreams(spawned.stdio[index], value);117+ pipeStreams([spawned.stdio[index]], value, controller);118 } else {118- pipeStreams(value, spawned.stdio[index]);119+ pipeStreams([value], spawned.stdio[index], controller);120 }121 122 const streamProperty = PROCESS_STREAM_PROPERTIES[index];123 if (streamProperty !== undefined) {7 unmodified linesadded:lib/stdio/pipeline.js+59 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import {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) => { if (sources.length === 1) { sources[0].pipe(destination); } else { const mergedSource = mergeStreams(sources); mergedSource.pipe(destination); handleDestinationComplete(mergedSource, destination, controller); }
for (const source of sources) { handleSourceAbortOrError(source, destination, controller); handleDestinationComplete(source, destination, controller); }};
// `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)) { return; }
try { await finished(source, {cleanup: true, signal}); } catch { await destroyStream(destination); }};
// 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)) { return; }
try { await finished(destination, {cleanup: true, signal}); } catch {} finally { await destroyStream(source); }};
// 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();};modified:lib/stdio/utils.js-14 removed
1233456789101113141516171819202122232425121314import {Buffer} from 'node:buffer';import process from 'node:process';import {finished} from 'node:stream/promises';
export const bufferToUint8Array = buffer => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
export const isUint8Array = value => Object.prototype.toString.call(value) === '[object Uint8Array]' && !Buffer.isBuffer(value);export const isBinary = value => isUint8Array(value) || Buffer.isBuffer(value);
const textDecoder = new TextDecoder();export const binaryToString = uint8ArrayOrBuffer => textDecoder.decode(uint8ArrayOrBuffer);
// Like `source.pipe(destination)`, if `source` ends, `destination` ends.// Like `Stream.pipeline(source, destination)`, if `source` aborts/errors, `destination` aborts.// Unlike `Stream.pipeline(source, destination)`, if `destination` ends/aborts/errors, `source` does not end/abort/error.export const pipeStreams = async (source, destination) => { source.pipe(destination);
try { await finished(source); } catch { destination.destroy(); }};
export const isStandardStream = stream => STANDARD_STREAMS.includes(stream);export const STANDARD_STREAMS = [process.stdin, process.stdout, process.stderr];export const STANDARD_STREAMS_ALIASES = ['stdin', 'stdout', 'stderr'];modified:lib/stream.js+7 added-25 removed
81 unmodified lines82 };83 84 const applyEncoding = (contents, encoding) => encoding === 'buffer' ? new Uint8Array(contents) : contents;85 86-// Retrieve streams created by the `std*` options87-const getCustomStreams = stdioStreamsGroups => stdioStreamsGroups.flat().filter(({type}) => type !== 'native');86+// Some `stdin`/`stdout`/`stderr` options create a stream, e.g. when passing a file path.87+// The `.pipe()` method automatically ends that stream when `childProcess` ends.88+// This makes sure we wait for the completion of those streams, in order to catch any error.89+const waitForCustomStreamsEnd = stdioStreamsGroups => stdioStreamsGroups.flat()90+ .filter(({type, value}) => type !== 'native' && !isStandardStream(value))91+ .map(({value}) => finished(value, {cleanup: true}));92 89-// Some `stdout`/`stderr` options create a stream, e.g. when passing a file path.90-// The `.pipe()` method automatically ends that stream when `childProcess.stdout|stderr` ends.91-// This makes sure we want for the completion of those streams, in order to catch any error.92-// Since we want to end those streams, they cannot be infinite, except for `process.stdout|stderr`.93-// However, for the `stdin`/`input`/`inputFile` options, we only wait for errors, not completion.94-// This is because source streams completion should end destination streams, but not the other way around.95-// This allows for source streams to pipe to multiple destinations.96-// We make an exception for `fileUrl` and `filePath`, since we create that source stream and we know it is piped to a single destination.97-const waitForCustomStreamsEnd = customStreams => customStreams98- .filter(({value, type, direction}) => shouldWaitForCustomStream(value, type, direction))99- .map(({value}) => finished(value));100-101-const throwOnCustomStreamsError = customStreams => customStreams102- .filter(({value, type, direction}) => !shouldWaitForCustomStream(value, type, direction))103- .map(({value}) => throwOnStreamError(value));104-105-const shouldWaitForCustomStream = (value, type, direction) => (type === 'fileUrl' || type === 'filePath')106- || (direction === 'output' && !isStandardStream(value));107-93 const throwIfStreamError = stream => stream === null ? [] : [throwOnStreamError(stream)];94 95 const throwOnStreamError = async stream => {96 const [error] = await once(stream, 'error');39 unmodified lines136 const processSpawnPromise = pEvent(spawned, 'spawn', controller);137 const processErrorPromise = pEvent(spawned, 'error', controller);138 const processExitPromise = pEvent(spawned, 'exit', controller);139 155- const customStreams = getCustomStreams(stdioStreamsGroups);156-140 const stdioPromises = spawned.stdio.map((stream, index) => getStdioPromise({stream, stdioStreams: stdioStreamsGroups[index], encoding, buffer, maxBuffer}));141 const allPromise = getAllPromise({spawned, encoding, buffer, maxBuffer});159- const customStreamsEndPromises = waitForCustomStreamsEnd(customStreams);142+ const customStreamsEndPromises = waitForCustomStreamsEnd(stdioStreamsGroups);143 144 try {145 return await Promise.race([146 Promise.all([3 unmodified lines150 allPromise,151 ...customStreamsEndPromises,152 ]),153 throwOnProcessError(processErrorPromise),171- ...throwOnCustomStreamsError(customStreams),154 ...throwIfStreamError(spawned.stdin),155 ...throwOnTimeout(timeout, context, controller),156 ]);157 } catch (error) {10 unmodified linesmodified:test/stdio/file-path.js+11 added-1 removed
139 unmodified lines140 test('stdio[*] must be an object when it is a file path string - sync', testFilePathObject, 3, execaSync);141 142 const testFileError = async (t, mapFile, index) => {143 await t.throwsAsync(144- execa('empty.js', getStdio(index, mapFile('./unknown/file'))),144+ execa('forever.js', getStdio(index, mapFile('./unknown/file'))),145 {code: 'ENOENT'},146 );147 };148 51 unmodified lines200 test('input Uint8Array and stdin can be both set - sync', testMultipleInputs, [0, 'binary'], execaSync);201 test('stdin and inputFile can be both set - sync', testMultipleInputs, [0, 'inputFile'], execaSync);202 test('input String, stdin and inputFile can be all set - sync', testMultipleInputs, ['inputFile', 0, 'string'], execaSync);203 test('input Uint8Array, stdin and inputFile can be all set - sync', testMultipleInputs, ['inputFile', 0, 'binary'], execaSync);204+205+const testInputFileHanging = async (t, mapFilePath) => {206+ const filePath = tempfile();207+ await writeFile(filePath, 'foobar');208+ await t.throwsAsync(execa('stdin.js', {stdin: mapFilePath(filePath), timeout: 1}), {message: /timed out/});209+ await rm(filePath);210+};211+212+test('Passing an input file path when process exits does not make promise hang', testInputFileHanging, getAbsolutePath);213+test('Passing an input file URL when process exits does not make promise hang', testInputFileHanging, pathToFileURL);modified:test/stdio/iterable.js+7 added-23 removed
1 import {once} from 'node:events';2-import {setTimeout, setImmediate} from 'node:timers/promises';2+import {setImmediate} from 'node:timers/promises';3 import test from 'ava';4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDir} from '../helpers/fixtures-dir.js';6 import {getStdio} from '../helpers/stdio.js';7 import {foobarObject, foobarObjectString} from '../helpers/input.js';8-import {serializeGenerator} from '../helpers/generator.js';8+import {serializeGenerator, infiniteGenerator} from '../helpers/generator.js';9 10 const stringArray = ['foo', 'bar'];11 12 const stringGenerator = function * () {92 unmodified lines105 test('stderr option cannot be an iterable', testNoIterableOutput, stringGenerator(), 2, execa);106 test('stdout option cannot be an iterable - sync', testNoIterableOutput, stringGenerator(), 1, execaSync);107 test('stderr option cannot be an iterable - sync', testNoIterableOutput, stringGenerator(), 2, execaSync);108 109-const infiniteGenerator = () => {110- const controller = new AbortController();111-112- const generator = async function * () {113- yield 'foo';114- await setTimeout(1e7, undefined, {signal: controller.signal});115- };116-117- return {iterable: generator(), abort: controller.abort.bind(controller)};118-};119-109 test('stdin option can be an infinite iterable', async t => {121- const {iterable, abort} = infiniteGenerator();122- try {123- const childProcess = execa('stdin.js', getStdio(0, iterable));124- const stdout = await once(childProcess.stdout, 'data');125- t.is(stdout.toString(), 'foo');126- childProcess.kill('SIGKILL');127- await t.throwsAsync(childProcess, {message: /SIGKILL/});110+ const childProcess = execa('stdin.js', getStdio(0, infiniteGenerator()));111+ const stdout = await once(childProcess.stdout, 'data');112+ t.true(stdout.toString().startsWith('foo'));113+ childProcess.kill();114+ await t.throwsAsync(childProcess, {code: 'ERR_STREAM_PREMATURE_CLOSE'});128- } finally {129- abort();130- }115 });116 117 const testMultipleIterable = async (t, index) => {118 const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, [stringGenerator(), asyncGenerator()]));5 unmodified linesmodified:test/stdio/node-stream.js+62 added-1 removed
115 unmodified lines116 test('stdout can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 1);117 test('stderr can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 2);118 test('stdio[*] can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 3);119 120-test('Wait for custom streams destroy on process errors', async t => {120+test('Waits for custom streams destroy on process errors', async t => {121 let waitedForDestroy = false;122 const stream = new Writable({123 destroy: callbackify(async error => {124 await setImmediate();16 unmodified lines141 };142 143 test('Input streams are canceled on early process exit', testStreamEarlyExit, noopReadable(), 'stdin');144 test('Output streams are canceled on early process exit', testStreamEarlyExit, noopWritable(), 'stdout');145+146+test('Handles output streams ends', async t => {147+ const stream = noopWritable();148+ stream.end();149+ await t.throwsAsync(150+ execa('forever.js', {stdout: [stream, 'pipe']}),151+ {code: 'ERR_STREAM_PREMATURE_CLOSE'},152+ );153+});154+155+const testStreamAbort = async (t, stream, streamName) => {156+ stream.destroy();157+ await t.throwsAsync(158+ execa('forever.js', {[streamName]: [stream, 'pipe']}),159+ {code: 'ERR_STREAM_PREMATURE_CLOSE'},160+ );161+};162+163+test('Handles input streams aborts', testStreamAbort, noopReadable(), 'stdin');164+test('Handles output streams aborts', testStreamAbort, noopWritable(), 'stdout');165+166+const testStreamError = async (t, stream, streamName) => {167+ const error = new Error('test');168+ stream.destroy(error);169+ t.is(170+ await t.throwsAsync(execa('forever.js', {[streamName]: [stream, 'pipe']})),171+ error,172+ );173+};174+175+test('Handles input streams errors', testStreamError, noopReadable(), 'stdin');176+test('Handles output streams errors', testStreamError, noopWritable(), 'stdout');177+178+test('Handles childProcess.stdin end', async t => {179+ const stream = noopReadable();180+ const childProcess = execa('forever.js', {stdin: [stream, 'pipe']});181+ childProcess.stdin.end();182+ await t.throwsAsync(childProcess, {code: 'ERR_STREAM_PREMATURE_CLOSE'});183+ t.true(stream.destroyed);184+});185+186+const testChildStreamAbort = async (t, stream, streamName) => {187+ const childProcess = execa('forever.js', {[streamName]: [stream, 'pipe']});188+ childProcess[streamName].destroy();189+ await t.throwsAsync(childProcess, {code: 'ERR_STREAM_PREMATURE_CLOSE'});190+ t.true(stream.destroyed);191+};192+193+test('Handles childProcess.stdin aborts', testChildStreamAbort, noopReadable(), 'stdin');194+test('Handles childProcess.stdout aborts', testChildStreamAbort, noopWritable(), 'stdout');195+196+const testChildStreamError = async (t, stream, streamName) => {197+ const childProcess = execa('forever.js', {[streamName]: [stream, 'pipe']});198+ const error = new Error('test');199+ childProcess[streamName].destroy(error);200+ t.is(await t.throwsAsync(childProcess), error);201+ t.true(stream.destroyed);202+};203+204+test('Handles childProcess.stdin errors', testChildStreamError, noopReadable(), 'stdin');205+test('Handles childProcess.stdout errors', testChildStreamError, noopWritable(), 'stdout');modified:test/stdio/web-stream.js+9 added
85 unmodified lines86 };87 88 test('stdin option handles errors in ReadableStream', testReadableStreamError, 0);89 test('stdio[*] option handles errors in ReadableStream', testReadableStreamError, 3);90+91+test('ReadableStream with stdin is canceled on process exit', async t => {92+ let readableStream;93+ const promise = new Promise(resolve => {94+ readableStream = new ReadableStream({cancel: resolve});95+ });96+ await t.throwsAsync(execa('stdin.js', {stdin: readableStream, timeout: 1}), {message: /timed out/});97+ await promise;98+});modified:index.js+1 added-1 removed
153 unmodified lines154 155 const controller = new AbortController();156 setMaxListeners(Number.POSITIVE_INFINITY, controller.signal);157 158- pipeOutputAsync(spawned, stdioStreamsGroups);158+ pipeOutputAsync(spawned, stdioStreamsGroups, controller);159 cleanupOnExit(spawned, options, controller);160 161 spawned.kill = spawnedKill.bind(undefined, spawned.kill.bind(spawned), options, controller);162 spawned.all = makeAllStream(spawned, options);200 unmodified lines