wait-stream.js
This file
Path
lib/resolve/wait-stream.js
121 lines · 6.3 KiB · JavaScript
Last changed by
Fix `stdin` iterables and input transforms edge casesSindre Sorhusbefore adoption6925cc3
History of this fileTake it
The walk stopped after 200 commits: lines older than 9f65b86 point at it.
100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 1–5why, one step back1import {finished} from 'node:stream/promises';23// Wraps `finished(stream)` to handle the following case:4// - When the subprocess exits, Node.js automatically calls `subprocess.stdin.destroy()`, which we need to ignore.5// - However, we still need to throw if `subprocess.stdin.destroy()` is called before subprocess exit.Fix the subprocess promise hanging until the user consumes an output streamSindre Sorhusbefore adoption004f3b3
lines 6–11why, one step back6export const waitForStream = async (stream, fdNumber, streamInfo, {7 isSameDirection,8 stopOnExit = false,9 readable = true,10 writable = true,11} = {}) => {100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 12–16why, one step back12 const state = handleStdinDestroy(stream, streamInfo);13 const abortController = new AbortController();14 try {15 await Promise.race([16 ...(stopOnExit ? [streamInfo.exitPromise] : []),Fix the subprocess promise hanging until the user consumes an output streamSindre Sorhusbefore adoption004f3b3
lines 17–22why, one step back17 finished(stream, {18 cleanup: true,19 signal: abortController.signal,20 readable,21 writable,22 }),100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 23–24why, one step back23 ]);24 } catch (error) {Fix `stdin` iterables and input transforms edge casesSindre Sorhusbefore adoption6925cc3
line 25why, one step back25 if (!state.stdinCleanedUp && !isInputTransformAbort(stream, fdNumber, streamInfo, error)) {100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 26–43why, one step back26 handleStreamError(error, fdNumber, streamInfo, isSameDirection);27 }28 } finally {29 abortController.abort();30 }31};3233// If `subprocess.stdin` is destroyed before being fully written to, it is considered aborted and should throw an error.34// This can happen for example when user called `subprocess.stdin.destroy()` before `subprocess.stdin.end()`.35// However, Node.js calls `subprocess.stdin.destroy()` on exit for cleanup purposes.36// https://github.com/nodejs/node/blob/0b4cdb4b42956cbd7019058e409e06700a199e11/lib/internal/child_process.js#L27837// This is normal and should not throw an error.38// Therefore, we need to differentiate between both situations to know whether to throw an error.39// Unfortunately, events (`close`, `error`, `end`, `exit`) cannot be used because `.destroy()` can take an arbitrary amount of time.40// For example, `stdin: 'pipe'` is implemented as a TCP socket, and its `.destroy()` method waits for TCP disconnection.41// Therefore `.destroy()` might end before or after subprocess exit, based on OS speed and load.42// The only way to detect this is to spy on `subprocess.stdin._destroy()` by wrapping it.43// If `subprocess.exitCode` or `subprocess.signalCode` is set, it means `.destroy()` is being called by Node.js itself.Fix `stdin` iterables and input transforms edge casesSindre Sorhusbefore adoption6925cc3
line 44why, one step back44// With an input transform, `subprocess.stdin` is that transform, so Node.js destroys it instead of the original `stdin`.Require Node.js 22 (#1243)Sindre Sorhusbefore adoption04b4454
lines 45–46why, one step back45const handleStdinDestroy = (stream, {originalStreams, subprocess}) => {46 const [originalStdin] = originalStreams;100% test coverage (#1018)ehmickybefore adoption9f65b86
line 47why, one step back47 const state = {stdinCleanedUp: false};Fix `stdin` iterables and input transforms edge casesSindre Sorhusbefore adoption6925cc3
line 48why, one step back48 if (stream === originalStdin || stream === subprocess.stdin) {100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 49–66why, one step back49 spyOnStdinDestroy(stream, subprocess, state);50 }5152 return state;53};5455const spyOnStdinDestroy = (subprocessStdin, subprocess, state) => {56 const {_destroy} = subprocessStdin;57 subprocessStdin._destroy = (...destroyArguments) => {58 setStdinCleanedUp(subprocess, state);59 _destroy.call(subprocessStdin, ...destroyArguments);60 };61};6263const setStdinCleanedUp = ({exitCode, signalCode}, state) => {64 if (exitCode !== null || signalCode !== null) {65 state.stdinCleanedUp = true;66 }Fix `stdin` iterables and input transforms edge casesSindre Sorhusbefore adoption6925cc3
lines 67–78why, one step back67};6869// An input transform writes to the subprocess' original stream. When that stream is closed first, e.g. when the subprocess exits without reading its input, the transform is aborted.70// Like `EPIPE` with `stdin: 'pipe'`, this is not an error.71// When the transform is aborted by the user instead, the original stream is still open at that point.72const isInputTransformAbort = (stream, fdNumber, streamInfo, error) => {73 const originalStream = streamInfo.originalStreams[fdNumber];74 return stream !== originalStream75 && isInputFileDescriptor(streamInfo, fdNumber)76 && originalStream?.destroyed === true77 // A `TransformStream` is aborted with an `AbortError`78 && (isStreamAbort(error) || error?.code === 'ABORT_ERR');100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 79–112why, one step back79};8081// We ignore EPIPEs on writable streams and aborts on readable streams since those can happen normally.82// When one stream errors, the error is propagated to the other streams on the same file descriptor.83// Those other streams might have a different direction due to the above.84// When this happens, the direction of both the initial stream and the others should then be taken into account.85// Therefore, we keep track of whether a stream error is currently propagating.86const handleStreamError = (error, fdNumber, streamInfo, isSameDirection) => {87 if (!shouldIgnoreStreamError(error, fdNumber, streamInfo, isSameDirection)) {88 throw error;89 }90};9192const shouldIgnoreStreamError = (error, fdNumber, streamInfo, isSameDirection = true) => {93 if (streamInfo.propagating) {94 return isStreamEpipe(error) || isStreamAbort(error);95 }9697 streamInfo.propagating = true;98 return isInputFileDescriptor(streamInfo, fdNumber) === isSameDirection99 ? isStreamEpipe(error)100 : isStreamAbort(error);101};102103// Unfortunately, we cannot use the stream's class or properties to know whether it is readable or writable.104// For example, `subprocess.stdin` is technically a Duplex, but can only be used as a writable.105// Therefore, we need to use the file descriptor's direction (`stdin` is input, `stdout` is output, etc.).106// However, while `subprocess.std*` and transforms follow that direction, any stream passed the `std*` option has the opposite direction.107// For example, `subprocess.stdin` is a writable, but the `stdin` option is a readable.108export const isInputFileDescriptor = ({fileDescriptors}, fdNumber) => fdNumber !== 'all' && fileDescriptors[fdNumber].direction === 'input';109110// When `stream.destroy()` is called without an `error` argument, stream is aborted.111// This is the only way to abort a readable stream, which can be useful in some instances.112// Therefore, we ignore this error on readable streams.Fix `.pipe()` and stream conversion edge casesSindre Sorhusbefore adoptiond3ec10d
line 113why, one step back113// Breaking out of `for await (const chunk of subprocess.stdout)` aborts it with an `AbortError` instead. However, that error cannot be told apart from an `AbortError` thrown by a transform, which must make the subprocess fail. So this is not supported, and `subprocess.readable()` or `subprocess.iterable()` should be used instead.100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 114–121why, one step back114export const isStreamAbort = error => error?.code === 'ERR_STREAM_PREMATURE_CLOSE';115116// When `stream.write()` is called but the underlying source has been closed, `EPIPE` is emitted.117// When piping subprocesses, the source subprocess usually decides when to stop piping.118// However, there are some instances when the destination does instead, such as `... | head -n1`.119// It notifies the source by using `EPIPE`.120// Therefore, we ignore this error on writable streams.121const isStreamEpipe = error => error?.code === 'EPIPE';