Fix `maxListeners` warning when running multiple processes in parallel (#785)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 4b487ce · Browse files · 3 files·+116 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+116 added−2 removed
- tests:+89 added−2 removed
- other:+27 added−0 removed
Provenance
- Commit
d50c4cc- Tree
9d898a6- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
4b487ce
3 files changed+116 added−2 removed
modified:lib/stdio/async.js+27 added
1234553 unmodified lines59606162636465666768697071727374757677787980818283848586878889909192939495969798997 unmodified linesimport {addAbortListener} from 'node:events';import {createReadStream, createWriteStream} from 'node:fs';import {Buffer} from 'node:buffer';import {Readable, Writable} from 'node:stream';import {handleInput} from './handle.js';53 unmodified lines if (type === 'native') { return; }
setStandardStreamMaxListeners(value, controller);
if (direction === 'output') { pipeStreams([spawned.stdio[index]], value, controller); } else { inputStreamsGroups[index] = [...(inputStreamsGroups[index] ?? []), value]; }};
// Multiple processes might be piping from/to `process.std*` at the same time.// This is not necessarily an error and should not print a `maxListeners` warning.const setStandardStreamMaxListeners = (stream, {signal}) => { if (!isStandardStream(stream)) { return; }
const maxListeners = stream.getMaxListeners(); if (maxListeners === 0 || maxListeners === Number.POSITIVE_INFINITY) { return; }
stream.setMaxListeners(maxListeners + maxListenersIncrement); addAbortListener(signal, () => { stream.setMaxListeners(stream.getMaxListeners() - maxListenersIncrement); });};
// `source.pipe(destination)` adds at most 1 listener for each event.// We also listen for the stream's completion using `finished()`, which adds 1 more listener.// If `stdin` option is an array, the values might be combined with `merge-streams`.// That library also listens for `source` end, which adds 1 more listener.const maxListenersIncrement = 3;
// The stream error handling is performed by the piping logic above, which cannot be performed before process spawning.// If the process spawning fails (e.g. due to an invalid command), the streams need to be manually destroyed.// We need to create those streams before process spawning, in case their creation fails, e.g. when passing an invalid generator as argument.// Like this, an exception would be thrown, which would prevent spawning a process.7 unmodified linesadded:test/stdio/async.js+88 added
1+import {once, defaultMaxListeners} from 'node:events';2+import process from 'node:process';3+import {setTimeout} from 'node:timers/promises';4+import test from 'ava';5+import {execa} from '../../index.js';6+import {STANDARD_STREAMS} from '../helpers/stdio.js';7+import {foobarString} from '../helpers/input.js';8+import {setFixtureDir} from '../helpers/fixtures-dir.js';9+10+setFixtureDir();11+12+const getStandardStreamListeners = stream => Object.fromEntries(stream.eventNames().map(eventName => [eventName, stream.listeners(eventName)]));13+const getStandardStreamsListeners = () => STANDARD_STREAMS.map(stream => getStandardStreamListeners(stream));14+15+const getComplexStdio = isMultiple => ({16+ stdin: ['pipe', 'inherit', ...(isMultiple ? [0, process.stdin] : [])],17+ stdout: ['pipe', 'inherit', ...(isMultiple ? [1, process.stdout] : [])],18+ stderr: ['pipe', 'inherit', ...(isMultiple ? [2, process.stderr] : [])],19+});20+21+const testListenersCleanup = async (t, isMultiple) => {22+ const streamsPreviousListeners = getStandardStreamsListeners();23+ const childProcess = execa('empty.js', getComplexStdio(isMultiple));24+ t.notDeepEqual(getStandardStreamsListeners(), streamsPreviousListeners);25+ await Promise.all([26+ childProcess,27+ once(childProcess.stdin, 'unpipe'),28+ once(process.stdout, 'unpipe'),29+ once(process.stderr, 'unpipe'),30+ ]);31+32+ for (const [index, streamNewListeners] of Object.entries(getStandardStreamsListeners())) {33+ const defaultListeners = Object.fromEntries(Reflect.ownKeys(streamNewListeners).map(eventName => [eventName, []]));34+ t.deepEqual(streamNewListeners, {...defaultListeners, ...streamsPreviousListeners[index]});35+ }36+};37+38+test.serial('process.std* listeners are cleaned up on success with a single input', testListenersCleanup, false);39+test.serial('process.std* listeners are cleaned up on success with multiple inputs', testListenersCleanup, true);40+41+const processesCount = 100;42+43+test.serial('Can spawn many processes in parallel', async t => {44+ const results = await Promise.all(45+ Array.from({length: processesCount}, () => execa('noop.js', [foobarString])),46+ );47+ t.true(results.every(({stdout}) => stdout === foobarString));48+});49+50+const testMaxListeners = async (t, isMultiple, maxListenersCount) => {51+ let warning;52+ const captureWarning = warningArgument => {53+ warning = warningArgument;54+ };55+56+ process.on('warning', captureWarning);57+58+ for (const standardStream of STANDARD_STREAMS) {59+ standardStream.setMaxListeners(maxListenersCount);60+ }61+62+ try {63+ const results = await Promise.all(64+ Array.from({length: processesCount}, () => execa('empty.js', getComplexStdio(isMultiple))),65+ );66+ await setTimeout(0);67+ t.true(results.every(({exitCode}) => exitCode === 0));68+ t.is(warning, undefined);69+ } finally {70+ for (const standardStream of STANDARD_STREAMS) {71+ t.is(standardStream.getMaxListeners(), maxListenersCount);72+ standardStream.setMaxListeners(defaultMaxListeners);73+ }74+75+ process.off('warning', captureWarning);76+ }77+};78+79+test.serial('No warning with maxListeners 1 and ["pipe", "inherit"]', testMaxListeners, false, 1);80+test.serial('No warning with maxListeners default and ["pipe", "inherit"]', testMaxListeners, false, defaultMaxListeners);81+test.serial('No warning with maxListeners 100 and ["pipe", "inherit"]', testMaxListeners, false, 100);82+test.serial('No warning with maxListeners Infinity and ["pipe", "inherit"]', testMaxListeners, false, Number.POSITIVE_INFINITY);83+test.serial('No warning with maxListeners 0 and ["pipe", "inherit"]', testMaxListeners, false, 0);84+test.serial('No warning with maxListeners 1 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 1);85+test.serial('No warning with maxListeners default and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, defaultMaxListeners);86+test.serial('No warning with maxListeners 100 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 100);87+test.serial('No warning with maxListeners Infinity and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, Number.POSITIVE_INFINITY);88+test.serial('No warning with maxListeners 0 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 0);modified:test/stream.js+1 added-2 removed
5 unmodified lines6 import getStream from 'get-stream';7 import {execa, execaSync} from '../index.js';8 import {setFixtureDir} from './helpers/fixtures-dir.js';9 import {fullStdio, getStdio} from './helpers/stdio.js';10+import {foobarString} from './helpers/input.js';11 12 setFixtureDir();13 13-const foobarString = 'foobar';14-14 test.serial('result.all shows both `stdout` and `stderr` intermixed', async t => {15 const {all} = await execa('noop-132.js', {all: true});16 t.is(all, '132');17 });388 unmodified lines