Improve `buffer: false` behavior (#747)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 74f4cc5 · Browse files · 5 files·+66 added−47 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+66 added−47 removed
- tests:+46 added−24 removed
- other:+20 added−23 removed
Provenance
- Commit
a510995- Tree
4549766- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
74f4cc5
5 files changed+66 added−47 removed
modified:lib/stream.js+12 added-19 removed
12345673 unmodified lines1112131414151617181920212223242526272829301516171835 unmodified lines54555657745859606162634 unmodified lines686970717273747576777879808182838481 unmodified lines1661671681691761701711721739 unmodified linesimport {once} from 'node:events';import {finished} from 'node:stream/promises';import {setImmediate} from 'node:timers/promises';import getStream, {getStreamAsArrayBuffer, getStreamAsArray} from 'get-stream';import mergeStreams from '@sindresorhus/merge-streams';import {throwOnTimeout, cleanupOnExit} from './kill.js';import {STANDARD_STREAMS} from './stdio/native.js';3 unmodified linesexport const makeAllStream = ({stdout, stderr}, {all}) => all && (stdout || stderr) ? mergeStreams([stdout, stderr].filter(Boolean)) : undefined;
// `childProcess.stdout|stderr` do not end until they have been consumed by `childProcess.all`.// `childProcess.all` does not end until `childProcess.stdout|stderr` have ended.// That's a good thing, since it ensures those streams are fully read and destroyed, even on errors.// However, this creates a deadlock if `childProcess.all` is not being read.// Doing so prevents the process from exiting, even when it failed.// It also prevents those streams from being properly destroyed.// This can only happen when:// - `all` is `true`// - `buffer` is `false`// - `childProcess.all` is not read by the user// Therefore, we forcefully resume `childProcess.all` flow on errors.const resumeAll = all => { if (all?.readableFlowing === null) { all.resume(); }};
// On failure, `result.stdout|stderr|all` should contain the currently buffered stream// They are automatically closed and flushed by Node.js when the child process exits// We guarantee this by calling `childProcess.kill()`// When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve35 unmodified lines return; }
if (!buffer) { return finished(stream); await Promise.all([finished(stream), resumeStream(stream)]); return; }
if (stream.readableObjectMode) { return getStreamAsArray(stream, {maxBuffer});4 unmodified lines : await getStream(stream, {maxBuffer}); return applyEncoding(contents, encoding);};
// When using `buffer: false`, users need to read `childProcess.stdout|stderr|all` right away// See https://github.com/sindresorhus/execa/issues/730 and https://github.com/sindresorhus/execa/pull/729#discussion_r1465496310const resumeStream = async stream => { await setImmediate(); if (stream.readableFlowing === null) { stream.resume(); }};
const applyEncoding = (contents, encoding) => encoding === 'buffer' ? new Uint8Array(contents) : contents;
// Retrieve streams created by the `std*` optionsconst getCustomStreams = stdioStreamsGroups => stdioStreamsGroups.flat().filter(({type}) => type !== 'native');81 unmodified lines ...throwOnTimeout(timeout, context, controller), ]); } catch (error) { spawned.kill(); resumeAll(spawned.all); const results = await Promise.all([ error, waitForFailedProcess(processSpawnPromise, processErrorPromise, processExitPromise), Promise.all(stdioPromises.map(stdioPromise => getBufferedData(stdioPromise, encoding))),9 unmodified linesadded:test/fixtures/noop-fd-ipc.js+6 added
123456#!/usr/bin/env nodeimport process from 'node:process';import {writeSync} from 'node:fs';
writeSync(Number(process.argv[2]), process.argv[3] || 'foobar');process.send('');modified:test/stream.js+40 added-24 removed
1 import {Buffer} from 'node:buffer';2 import {once} from 'node:events';3-import process from 'node:process';3 import {getDefaultHighWaterMark} from 'node:stream';4 import {setTimeout, setImmediate} from 'node:timers/promises';5 import test from 'ava';6 import getStream from 'get-stream';76 unmodified lines83 const [output] = await once(stream, 'data');84 return output.toString();85 };86 87+const testLateStream = async (t, index, all) => {88+ const subprocess = execa('noop-fd-ipc.js', [`${index}`, foobarString], {...getStdio(4, 'ipc', 4), buffer: false, all});89+ await once(subprocess, 'message');90+ await setImmediate();91+ const [output, allOutput] = await Promise.all([92+ getStream(subprocess.stdio[index]),93+ all ? getStream(subprocess.all) : undefined,94+ subprocess,95+ ]);96+97+ t.is(output, '');98+99+ if (all) {100+ t.is(allOutput, '');101+ }102+};103+104+test('Lacks some data when stdout is read too late `buffer` set to `false`', testLateStream, 1, false);105+test('Lacks some data when stderr is read too late `buffer` set to `false`', testLateStream, 2, false);106+test('Lacks some data when stdio[*] is read too late `buffer` set to `false`', testLateStream, 3, false);107+test('Lacks some data when all is read too late `buffer` set to `false`', testLateStream, 1, true);108+109 // eslint-disable-next-line max-params110 const testIterationBuffer = async (t, index, buffer, useDataEvents, all) => {111 const subprocess = execa('noop-fd.js', [`${index}`, foobarString], {...fullStdio, buffer, all});112 const getOutput = useDataEvents ? getFirstDataEvent : getStream;175 unmodified lines288 test('Process buffers stdout, which does not prevent exit if ignored', testBufferIgnore, 1, false);289 test('Process buffers stderr, which does not prevent exit if ignored', testBufferIgnore, 2, false);290 test('Process buffers all, which does not prevent exit if ignored', testBufferIgnore, 1, true);291 271-// This specific behavior does not happen on Windows.272-// Also, on macOS, it randomly happens, which would make those tests randomly fail.273-if (process.platform === 'linux') {274- const testBufferNotRead = async (t, index, all) => {275- const subprocess = execa('max-buffer.js', [`${index}`], {...fullStdio, buffer: false, all, timeout: 1e3});276- const {timedOut} = await t.throwsAsync(subprocess);277- t.true(timedOut);292+const testBufferNotRead = async (t, index, all) => {293+ const subprocess = execa('max-buffer.js', [`${index}`], {...fullStdio, buffer: false, all});294+ await t.notThrowsAsync(subprocess);295+};278- };296 280- test('Process buffers stdout, which prevents exit if not read and buffer is false', testBufferNotRead, 1, false);281- test('Process buffers stderr, which prevents exit if not read and buffer is false', testBufferNotRead, 2, false);282- test('Process buffers stdio[*], which prevents exit if not read and buffer is false', testBufferNotRead, 3, false);283- test('Process buffers all, which prevents exit if not read and buffer is false', testBufferNotRead, 1, true);297+test('Process buffers stdout, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, false);298+test('Process buffers stderr, which does not prevent exit if not read and buffer is false', testBufferNotRead, 2, false);299+test('Process buffers stdio[*], which does not prevent exit if not read and buffer is false', testBufferNotRead, 3, false);300+test('Process buffers all, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, true);301 285- const testBufferRead = async (t, index, all) => {286- const subprocess = execa('max-buffer.js', [`${index}`], {...fullStdio, buffer: false, all, timeout: 1e4});287- const stream = all ? subprocess.all : subprocess.stdio[index];288- stream.resume();289- await t.notThrowsAsync(subprocess);290- };302+const testBufferRead = async (t, index, all) => {303+ const subprocess = execa('max-buffer.js', [`${index}`], {...fullStdio, buffer: false, all});304+ const stream = all ? subprocess.all : subprocess.stdio[index];305+ stream.resume();306+ await t.notThrowsAsync(subprocess);307+};308 292- test.serial('Process buffers stdout, which does not prevent exit if read and buffer is false', testBufferRead, 1, false);293- test.serial('Process buffers stderr, which does not prevent exit if read and buffer is false', testBufferRead, 2, false);294- test.serial('Process buffers stdio[*], which does not prevent exit if read and buffer is false', testBufferRead, 3, false);295- test.serial('Process buffers all, which does not prevent exit if read and buffer is false', testBufferRead, 1, true);296-}309+test('Process buffers stdout, which does not prevent exit if read and buffer is false', testBufferRead, 1, false);310+test('Process buffers stderr, which does not prevent exit if read and buffer is false', testBufferRead, 2, false);311+test('Process buffers stdio[*], which does not prevent exit if read and buffer is false', testBufferRead, 3, false);312+test('Process buffers all, which does not prevent exit if read and buffer is false', testBufferRead, 1, true);313 314 const testStreamDestroy = async (t, index) => {315 const childProcess = execa('forever.js', fullStdio);316 const error = new Error('test');80 unmodified linesmodified:index.d.ts+4 added-2 removed
536 unmodified lines537 */538 readonly cleanup?: IfAsync<IsSync, boolean>;539 540 /**541- Buffer the output from the spawned process. When set to `false`, you must read the output of `stdout` and `stderr` (or `all` if the `all` option is `true`). Otherwise the returned promise will not be resolved/rejected.541+ Whether to return the child process' output using the `result.stdout`, `result.stderr`, `result.all` and `result.stdio` properties.542 543- If the spawned process fails, `error.stdout`, `error.stderr`, and `error.all` will contain the buffered data.543+ On failure, the `error.stdout`, `error.stderr`, `error.all` and `error.stdio` properties are used instead.544 545+ When `buffer` is `false`, the output can still be read using the `childProcess.stdout`, `childProcess.stderr`, `childProcess.stdio` and `childProcess.all` streams. If the output is read, this should be done right away to avoid missing any data.546+547 @default true548 */549 readonly buffer?: IfAsync<IsSync, boolean>;550 754 unmodified linesmodified:readme.md+4 added-2 removed
532 unmodified lines533 534 Type: `boolean`\535 Default: `true`536 537-Buffer the output from the spawned process. When set to `false`, you must read the output of [`stdout`](#stdout-1) and [`stderr`](#stderr-1) (or [`all`](#all) if the [`all`](#all-2) option is `true`). Otherwise the returned promise will not be resolved/rejected.537+Whether to return the child process' output using the [`result.stdout`](#stdout), [`result.stderr`](#stderr), [`result.all`](#all-1) and [`result.stdio`](#stdio) properties.538 539-If the spawned process fails, [`error.stdout`](#stdout), [`error.stderr`](#stderr), [`error.all`](#all) and [`error.stdio`](#stdio) will contain the buffered data.539+On failure, the [`error.stdout`](#stdout), [`error.stderr`](#stderr), [`error.all`](#all-1) and [`error.stdio`](#stdio) properties are used instead.540 541+When `buffer` is `false`, the output can still be read using the [`childProcess.stdout`](#stdout-1), [`childProcess.stderr`](#stderr-1), [`childProcess.stdio`](https://nodejs.org/api/child_process.html#subprocessstdio) and [`childProcess.all`](#all) streams. If the output is read, this should be done right away to avoid missing any data.542+543 #### input544 545 Type: `string | Uint8Array | stream.Readable`546 410 unmodified lines