Skip to content
Myr

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

10 files+169 added−78 removed

modified:lib/stdio/async.js+8 added-9 removed
modified:lib/stdio/generator.js+5 added-4 removed
1import {generatorsToTransform} from './transform.js';2import {getEncodingStartGenerator} from './encoding.js';3import {getLinesGenerator} from './lines.js';4import {pipeStreams} from './pipeline.js';5import {isGeneratorOptions, isAsyncGenerator} from './type.js';5import {isBinary, pipeStreams} from './utils.js';6import {isBinary} from './utils.js';78export const normalizeGenerators = stdioStreams => {9 const nonGenerators = stdioStreams.filter(({type}) => type !== 'generator');10 const generators = stdioStreams.filter(({type}) => type === 'generator');
100 unmodified lines
111 }112};113114// `childProcess.stdin|stdout|stderr|stdio` is directly mutated.114export const pipeGenerator = (spawned, {value, direction, index}) => {115export 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 }121122 const streamProperty = PROCESS_STREAM_PROPERTIES[index];123 if (streamProperty !== undefined) {
7 unmodified lines
added:lib/stdio/pipeline.js+59 added
modified:lib/stdio/utils.js-14 removed
modified:lib/stream.js+7 added-25 removed
81 unmodified lines
82};8384const applyEncoding = (contents, encoding) => encoding === 'buffer' ? new Uint8Array(contents) : contents;8586// Retrieve streams created by the `std*` options87const 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.89const waitForCustomStreamsEnd = stdioStreamsGroups => stdioStreamsGroups.flat()90 .filter(({type, value}) => type !== 'native' && !isStandardStream(value))91 .map(({value}) => finished(value, {cleanup: true}));9289// 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.97const waitForCustomStreamsEnd = customStreams => customStreams98 .filter(({value, type, direction}) => shouldWaitForCustomStream(value, type, direction))99 .map(({value}) => finished(value));100101const throwOnCustomStreamsError = customStreams => customStreams102 .filter(({value, type, direction}) => !shouldWaitForCustomStream(value, type, direction))103 .map(({value}) => throwOnStreamError(value));104105const shouldWaitForCustomStream = (value, type, direction) => (type === 'fileUrl' || type === 'filePath')106 || (direction === 'output' && !isStandardStream(value));10793const throwIfStreamError = stream => stream === null ? [] : [throwOnStreamError(stream)];9495const throwOnStreamError = async stream => {96 const [error] = await once(stream, 'error');
39 unmodified lines
136 const processSpawnPromise = pEvent(spawned, 'spawn', controller);137 const processErrorPromise = pEvent(spawned, 'error', controller);138 const processExitPromise = pEvent(spawned, 'exit', controller);139155 const customStreams = getCustomStreams(stdioStreamsGroups);156140 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);143144 try {145 return await Promise.race([146 Promise.all([
3 unmodified lines
150 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 lines
modified:test/stdio/file-path.js+11 added-1 removed
139 unmodified lines
140test('stdio[*] must be an object when it is a file path string - sync', testFilePathObject, 3, execaSync);141142const 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 lines
200test('input Uint8Array and stdin can be both set - sync', testMultipleInputs, [0, 'binary'], execaSync);201test('stdin and inputFile can be both set - sync', testMultipleInputs, [0, 'inputFile'], execaSync);202test('input String, stdin and inputFile can be all set - sync', testMultipleInputs, ['inputFile', 0, 'string'], execaSync);203test('input Uint8Array, stdin and inputFile can be all set - sync', testMultipleInputs, ['inputFile', 0, 'binary'], execaSync);204205const 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};211212test('Passing an input file path when process exits does not make promise hang', testInputFileHanging, getAbsolutePath);213test('Passing an input file URL when process exits does not make promise hang', testInputFileHanging, pathToFileURL);
modified:test/stdio/iterable.js+7 added-23 removed
1import {once} from 'node:events';2import {setTimeout, setImmediate} from 'node:timers/promises';2import {setImmediate} from 'node:timers/promises';3import test from 'ava';4import {execa, execaSync} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {getStdio} from '../helpers/stdio.js';7import {foobarObject, foobarObjectString} from '../helpers/input.js';8import {serializeGenerator} from '../helpers/generator.js';8import {serializeGenerator, infiniteGenerator} from '../helpers/generator.js';910const stringArray = ['foo', 'bar'];1112const stringGenerator = function * () {
92 unmodified lines
105test('stderr option cannot be an iterable', testNoIterableOutput, stringGenerator(), 2, execa);106test('stdout option cannot be an iterable - sync', testNoIterableOutput, stringGenerator(), 1, execaSync);107test('stderr option cannot be an iterable - sync', testNoIterableOutput, stringGenerator(), 2, execaSync);108109const infiniteGenerator = () => {110 const controller = new AbortController();111112 const generator = async function * () {113 yield 'foo';114 await setTimeout(1e7, undefined, {signal: controller.signal});115 };116117 return {iterable: generator(), abort: controller.abort.bind(controller)};118};119109test('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});116117const testMultipleIterable = async (t, index) => {118 const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, [stringGenerator(), asyncGenerator()]));
5 unmodified lines
modified:test/stdio/node-stream.js+62 added-1 removed
115 unmodified lines
116test('stdout can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 1);117test('stderr can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 2);118test('stdio[*] can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 3);119120test('Wait for custom streams destroy on process errors', async t => {120test('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 lines
141};142143test('Input streams are canceled on early process exit', testStreamEarlyExit, noopReadable(), 'stdin');144test('Output streams are canceled on early process exit', testStreamEarlyExit, noopWritable(), 'stdout');145146test('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});154155const 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};162163test('Handles input streams aborts', testStreamAbort, noopReadable(), 'stdin');164test('Handles output streams aborts', testStreamAbort, noopWritable(), 'stdout');165166const 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};174175test('Handles input streams errors', testStreamError, noopReadable(), 'stdin');176test('Handles output streams errors', testStreamError, noopWritable(), 'stdout');177178test('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});185186const 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};192193test('Handles childProcess.stdin aborts', testChildStreamAbort, noopReadable(), 'stdin');194test('Handles childProcess.stdout aborts', testChildStreamAbort, noopWritable(), 'stdout');195196const 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};203204test('Handles childProcess.stdin errors', testChildStreamError, noopReadable(), 'stdin');205test('Handles childProcess.stdout errors', testChildStreamError, noopWritable(), 'stdout');
modified:test/stdio/web-stream.js+9 added
85 unmodified lines
86};8788test('stdin option handles errors in ReadableStream', testReadableStreamError, 0);89test('stdio[*] option handles errors in ReadableStream', testReadableStreamError, 3);9091test('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 lines
154155 const controller = new AbortController();156 setMaxListeners(Number.POSITIVE_INFINITY, controller.signal);157158 pipeOutputAsync(spawned, stdioStreamsGroups);158 pipeOutputAsync(spawned, stdioStreamsGroups, controller);159 cleanupOnExit(spawned, options, controller);160161 spawned.kill = spawnedKill.bind(undefined, spawned.kill.bind(spawned), options, controller);162 spawned.all = makeAllStream(spawned, options);
200 unmodified lines