Destroy internal streams when process exits early (#770)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent db95b51 · Browse files · 8 files·+45 added−8 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+45 added−8 removed
- tests:+23 added−1 removed
- other:+22 added−7 removed
Provenance
- Commit
8db0b09- Tree
2151fab- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
db95b51
8 files changed+45 added−8 removed
modified:lib/stdio/async.js+13 added-1 removed
3 unmodified lines456788910111252 unmodified lines656667686970717273747576777879803 unmodified linesimport mergeStreams from '@sindresorhus/merge-streams';import {handleInput} from './handle.js';import {TYPE_TO_MESSAGE} from './type.js';import {generatorToDuplexStream, pipeGenerator} from './generator.js';import {pipeStreams} from './utils.js';import {pipeStreams, isStandardStream} from './utils.js';
// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async modeexport const handleInputAsync = options => handleInput(addPropertiesAsync, options, false);
52 unmodified lines } else { inputStreamsGroups[index] = [...(inputStreamsGroups[index] ?? []), value]; }};
// 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.export const cleanupStdioStreams = stdioStreamsGroups => { for (const {value, type} of stdioStreamsGroups.flat()) { if (type !== 'native' && !isStandardStream(value)) { value.destroy(); } }};modified:lib/stdio/native.js+1 added-3 removed
112345636 unmodified lines434445464748import process from 'node:process';import {isStream as isNodeStream} from 'is-stream';import {STANDARD_STREAMS} from './utils.js';
// When we use multiple `stdio` values for the same streams, we pass 'pipe' to `child_process.spawn()`.// We then emulate the piping done by core Node.js.// To do so, we transform the following values:36 unmodified lines }
return standardStream;};
export const STANDARD_STREAMS = [process.stdin, process.stdout, process.stderr];modified:lib/stdio/utils.js+4 added
12345614 unmodified lines21222324252627import {Buffer} from 'node:buffer';import process from 'node:process';import {finished} from 'node:stream/promises';
export const bufferToUint8Array = buffer => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
14 unmodified lines } catch { destination.destroy(); }};
export const isStandardStream = stream => STANDARD_STREAMS.includes(stream);export const STANDARD_STREAMS = [process.stdin, process.stdout, process.stderr];modified:lib/stream.js+2 added-2 removed
2 unmodified lines3 import {setImmediate} from 'node:timers/promises';4 import getStream, {getStreamAsArrayBuffer, getStreamAsArray} from 'get-stream';5 import mergeStreams from '@sindresorhus/merge-streams';6 import {throwOnTimeout, cleanupOnExit} from './kill.js';7-import {STANDARD_STREAMS} from './stdio/native.js';7+import {isStandardStream} from './stdio/utils.js';8 import {generatorToDuplexStream} from './stdio/generator.js';9 10 // `all` interleaves `stdout` and `stderr`11 export const makeAllStream = ({stdout, stderr}, {all}) => all && (stdout || stderr)87 unmodified lines99 .filter(({value, type, direction}) => !shouldWaitForCustomStream(value, type, direction))100 .map(({value}) => throwOnStreamError(value));101 102 const shouldWaitForCustomStream = (value, type, direction) => (type === 'fileUrl' || type === 'filePath')103- || (direction === 'output' && !STANDARD_STREAMS.includes(value));103+ || (direction === 'output' && !isStandardStream(value));104 105 const throwIfStreamError = stream => stream === null ? [] : [throwOnStreamError(stream)];106 107 const throwOnStreamError = async stream => {75 unmodified linesmodified:test/helpers/generator.js+7 added-1 removed
1-import {setImmediate} from 'node:timers/promises';1+import {setImmediate, setInterval} from 'node:timers/promises';2 import {foobarObject} from './input.js';3 4 export const noopGenerator = (objectMode, binary) => ({5 * transform(line) {52 unmodified lines58 59 const generatorOptions = typeof transform === 'function' ? {transform} : transform;60 return ({...generatorOptions, transform: noYieldTransform, final: generatorOptions.transform});61 };62+63+export const infiniteGenerator = async function * () {64+ for await (const value of setInterval(100, 'foo')) {65+ yield value;66+ }67+};modified:test/stdio/generator.js+5 added
15 unmodified lines16 getOutputGenerator,17 outputObjectGenerator,18 noYieldGenerator,19 convertTransformToFinal,20+ infiniteGenerator,21 } from '../helpers/generator.js';22 23 setFixtureDir();24 677 unmodified lines702 const childProcess = execa('stdin-fd.js', ['0'], {stdin: [noopGenerator(false), throwingGenerator, noopGenerator(false)]});703 childProcess.stdin.write('foobar\n');704 await t.throwsAsync(childProcess, {message: GENERATOR_ERROR_REGEXP});705 });706+707+test('Generators are canceled on early process exit', async t => {708+ await t.throwsAsync(execa('noop.js', {stdout: infiniteGenerator, uid: -1}));709+});modified:test/stdio/node-stream.js+11 added
129 unmodified lines130 const {timedOut} = await t.throwsAsync(childProcess);131 t.true(timedOut);132 t.true(waitedForDestroy);133 });134+135+const noopReadable = () => new Readable({read() {}});136+const noopWritable = () => new Writable({write() {}});137+138+const testStreamEarlyExit = async (t, stream, streamName) => {139+ await t.throwsAsync(execa('noop.js', {[streamName]: [stream, 'pipe'], uid: -1}));140+ t.true(stream.destroyed);141+};142+143+test('Input streams are canceled on early process exit', testStreamEarlyExit, noopReadable(), 'stdin');144+test('Output streams are canceled on early process exit', testStreamEarlyExit, noopWritable(), 'stdout');modified:index.js+2 added-1 removed
6 unmodified lines7 import crossSpawn from 'cross-spawn';8 import stripFinalNewline from 'strip-final-newline';9 import {npmRunPathEnv} from 'npm-run-path';10 import {makeError} from './lib/error.js';11-import {handleInputAsync, pipeOutputAsync} from './lib/stdio/async.js';11+import {handleInputAsync, pipeOutputAsync, cleanupStdioStreams} from './lib/stdio/async.js';12 import {handleInputSync, pipeOutputSync} from './lib/stdio/sync.js';13 import {normalizeStdioNode} from './lib/stdio/normalize.js';14 import {spawnedKill, validateTimeout, normalizeForceKillAfterDelay} from './lib/kill.js';15 import {pipeToProcess} from './lib/pipe.js';118 unmodified lines134 let spawned;135 try {136 spawned = childProcess.spawn(file, args, options);137 } catch (error) {138+ cleanupStdioStreams(stdioStreamsGroups);139 // Ensure the returned error is always both a promise and a child process140 const dummySpawned = new childProcess.ChildProcess();141 const errorInstance = makeError({142 error,217 unmodified lines