Fix race condition with `subprocess.stdin.destroy()` (#904)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent d1889f6 · Browse files · 3 files·+42 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
3 files+42 added−8 removed
- tests:+2 added−3 removed
- other:+40 added−5 removed
Provenance
- Commit
588bf16- Tree
4cc4345- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
d1889f6
3 files changed+42 added−8 removed
modified:lib/stream/resolve.js+1 added-1 removed
17 unmodified lines1819202122222324252658 unmodified lines17 unmodified lines originalStreams, controller,}) => { const exitPromise = waitForExit(subprocess); const streamInfo = {originalStreams, stdioStreamsGroups, exitPromise, propagating: new Set([])}; const streamInfo = {originalStreams, stdioStreamsGroups, subprocess, exitPromise, propagating: new Set([])};
const stdioPromises = waitForSubprocessStreams({subprocess, encoding, buffer, maxBuffer, streamInfo}); const allPromise = waitForAllStream({subprocess, encoding, buffer, maxBuffer, streamInfo}); const originalPromises = waitForOriginalStreams(originalStreams, subprocess, streamInfo);58 unmodified linesmodified:lib/stream/wait.js+39 added-4 removed
2 unmodified lines345678789101211121314151616171819202122232425262728293031323334353637383940414243444546474849505152535455565758596039 unmodified lines2 unmodified lines// Wraps `finished(stream)` to handle the following case:// - When the subprocess exits, Node.js automatically calls `subprocess.stdin.destroy()`, which we need to ignore.// - However, we still need to throw if `subprocess.stdin.destroy()` is called before subprocess exit.export const waitForStream = async (stream, fdNumber, streamInfo, {isSameDirection, stopOnExit = false} = {}) => { const {originalStreams: [originalStdin], exitPromise} = streamInfo;
const state = handleStdinDestroy(stream, streamInfo); const abortController = new AbortController(); try { await Promise.race([ ...(stopOnExit || stream === originalStdin ? [exitPromise] : []), ...(stopOnExit ? [streamInfo.exitPromise] : []), finished(stream, {cleanup: true, signal: abortController.signal}), ]); } catch (error) { if (!state.stdinCleanedUp) { handleStreamError(error, fdNumber, streamInfo, isSameDirection); handleStreamError(error, fdNumber, streamInfo, isSameDirection); } } finally { abortController.abort(); }};
// If `subprocess.stdin` is destroyed before being fully written to, it is considered aborted and should throw an error.// This can happen for example when user called `subprocess.stdin.destroy()` before `subprocess.stdin.end()`.// However, Node.js calls `subprocess.stdin.destroy()` on exit for cleanup purposes.// https://github.com/nodejs/node/blob/0b4cdb4b42956cbd7019058e409e06700a199e11/lib/internal/child_process.js#L278// This is normal and should not throw an error.// Therefore, we need to differentiate between both situations to know whether to throw an error.// Unfortunately, events (`close`, `error`, `end`, `exit`) cannot be used because `.destroy()` can take an arbitrary amount of time.// For example, `stdin: 'pipe'` is implemented as a TCP socket, and its `.destroy()` method waits for TCP disconnection.// Therefore `.destroy()` might end before or after subprocess exit, based on OS speed and load.// The only way to detect this is to spy on `subprocess.stdin._destroy()` by wrapping it.// If `subprocess.exitCode` or `subprocess.signalCode` is set, it means `.destroy()` is being called by Node.js itself.const handleStdinDestroy = (stream, {originalStreams: [originalStdin], subprocess}) => { const state = {stdinCleanedUp: false}; if (stream === originalStdin) { spyOnStdinDestroy(stream, subprocess, state); }
return state;};
const spyOnStdinDestroy = (subprocessStdin, subprocess, state) => { const {_destroy} = subprocessStdin; subprocessStdin._destroy = (...args) => { setStdinCleanedUp(subprocess, state); _destroy.call(subprocessStdin, ...args); };};
const setStdinCleanedUp = ({exitCode, signalCode}, state) => { if (exitCode !== null || signalCode !== null) { state.stdinCleanedUp = true; }};
// We ignore EPIPEs on writable streams and aborts on readable streams since those can happen normally.// When one stream errors, the error is propagated to the other streams on the same file descriptor.// Those other streams might have a different direction due to the above.// When this happens, the direction of both the initial stream and the others should then be taken into account.39 unmodified linesmodified:test/stdio/async.js+2 added-3 removed
17 unmodified lines18 stdout: ['pipe', 'inherit', ...(isMultiple ? [1, process.stdout] : [])],19 stderr: ['pipe', 'inherit', ...(isMultiple ? [2, process.stderr] : [])],20 });21 22-const onStdinRemoveListener = () => once(process.stdin, 'removeListener', {cleanup: true});22+const onStdinRemoveListener = () => once(process.stdin, 'removeListener');23 24 const testListenersCleanup = async (t, isMultiple) => {25 const streamsPreviousListeners = getStandardStreamsListeners();26 const subprocess = execa('empty.js', getComplexStdio(isMultiple));27 t.notDeepEqual(getStandardStreamsListeners(), streamsPreviousListeners);28- await subprocess;29- await onStdinRemoveListener();28+ await Promise.all([subprocess, onStdinRemoveListener()]);29 if (isMultiple) {30 await onStdinRemoveListener();31 }32 52 unmodified lines