Skip to content
Myr

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

9 files+63 added−107 removed

modified:lib/convert/loop.js+18 added-41 removed
modified:lib/stdio/transform.js+2 added-2 removed
102 unmodified lines
103 ...chunks.flatMap(chunk => [...transformChunkSync(chunk, generators, 0)]),104 ...finalChunksSync(generators),105];106107const transformChunkSync = function * (chunk, generators, index) {107export const transformChunkSync = function * (chunk, generators, index) {108 if (index === generators.length) {109 yield chunk;110 return;111 }
3 unmodified lines
115 yield * transformChunkSync(transformedChunk, generators, index + 1);116 }117};118119const finalChunksSync = function * (generators) {119export const finalChunksSync = function * (generators) {120 for (const [index, {final}] of Object.entries(generators)) {121 yield * generatorFinalChunksSync(final, Number(index), generators);122 }123};
14 unmodified lines
modified:lib/stream/all.js-1 removed
modified:lib/stream/resolve.js+1 added-1 removed
53 unmodified lines
54};5556// Read the contents of `subprocess.std*` and|or wait for its completion57const 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}));5960// Transforms replace `subprocess.std*`, which means they are not exposed to users.61// However, we still want to wait for their completion.62const waitForOriginalStreams = (originalStreams, subprocess, streamInfo) =>
23 unmodified lines
modified:lib/stream/subprocess.js+28 added-43 removed
1import {setImmediate} from 'node:timers/promises';2import getStream, {getStreamAsArrayBuffer, getStreamAsArray, MaxBufferError} from 'get-stream';3import {iterateForResult} from '../convert/loop.js';4import {isArrayBuffer} from '../stdio/uint-array.js';5import {waitForStream, handleStreamError, isInputFileDescriptor} from './wait.js';5import {waitForStream, isInputFileDescriptor} from './wait.js';67export const waitForSubprocessStream = async ({stream, subprocess, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, streamInfo}) => {7export const waitForSubprocessStream = async ({stream, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, streamInfo}) => {8 if (!stream) {9 return;10 }1112 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};1920const 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 }2425 if (!buffer) {18 await Promise.all([19 waitForStream(stream, fdNumber, streamInfo),20 resumeStream(stream),21 ]);26 await resumeStream(stream);27 return;28 }2925 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 }3132 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};3334// 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_r1465496310
3 unmodified lines
39 stream.resume();40 }41};4246const 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 }43const getStreamContents = async ({stream, iterable, encoding, maxBuffer, lines}) => {44 try {45 if (stream.readableObjectMode || lines) {46 return await getStreamAsArray(iterable, {maxBuffer});47 }4852 if (stream.readableObjectMode) {53 return getStreamAsArray(stream, {maxBuffer});54 }49 if (encoding === 'buffer') {50 return new Uint8Array(await getStreamAsArrayBuffer(iterable, {maxBuffer}));51 }5256 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 }5860 if (lines) {61 const iterable = getIterable({stream, fdNumber, encoding, lines, stripFinalNewline, streamInfo});62 return getStreamAsArray(iterable, {maxBuffer});59 throw error;60 }6465 if (encoding !== 'utf8') {66 const iterable = getIterable({stream, fdNumber, encoding, lines, stripFinalNewline, streamInfo});67 return getStream(iterable, {maxBuffer});68 }6970 return getStream(stream, {maxBuffer});61};6273const getIterable = ({stream, fdNumber, encoding, lines, stripFinalNewline, streamInfo}) => {74 const onStreamEnd = waitForStream(stream, fdNumber, streamInfo);75 return iterateForResult({stream, onStreamEnd, lines, encoding, stripFinalNewline});76};7763// 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 retrieve66export const getBufferedData = async streamPromise => {
11 unmodified lines
modified:lib/stream/wait.js+1 added-1 removed
57 unmodified lines
58// 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.62export const handleStreamError = (error, fdNumber, streamInfo, isSameDirection) => {62const handleStreamError = (error, fdNumber, streamInfo, isSameDirection) => {63 if (!shouldIgnoreStreamError(error, fdNumber, streamInfo, isSameDirection)) {64 throw error;65 }66};
30 unmodified lines
modified:test/exit/kill.js-9 removed
23 unmodified lines
24};2526const spawnNoKillableSimple = options => execa('forever.js', {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, ...options});2728const spawnNoKillableOutput = options => execa('noop-forever.js', ['.'], {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, ...options});2928test('kill("SIGKILL") should terminate cleanly', async t => {29 const {subprocess} = await spawnNoKillable();3031 subprocess.kill('SIGKILL');
80 unmodified lines
112 t.is(signal, 'SIGKILL');113 t.true(timedOut);114 });115118 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 });124116 test.serial('Can call `.kill()` with `forceKillAfterDelay` many times without triggering the maxListeners warning', async t => {117 const checkMaxListeners = assertMaxListeners(t);118119 const subprocess = spawnNoKillableSimple();
184 unmodified lines
modified:test/stream/max-buffer.js+10 added-6 removed
17 unmodified lines
18test('maxBuffer does not affect stderr if too high', testMaxBufferSuccess, 2, false);19test('maxBuffer does not affect stdio[*] if too high', testMaxBufferSuccess, 3, false);20test('maxBuffer does not affect all if too high', testMaxBufferSuccess, 1, true);2122test('maxBuffer uses killSignal', async t => {23 const {isTerminated, signal} = await t.throwsAsync(24 execa('noop-forever.js', ['.'.repeat(maxBuffer + 1)], {maxBuffer, killSignal: 'SIGINT'}),22const 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};3132test('maxBuffer terminates stream gracefully, more writes', testGracefulExit, 'noop-repeat.js', 1);33test('maxBuffer terminates stream gracefully, no more writes', testGracefulExit, 'noop-fd.js', 0);3435const 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 lines
modified:test/stream/subprocess.js+3 added-3 removed
99 unmodified lines
100 t.is(error.cause, cause);101 assertStreamOutputError(t, fdNumber, error);102};103104test('Errors on stdout should not make the subprocess exit', testStreamOutputError, 1);105test('Errors on stderr should not make the subprocess exit', testStreamOutputError, 2);106test('Errors on output stdio[*] should not make the subprocess exit', testStreamOutputError, 3);104test('Errors on stdout should make the subprocess exit', testStreamOutputError, 1);105test('Errors on stderr should make the subprocess exit', testStreamOutputError, 2);106test('Errors on output stdio[*] should make the subprocess exit', testStreamOutputError, 3);107108const testWaitOnStreamEnd = async (t, fdNumber) => {109 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], fullStdio);110 await setTimeout(100);
7 unmodified lines