Make `maxBuffer` option terminate subprocess gracefully (#959)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 507b09c · Browse files · 9 files·+63 added−107 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+63 added−107 removed
- tests:+13 added−18 removed
- other:+50 added−89 removed
Provenance
- Commit
bdda475- Tree
ecf8c5a- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
507b09c
9 files changed+63 added−107 removed
modified:lib/convert/loop.js+18 added-41 removed
123456789101112131314151617187 unmodified lines262728292930313132333435363736383938404142434443454647464849505152535418 unmodified lines7374757673777879807781828384858687848889909188899091929394959697989910010110210310410510610710810911011111211311411511611711892939495import {on} from 'node:events';import {getEncodingTransformGenerator} from '../stdio/encoding-transform.js';import {getSplitLinesGenerator} from '../stdio/split.js';import {transformChunkSync, finalChunksSync} from '../stdio/transform.js';
// Iterate over lines of `subprocess.stdout`, used by `subprocess.readable|duplex|iterable()`export const iterateOnSubprocessStream = ({subprocessStdout, subprocess, binary, shouldEncode, encoding, preserveNewlines}) => { const controller = new AbortController(); stopReadingOnExit(subprocess, controller); return iterateOnStream({ stream: subprocessStdout, controller, binary, shouldEncode: shouldEncode && !subprocessStdout.readableObjectMode, shouldEncode: !subprocessStdout.readableObjectMode && shouldEncode, encoding, shouldSplit: !subprocessStdout.readableObjectMode, preserveNewlines, });7 unmodified lines }};
// Iterate over lines of `subprocess.stdout`, used by `result.stdout` + `lines: true` optionexport const iterateForResult = ({stream, onStreamEnd, lines, encoding, stripFinalNewline}) => {export const iterateForResult = ({stream, onStreamEnd, lines, encoding, stripFinalNewline, allMixed}) => { const controller = new AbortController(); stopReadingOnStreamEnd(controller, onStreamEnd); stopReadingOnStreamEnd(onStreamEnd, controller, stream); const objectMode = stream.readableObjectMode && !allMixed; return iterateOnStream({ stream, controller, binary: encoding === 'buffer', shouldEncode: true, shouldEncode: !objectMode, encoding, shouldSplit: lines, shouldSplit: !objectMode && lines, preserveNewlines: !stripFinalNewline, });};
const stopReadingOnStreamEnd = async (controller, onStreamEnd) => {const stopReadingOnStreamEnd = async (onStreamEnd, controller, stream) => { try { await onStreamEnd; } catch {} finally { } catch { stream.destroy(); } finally { controller.abort(); }};
18 unmodified lines// Note: this option does not exist on Node 18, but this is ok since the logic works without it. It just consumes more memory.const HIGH_WATER_MARK = DEFAULT_OBJECT_HIGH_WATER_MARK;
const iterateOnData = async function * ({onStdoutChunk, controller, binary, shouldEncode, encoding, shouldSplit, preserveNewlines}) { const {encodeChunk, encodeChunkFinal, splitLines, splitLinesFinal} = getTransforms({binary, shouldEncode, encoding, shouldSplit, preserveNewlines}); const generators = getGenerators({binary, shouldEncode, encoding, shouldSplit, preserveNewlines});
try { for await (const [chunk] of onStdoutChunk) { yield * handleChunk(encodeChunk, splitLines, chunk); yield * transformChunkSync(chunk, generators, 0); } } catch (error) { if (!controller.signal.aborted) { throw error; } } finally { yield * handleFinalChunks(encodeChunkFinal, splitLines, splitLinesFinal); yield * finalChunksSync(generators); }};
const getTransforms = ({binary, shouldEncode, encoding, shouldSplit, preserveNewlines}) => { const { transform: encodeChunk = identityGenerator, final: encodeChunkFinal = noopGenerator, } = getEncodingTransformGenerator(binary, encoding, !shouldEncode) ?? {}; const { transform: splitLines = identityGenerator, final: splitLinesFinal = noopGenerator, } = getSplitLinesGenerator(binary, preserveNewlines, !shouldSplit, {}) ?? {}; return {encodeChunk, encodeChunkFinal, splitLines, splitLinesFinal};};
const identityGenerator = function * (chunk) { yield chunk;};
const noopGenerator = function * () {};
const handleChunk = function * (encodeChunk, splitLines, chunk) { for (const encodedChunk of encodeChunk(chunk)) { yield * splitLines(encodedChunk); }};
const handleFinalChunks = function * (encodeChunkFinal, splitLines, splitLinesFinal) { for (const encodedChunk of encodeChunkFinal()) { yield * splitLines(encodedChunk); }
yield * splitLinesFinal();};const getGenerators = ({binary, shouldEncode, encoding, shouldSplit, preserveNewlines}) => [ getEncodingTransformGenerator(binary, encoding, !shouldEncode), getSplitLinesGenerator(binary, preserveNewlines, !shouldSplit, {}),].filter(Boolean);modified:lib/stdio/transform.js+2 added-2 removed
102 unmodified lines103 ...chunks.flatMap(chunk => [...transformChunkSync(chunk, generators, 0)]),104 ...finalChunksSync(generators),105 ];106 107-const transformChunkSync = function * (chunk, generators, index) {107+export const transformChunkSync = function * (chunk, generators, index) {108 if (index === generators.length) {109 yield chunk;110 return;111 }3 unmodified lines115 yield * transformChunkSync(transformedChunk, generators, index + 1);116 }117 };118 119-const finalChunksSync = function * (generators) {119+export const finalChunksSync = function * (generators) {120 for (const [index, {final}] of Object.entries(generators)) {121 yield * generatorFinalChunksSync(final, Number(index), generators);122 }123 };14 unmodified linesmodified:lib/stream/all.js-1 removed
7 unmodified lines891011121213141514 unmodified lines7 unmodified lines
// Read the contents of `subprocess.all` and|or wait for its completionexport const waitForAllStream = ({subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline, streamInfo}) => waitForSubprocessStream({ stream: subprocess.all, subprocess, fdNumber: 1, encoding, buffer, maxBuffer: maxBuffer * 2,14 unmodified linesmodified:lib/stream/resolve.js+1 added-1 removed
53 unmodified lines54 };55 56 // Read the contents of `subprocess.std*` and|or wait for its completion57 const waitForSubprocessStreams = ({subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline, streamInfo}) =>58- subprocess.stdio.map((stream, fdNumber) => waitForSubprocessStream({stream, subprocess, fdNumber, encoding, buffer, maxBuffer, lines, allMixed: false, stripFinalNewline, streamInfo}));58+ subprocess.stdio.map((stream, fdNumber) => waitForSubprocessStream({stream, fdNumber, encoding, buffer, maxBuffer, lines, allMixed: false, stripFinalNewline, streamInfo}));59 60 // Transforms replace `subprocess.std*`, which means they are not exposed to users.61 // However, we still want to wait for their completion.62 const waitForOriginalStreams = (originalStreams, subprocess, streamInfo) =>23 unmodified linesmodified:lib/stream/subprocess.js+28 added-43 removed
1 import {setImmediate} from 'node:timers/promises';2 import getStream, {getStreamAsArrayBuffer, getStreamAsArray, MaxBufferError} from 'get-stream';3 import {iterateForResult} from '../convert/loop.js';4 import {isArrayBuffer} from '../stdio/uint-array.js';5-import {waitForStream, handleStreamError, isInputFileDescriptor} from './wait.js';5+import {waitForStream, isInputFileDescriptor} from './wait.js';6 7-export const waitForSubprocessStream = async ({stream, subprocess, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, streamInfo}) => {7+export const waitForSubprocessStream = async ({stream, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, streamInfo}) => {8 if (!stream) {9 return;10 }11 12+ const onStreamEnd = waitForStream(stream, fdNumber, streamInfo);13+ const [output] = await Promise.all([14+ waitForDefinedStream({stream, onStreamEnd, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, streamInfo}),15+ onStreamEnd,16+ ]);17+ return output;18+};19+20+const waitForDefinedStream = async ({stream, onStreamEnd, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, streamInfo}) => {21 if (isInputFileDescriptor(streamInfo, fdNumber)) {13- await waitForStream(stream, fdNumber, streamInfo);22 return;23 }24 25 if (!buffer) {18- await Promise.all([19- waitForStream(stream, fdNumber, streamInfo),20- resumeStream(stream),21- ]);26+ await resumeStream(stream);27 return;28 }29 25- try {26- return await getAnyStream({stream, fdNumber, encoding, maxBuffer, lines, allMixed, stripFinalNewline, streamInfo});27- } catch (error) {28- if (error instanceof MaxBufferError) {29- subprocess.kill();30- }31-32- handleStreamError(error, fdNumber, streamInfo);33- return handleBufferedData(error);34- }30+ const iterable = iterateForResult({stream, onStreamEnd, lines, encoding, stripFinalNewline, allMixed});31+ return getStreamContents({stream, iterable, encoding, maxBuffer, lines});32 };33 34 // When using `buffer: false`, users need to read `subprocess.stdout|stderr|all` right away35 // See https://github.com/sindresorhus/execa/issues/730 and https://github.com/sindresorhus/execa/pull/729#discussion_r14654963103 unmodified lines39 stream.resume();40 }41 };42 46-const getAnyStream = async ({stream, fdNumber, encoding, maxBuffer, lines, allMixed, stripFinalNewline, streamInfo}) => {47- if (allMixed) {48- const iterable = getIterable({stream, fdNumber, encoding, lines, stripFinalNewline, streamInfo});49- return getStreamAsArray(iterable, {maxBuffer});50- }43+const getStreamContents = async ({stream, iterable, encoding, maxBuffer, lines}) => {44+ try {45+ if (stream.readableObjectMode || lines) {46+ return await getStreamAsArray(iterable, {maxBuffer});47+ }48 52- if (stream.readableObjectMode) {53- return getStreamAsArray(stream, {maxBuffer});54- }49+ if (encoding === 'buffer') {50+ return new Uint8Array(await getStreamAsArrayBuffer(iterable, {maxBuffer}));51+ }52 56- if (encoding === 'buffer') {57- return new Uint8Array(await getStreamAsArrayBuffer(stream, {maxBuffer}));58- }53+ return await getStream(iterable, {maxBuffer});54+ } catch (error) {55+ if (error instanceof MaxBufferError) {56+ stream.destroy();57+ }58 60- if (lines) {61- const iterable = getIterable({stream, fdNumber, encoding, lines, stripFinalNewline, streamInfo});62- return getStreamAsArray(iterable, {maxBuffer});59+ throw error;60 }64-65- if (encoding !== 'utf8') {66- const iterable = getIterable({stream, fdNumber, encoding, lines, stripFinalNewline, streamInfo});67- return getStream(iterable, {maxBuffer});68- }69-70- return getStream(stream, {maxBuffer});61 };62 73-const getIterable = ({stream, fdNumber, encoding, lines, stripFinalNewline, streamInfo}) => {74- const onStreamEnd = waitForStream(stream, fdNumber, streamInfo);75- return iterateForResult({stream, onStreamEnd, lines, encoding, stripFinalNewline});76-};77-63 // On failure, `result.stdout|stderr|all` should contain the currently buffered stream64 // They are automatically closed and flushed by Node.js when the subprocess exits65 // When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve66 export const getBufferedData = async streamPromise => {11 unmodified linesmodified:lib/stream/wait.js+1 added-1 removed
57 unmodified lines58 // When one stream errors, the error is propagated to the other streams on the same file descriptor.59 // Those other streams might have a different direction due to the above.60 // When this happens, the direction of both the initial stream and the others should then be taken into account.61 // Therefore, we keep track of whether a stream error is currently propagating.62-export const handleStreamError = (error, fdNumber, streamInfo, isSameDirection) => {62+const handleStreamError = (error, fdNumber, streamInfo, isSameDirection) => {63 if (!shouldIgnoreStreamError(error, fdNumber, streamInfo, isSameDirection)) {64 throw error;65 }66 };30 unmodified linesmodified:test/exit/kill.js-9 removed
23 unmodified lines24 };25 26 const spawnNoKillableSimple = options => execa('forever.js', {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, ...options});27 28-const spawnNoKillableOutput = options => execa('noop-forever.js', ['.'], {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, ...options});29-28 test('kill("SIGKILL") should terminate cleanly', async t => {29 const {subprocess} = await spawnNoKillable();30 31 subprocess.kill('SIGKILL');80 unmodified lines112 t.is(signal, 'SIGKILL');113 t.true(timedOut);114 });115 118- test('`forceKillAfterDelay` works with the "maxBuffer" option', async t => {119- const subprocess = spawnNoKillableOutput({maxBuffer: 1});120- const {isTerminated, signal} = await t.throwsAsync(subprocess);121- t.true(isTerminated);122- t.is(signal, 'SIGKILL');123- });124-116 test.serial('Can call `.kill()` with `forceKillAfterDelay` many times without triggering the maxListeners warning', async t => {117 const checkMaxListeners = assertMaxListeners(t);118 119 const subprocess = spawnNoKillableSimple();184 unmodified linesmodified:test/stream/max-buffer.js+10 added-6 removed
17 unmodified lines18 test('maxBuffer does not affect stderr if too high', testMaxBufferSuccess, 2, false);19 test('maxBuffer does not affect stdio[*] if too high', testMaxBufferSuccess, 3, false);20 test('maxBuffer does not affect all if too high', testMaxBufferSuccess, 1, true);21 22-test('maxBuffer uses killSignal', async t => {23- const {isTerminated, signal} = await t.throwsAsync(24- execa('noop-forever.js', ['.'.repeat(maxBuffer + 1)], {maxBuffer, killSignal: 'SIGINT'}),22+const testGracefulExit = async (t, fixtureName, expectedExitCode) => {23+ const {exitCode, signal, stdout} = await t.throwsAsync(24+ execa(fixtureName, ['1', '.'.repeat(maxBuffer + 1)], {maxBuffer}),25 {message: maxBufferMessage},26 );27- t.true(isTerminated);28- t.is(signal, 'SIGINT');29-});27+ t.is(exitCode, expectedExitCode);28+ t.is(signal, undefined);29+ t.is(stdout, '.'.repeat(maxBuffer));30+};31 32+test('maxBuffer terminates stream gracefully, more writes', testGracefulExit, 'noop-repeat.js', 1);33+test('maxBuffer terminates stream gracefully, no more writes', testGracefulExit, 'noop-fd.js', 0);34+35 const testMaxBufferLimit = async (t, fdNumber, all) => {36 const length = all ? maxBuffer * 2 : maxBuffer;37 const result = await t.throwsAsync(38 execa('max-buffer.js', [`${fdNumber}`, `${length + 1}`], {...fullStdio, maxBuffer, all}),85 unmodified linesmodified:test/stream/subprocess.js+3 added-3 removed
99 unmodified lines100 t.is(error.cause, cause);101 assertStreamOutputError(t, fdNumber, error);102 };103 104-test('Errors on stdout should not make the subprocess exit', testStreamOutputError, 1);105-test('Errors on stderr should not make the subprocess exit', testStreamOutputError, 2);106-test('Errors on output stdio[*] should not make the subprocess exit', testStreamOutputError, 3);104+test('Errors on stdout should make the subprocess exit', testStreamOutputError, 1);105+test('Errors on stderr should make the subprocess exit', testStreamOutputError, 2);106+test('Errors on output stdio[*] should make the subprocess exit', testStreamOutputError, 3);107 108 const testWaitOnStreamEnd = async (t, fdNumber) => {109 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], fullStdio);110 await setTimeout(100);7 unmodified lines