Skip to content
Myr

Fix `maxBuffer` being ignored or wrongly applied

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sindre Sorhus · committed by Sindre Sorhus · parent 6adb3c3 · Browse files · 11 files+240 added−35 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

11 files+240 added−35 removed

  • tests:+178 added−4 removed
  • other:+62 added−31 removed

11 files+240 added−35 removed

modified:docs/api.md+2 added
1025 unmodified lines
1026Largest amount of data allowed on [`stdout`](#resultstdout), [`stderr`](#resultstderr) and [`stdio`](#resultstdio).10271028By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](output.md#stdoutstderr-specific-options).10291030With [synchronous methods](execution.md#synchronous-execution), this cannot be enforced per file descriptor while the subprocess runs, since `spawnSync()` only accepts a single value, which limits the total output of all file descriptors. The `maxBuffer.stdout` value is used for it. The other file descriptors' own values are enforced from the output, once the subprocess ended, and cannot be higher than `maxBuffer.stdout`.10311032When reached, [`error.isMaxBuffer`](#errorismaxbuffer) becomes `true`.10331034[More info.](output.md#big-output)1035
330 unmodified lines
modified:docs/execution.md+1 added-1 removed
modified:lib/io/max-buffer.js+40 added-19 removed
33 unmodified lines
3435 return 'characters';36};3738// Check the `maxBuffer` option with `result.ipcOutput`39export const checkIpcMaxBuffer = (subprocess, ipcOutput, maxBuffer) => {40 if (ipcOutput.length !== maxBuffer) {38// Check the `maxBuffer` option with `result.ipcOutput`, before buffering one more message.39// Like the stream-based `maxBuffer`, the threshold is hit when the buffered amount would exceed it, which also applies to non-integer values.40export const checkIpcMaxBuffer = (ipcOutput, maxBuffer) => {41 if (ipcOutput.length + 1 <= maxBuffer) {42 return;43 }4445 const error = new MaxBufferError();
11 unmodified lines
57 if (error?.maxBufferInfo === undefined) {58 return {streamName: 'output', threshold: maxBuffer[1], unit: 'bytes'};59 }6060 const {maxBufferInfo: {fdNumber, unit}} = error;61 const {maxBufferInfo: {fdNumber, unit, threshold = getFdSpecificValue(maxBuffer, fdNumber)}} = error;62 delete error.maxBufferInfo;6363 const threshold = getFdSpecificValue(maxBuffer, fdNumber);64 if (fdNumber === 'ipc') {65 return {streamName: 'IPC output', threshold, unit: 'messages'};66 }6768 return {streamName: getStreamName(fdNumber), threshold, unit};69};7071// The only way to apply `maxBuffer` with `spawnSync()` is to use the native `maxBuffer` option Node.js provides.72// However, this has multiple limitations, and cannot behave the exact same way as the async behavior.73// When the `maxBuffer` is hit, a `ENOBUFS` error is thrown.74export const isMaxBufferSync = (resultError, output, maxBuffer) => resultError?.code === 'ENOBUFS'75 && output !== null76 && output.some(result => result !== null && result.length > getMaxBufferSync(maxBuffer));71// The native `maxBuffer` option passed to `spawnSync()` does not allow differentiating values per file descriptor, so we use `stdout`'s.72// Since each other file descriptor's own limit is capped by `stdout`'s, this is also the highest one.73// Node.js applies it to the total output of all piped file descriptors, not to each of them. When it is hit, the subprocess is killed and a `ENOBUFS` error is thrown.74export const getMaxBufferSync = ([, stdoutMaxBuffer]) => stdoutMaxBuffer;7578// When `maxBuffer` is hit, ensure the result is truncated79export const truncateMaxBufferSync = (result, isMaxBuffer, maxBuffer) => {80 if (!isMaxBuffer) {81 return result;76// File descriptors with a limit lower than `spawnSync()`'s native `maxBuffer` are enforced from the output, after the subprocess exits.77// Since no native error was thrown, we create the `ENOBUFS` error ourselves.78// Like with asynchronous methods, file descriptors which are not buffered are not limited by their own value. However, when they are piped, e.g. to a file, they still count towards the native limit, which is `stdout`'s value.79export const handleMaxBufferSync = ({resultError, output, maxBuffer, buffer}) => {80 const fdNumber = findMaxBufferSync(output, maxBuffer, buffer);81 if (fdNumber === undefined) {82 // The native limit can be hit by the total output without any single file descriptor being over its own limit83 return {resultError, isMaxBuffer: resultError?.code === 'ENOBUFS'};84 }8584 const maxBufferValue = getMaxBufferSync(maxBuffer);85 return result.length > maxBufferValue ? result.slice(0, maxBufferValue) : result;86 const threshold = getMaxBufferValueSync(maxBuffer, fdNumber);87 const error = resultError ?? Object.assign(new MaxBufferError(), {code: 'ENOBUFS'});88 error.maxBufferInfo = {fdNumber, unit: 'bytes', threshold};89 return {resultError: error, isMaxBuffer: true};90};9188// `spawnSync()` does not allow differentiating `maxBuffer` per file descriptor, so we always use `stdout`89export const getMaxBufferSync = ([, stdoutMaxBuffer]) => stdoutMaxBuffer;92const findMaxBufferSync = (output, maxBuffer, buffer) => {93 if (output === null) {94 return;95 }9697 const fdNumber = output.findIndex((result, index) => result !== null98 && buffer[index]99 && result.length > getMaxBufferValueSync(maxBuffer, index));100 return fdNumber === -1 ? undefined : fdNumber;101};102103// `spawnSync()` uses `maxBuffer.stdout` as its native `maxBuffer`, so other file descriptors' limits can only be lower than that104const getMaxBufferValueSync = (maxBuffer, fdNumber) => Math.min(maxBuffer[1], maxBuffer[fdNumber]);105106// When `maxBuffer` is hit, ensure each buffered file descriptor's result is truncated at its own limit107export const truncateMaxBufferSync = (result, fdNumber, {maxBuffer, buffer}) => {108 const maxBufferValue = getMaxBufferValueSync(maxBuffer, fdNumber);109 return buffer[fdNumber] && result.length > maxBufferValue ? result.slice(0, maxBufferValue) : result;110};
modified:lib/io/output-sync.js+3 added-4 removed
5 unmodified lines
6import {FILE_TYPES} from '../stdio/type.js';7import {truncateMaxBufferSync} from './max-buffer.js';89// Apply `stdout`/`stderr` options, after spawning, in sync mode10export const transformOutputSync = ({fileDescriptors, syncResult: {output}, options, isMaxBuffer, verboseInfo}) => {10export const transformOutputSync = ({fileDescriptors, syncResult: {output}, options, verboseInfo}) => {11 if (output === null) {12 return {output: Array.from({length: 3})};13 }14
5 unmodified lines
20 fileDescriptors,21 fdNumber,22 state,23 outputFiles,24 isMaxBuffer,24 verboseInfo,25 }, options));26 return {output: transformedOutput, ...state};27};2829const transformOutputResultSync = (31 {result, fileDescriptors, fdNumber, state, outputFiles, isMaxBuffer, verboseInfo},30 {result, fileDescriptors, fdNumber, state, outputFiles, verboseInfo},31 {buffer, encoding, lines, stripFinalNewline, maxBuffer},32) => {33 if (result === null) {34 return;35 }3638 const truncatedResult = truncateMaxBufferSync(result, isMaxBuffer, maxBuffer);37 const truncatedResult = truncateMaxBufferSync(result, fdNumber, {maxBuffer, buffer});38 const uint8ArrayResult = bufferToUint8Array(truncatedResult);39 const {stdioItems, objectMode} = fileDescriptors[fdNumber];40 const chunks = runOutputGeneratorsSync([uint8ArrayResult], stdioItems, encoding, state);41 const {serializedResult, finalResult = serializedResult} = serializeChunks({
94 unmodified lines
modified:lib/ipc/buffer-messages.js+1 added-1 removed
27 unmodified lines
28 shouldAwait: false,29 reference: true,30 })) {31 if (buffer) {32 checkIpcMaxBuffer(subprocess, ipcOutput, maxBuffer);32 checkIpcMaxBuffer(ipcOutput, maxBuffer);33 ipcOutput.push(message);34 }3536 if (isVerbose) {
11 unmodified lines
modified:lib/methods/main-sync.js-1 removed
94 unmodified lines
95 const {output, error = resultError} = transformOutputSync({96 fileDescriptors,97 syncResult,98 options,99 isMaxBuffer,99 verboseInfo,100 });101 const stdio = output.map((stdioOutput, fdNumber) => stripNewline(stdioOutput, options, fdNumber));102 const all = stripNewline(getAllSync(output, options), options, 'all');
64 unmodified lines
modified:lib/resolve/exit-sync.js+13 added-5 removed
added:test/fixtures/max-buffer-forever.js+8 added
1#!/usr/bin/env node2import process from 'node:process';3import {getWriteStream} from '../helpers/fs.js';45const fdNumber = Number(process.argv[2]);6const bytes = '.'.repeat(Number(process.argv[3]));7getWriteStream(fdNumber).write(bytes);8setTimeout(() => {}, 1e8);
modified:test/helpers/max-buffer.js+2 added-4 removed
1 unmodified line
23export const maxBuffer = 10;45export const assertErrorMessage = (t, shortMessage, {execaMethod = execa, length = maxBuffer, fdNumber = 1, unit = 'characters'} = {}) => {6 const [expectedStreamName, expectedUnit] = execaMethod === execaSync7 ? ['output', 'bytes']8 : [STREAM_NAMES[fdNumber], unit];9 t.true(shortMessage.includes(`${expectedStreamName} was larger than ${length} ${expectedUnit}`));6 const expectedUnit = execaMethod === execaSync ? 'bytes' : unit;7 t.true(shortMessage.includes(`${STREAM_NAMES[fdNumber]} was larger than ${length} ${expectedUnit}`));8};910const STREAM_NAMES = ['stdin', 'stdout', 'stderr', 'stdio[3]'];
modified:test/io/max-buffer.js+168 added
121 unmodified lines
122test('maxBuffer truncates file descriptors with fd-specific options, stdout, all', testFdSpecific, 1, 'all', execa);123test('maxBuffer truncates file descriptors with fd-specific options, stderr, all', testFdSpecific, 2, 'all', execa);124test('maxBuffer truncates file descriptors with fd-specific options, fd3', testFdSpecific, 3, 'fd3', execa);125test('maxBuffer.stdout is used for stdout with fd-specific options, stdout, sync', testFdSpecific, 1, 'stdout', execaSync);126test('maxBuffer.stderr is used for stderr with fd-specific options, stderr, sync', testFdSpecific, 2, 'stderr', execaSync);127test('maxBuffer.fd3 is used for stdio[*] with fd-specific options, fd3, sync', testFdSpecific, 3, 'fd3', execaSync);128129test('maxBuffer does not affect other file descriptors with fd-specific options', async t => {130 const {isMaxBuffer} = await getMaxBufferSubprocess(execa, 2, {maxBuffer: {stdout: 1}});131 t.false(isMaxBuffer);
25 unmodified lines
157 assertErrorMessage(t, shortMessage, {execaMethod: execaSync, fdNumber: 2, length});158 t.is(stderr, getExpectedOutput(length));159});160161// `spawnSync()`'s native `maxBuffer` is `maxBuffer.stdout`, so a lower limit on another file descriptor is only enforced from the output, after the subprocess exits162test('maxBuffer.stderr is used when lower than maxBuffer.stdout, sync', t => {163 const length = 3;164 const error = t.throws(() => {165 execaSync('noop-both.js', ['.'.repeat(maxBuffer + 1)], {maxBuffer: {stdout: 1e8, stderr: length}});166 }, maxBufferCodeSync);167 t.true(error.isMaxBuffer);168 t.is(error.maxBufferInfo, undefined);169 assertErrorMessage(t, error.shortMessage, {execaMethod: execaSync, fdNumber: 2, length});170 t.is(error.stdout, getExpectedOutput(maxBuffer + 1));171 t.is(error.stderr, getExpectedOutput(length));172 t.is(error.signal, undefined);173 t.is(error.exitCode, 0);174});175176test('maxBuffer.stderr is used when lower than maxBuffer.stdout', async t => {177 const length = 3;178 const error = await t.throwsAsync(execa('noop-both.js', ['.'.repeat(maxBuffer + 1)], {maxBuffer: {stdout: 1e8, stderr: length}}));179 t.true(error.isMaxBuffer);180 assertErrorMessage(t, error.shortMessage, {fdNumber: 2, length});181 t.is(error.stdout, getExpectedOutput(maxBuffer + 1));182 t.is(error.stderr, getExpectedOutput(length));183 t.is(error.signal, undefined);184 t.is(error.exitCode, 0);185});186187test('maxBuffer is not hit when under each file descriptor\'s value, sync', t => {188 const length = 9;189 const {isMaxBuffer, stdout, stderr} = execaSync('noop-both.js', ['.'.repeat(length)], {maxBuffer: {stdout: 1e8, stderr: 10}});190 t.false(isMaxBuffer);191 t.is(stdout, getExpectedOutput(length));192 t.is(stderr, getExpectedOutput(length));193});194195const testAll = async (t, shouldFail) => {196 const difference = shouldFail ? 0 : 1;197 const maxBufferStdout = 2;198 const maxBufferStderr = 4 - difference;
35 unmodified lines
234test('maxBuffer.fd0 is invalid, sync', testInvalidFd, 'fd0', execaSync);235test('maxBuffer.other is invalid, sync', testInvalidFd, 'other', execaSync);236test('maxBuffer.fd10 is invalid, sync', testInvalidFd, 'fd10', execaSync);237238// These tests need the subprocess to have written its output before the timeout kills it, which is only guaranteed if the timeout leaves room for the subprocess to start. On a busy machine, starting Node.js can take over a second.239const SYNC_TIMEOUT = 1e4;240241// A file descriptor limit lower than `maxBuffer.stdout` does not stop the subprocess with synchronous methods, so the subprocess can still time out afterwards242const testMaxBufferTimeoutSync = (t, fdNumber, fdName) => {243 const length = 3;244 const error = t.throws(() => {245 execaSync('max-buffer-forever.js', [`${fdNumber}`, `${maxBuffer}`], {...fullStdio, timeout: SYNC_TIMEOUT, maxBuffer: {[fdName]: length}});246 }, {code: 'ETIMEDOUT'});247 t.true(error.timedOut);248 t.false(error.isMaxBuffer);249 t.is(error.maxBufferInfo, undefined);250 t.false(Object.hasOwn(error.cause, 'maxBufferInfo'));251 t.true(error.shortMessage.startsWith(`Command timed out after ${SYNC_TIMEOUT} milliseconds`));252 t.is(error.stdio[fdNumber], getExpectedOutput(length));253};254255test('timeout is reported instead of maxBuffer.stderr, sync', testMaxBufferTimeoutSync, 2, 'stderr');256test('timeout is reported instead of maxBuffer.fd3, sync', testMaxBufferTimeoutSync, 3, 'fd3');257258test('timeout does not truncate output under maxBuffer.stderr, sync', t => {259 const {timedOut, isMaxBuffer, stderr} = t.throws(() => {260 execaSync('max-buffer-forever.js', ['2', `${maxBuffer}`], {timeout: SYNC_TIMEOUT, maxBuffer: {stderr: maxBuffer}});261 }, {code: 'ETIMEDOUT'});262 t.true(timedOut);263 t.false(isMaxBuffer);264 t.is(stderr, getExpectedOutput(maxBuffer));265});266267// `maxBuffer.stdout` is enforced by `spawnSync()` itself, which stops the subprocess before it can time out268test('maxBuffer.stdout is reported before timeout, sync', t => {269 const length = 3;270 const error = t.throws(() => {271 execaSync('max-buffer-forever.js', ['1', `${maxBuffer}`], {timeout: SYNC_TIMEOUT, maxBuffer: {stdout: length}});272 }, maxBufferCodeSync);273 t.false(error.timedOut);274 t.true(error.isMaxBuffer);275 t.is(error.maxBufferInfo, undefined);276 assertErrorMessage(t, error.shortMessage, {execaMethod: execaSync, length});277 t.is(error.stdout, getExpectedOutput(length));278});279280test('maxBuffer.stderr is reported with a non-zero exit code, sync', t => {281 const length = 3;282 const error = t.throws(() => {283 execaSync('noop-both-fail.js', ['.'.repeat(maxBuffer)], {maxBuffer: {stdout: 1e8, stderr: length}});284 });285 t.true(error.isMaxBuffer);286 t.is(error.maxBufferInfo, undefined);287 assertErrorMessage(t, error.shortMessage, {execaMethod: execaSync, fdNumber: 2, length});288 t.is(error.exitCode, 1);289 t.is(error.stdout, getExpectedOutput(maxBuffer));290 t.is(error.stderr, getExpectedOutput(length));291});292293test('maxBuffer.stderr works with reject false, sync', t => {294 const length = 3;295 const {failed, isMaxBuffer, maxBufferInfo, shortMessage, stderr} = execaSync('noop-fd.js', ['2', '.'.repeat(maxBuffer)], {maxBuffer: {stdout: 1e8, stderr: length}, reject: false});296 t.true(failed);297 t.true(isMaxBuffer);298 t.is(maxBufferInfo, undefined);299 assertErrorMessage(t, shortMessage, {execaMethod: execaSync, fdNumber: 2, length});300 t.is(stderr, getExpectedOutput(length));301});302303test('maxBuffer.stderr works with lines, sync', t => {304 const length = 3;305 const {isMaxBuffer, stderr} = t.throws(() => {306 execaSync('noop-both.js', ['.'.repeat(maxBuffer)], {maxBuffer: {stdout: 1e8, stderr: length}, lines: true});307 }, maxBufferCodeSync);308 t.true(isMaxBuffer);309 t.deepEqual(stderr, [getExpectedOutput(length)]);310});311312test('maxBuffer.stdout is an upper bound for maxBuffer.stderr, sync', t => {313 const length = 3;314 const {isMaxBuffer, shortMessage, stderr} = t.throws(() => {315 execaSync('noop-fd.js', ['2', '.'.repeat(maxBuffer)], {maxBuffer: {stdout: length, stderr: 1e8}});316 }, maxBufferCodeSync);317 t.true(isMaxBuffer);318 assertErrorMessage(t, shortMessage, {execaMethod: execaSync, fdNumber: 2, length});319 t.is(stderr, getExpectedOutput(length));320});321322test('maxBuffer.stderr is not reported on spawn errors, sync', t => {323 const {code, isMaxBuffer} = t.throws(() => {324 execaSync('non-existent-command', {maxBuffer: {stderr: 1}});325 });326 t.is(code, 'ENOENT');327 t.false(isMaxBuffer);328});329330const testMaxBufferEncoding = async (t, execaMethod, fdNumber) => {331 const {shortMessage, stdio} = await runMaxBuffer(t, execaMethod, fdNumber, {encoding: 'buffer'});332 assertErrorMessage(t, shortMessage, {execaMethod, fdNumber, unit: 'bytes'});333 const stream = stdio[fdNumber];
114 unmodified lines
448test('maxBuffer is ignored with result.ipcOutput if buffer is false', async t => {449 const {ipcOutput} = await execa('ipc-send-twice.js', {ipc: true, maxBuffer: {ipc: 1}, buffer: false});450 t.deepEqual(ipcOutput, []);451});452453/*454`result.ipcOutput` is counted in messages, which are indivisible, so any `maxBuffer` value the count cannot land on exactly must still be enforced.455The threshold is hit as soon as buffering one more message would exceed it, which is how the stream-based `maxBuffer` behaves too.456*/457const testIpcMaxBufferValue = async (t, maxBuffer, expectedOutput) => {458 const {isMaxBuffer, ipcOutput} = await t.throwsAsync(execa('ipc-send-twice.js', {ipc: true, maxBuffer: {ipc: maxBuffer}}));459 t.true(isMaxBuffer);460 t.deepEqual(ipcOutput, expectedOutput);461};462463test('maxBuffer works with result.ipcOutput, negative', testIpcMaxBufferValue, -1, []);464test('maxBuffer works with result.ipcOutput, 0', testIpcMaxBufferValue, 0, []);465test('maxBuffer works with result.ipcOutput, below 1', testIpcMaxBufferValue, 0.5, []);466test('maxBuffer works with result.ipcOutput, 1', testIpcMaxBufferValue, 1, [foobarArray[0]]);467test('maxBuffer works with result.ipcOutput, fractional', testIpcMaxBufferValue, 1.5, [foobarArray[0]]);468469const testIpcMaxBufferNotHit = async (t, maxBuffer) => {470 const {isMaxBuffer, ipcOutput} = await execa('ipc-send-twice.js', {ipc: true, maxBuffer: {ipc: maxBuffer}});471 t.false(isMaxBuffer);472 t.deepEqual(ipcOutput, foobarArray);473};474475test('maxBuffer is not hit with result.ipcOutput, exact count', testIpcMaxBufferNotHit, 2);476test('maxBuffer is not hit with result.ipcOutput, fractional', testIpcMaxBufferNotHit, 2.5);477478// The same `maxBuffer` value must be interpreted the same way whether the output is buffered as messages or as characters479const testIpcMaxBufferLikeStream = async (t, maxBuffer) => {480 const [ipcResult, streamResult] = await Promise.all([481 execa('ipc-send-twice.js', {ipc: true, maxBuffer: {ipc: maxBuffer}, reject: false}),482 execa('noop-fd.js', ['1', 'ab'], {maxBuffer, reject: false}),483 ]);484 t.is(ipcResult.isMaxBuffer, streamResult.isMaxBuffer);485 t.is(ipcResult.ipcOutput.length, streamResult.stdout.length);486};487488test('maxBuffer with result.ipcOutput matches stdout, 0.5', testIpcMaxBufferLikeStream, 0.5);489test('maxBuffer with result.ipcOutput matches stdout, 1', testIpcMaxBufferLikeStream, 1);490test('maxBuffer with result.ipcOutput matches stdout, 1.5', testIpcMaxBufferLikeStream, 1.5);491test('maxBuffer with result.ipcOutput matches stdout, 2', testIpcMaxBufferLikeStream, 2);
modified:types/arguments/options.d.ts+2 added
190 unmodified lines
191 Largest amount of data allowed on `stdout`, `stderr` and `stdio`.192193 By default, this applies to both `stdout` and `stderr`, but different values can also be passed.194195 With synchronous methods, this cannot be enforced per file descriptor while the subprocess runs, since `spawnSync()` only accepts a single value, which limits the total output of all file descriptors. The `maxBuffer.stdout` value is used for it. The other file descriptors' own values are enforced from the output, once the subprocess ended, and cannot be higher than `maxBuffer.stdout`.196197 When reached, `error.isMaxBuffer` becomes `true`.198199 @default 100_000_000200 */
229 unmodified lines