Skip to content
Myr

wait-stream.js

This file

Path

lib/resolve/wait-stream.js

107 lines · 5.1 KiB · JavaScript

Last changed by

Fix the subprocess promise hanging until the user consumes an output streamSindre Sorhusbefore adoption004f3b3

History of this file

Take it

The walk stopped after 200 commits: lines older than 4b2e316 point at it.

Rename files (#977)ehmickybefore adoption4b2e316

lines 1–5why, one step back
1import {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 back
6export const waitForStream = async (stream, fdNumber, streamInfo, {
7 isSameDirection,8 stopOnExit = false,9 readable = true,10 writable = true,11} = {}) => {

Rename files (#977)ehmickybefore adoption4b2e316

lines 12–16why, one step back
12 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 back
17 finished(stream, {
18 cleanup: true,19 signal: abortController.signal,20 readable,21 writable,22 }),

Rename files (#977)ehmickybefore adoption4b2e316

lines 23–43why, one step back
23 ]);
24 } catch (error) {25 if (!state.stdinCleanedUp) {26 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.

Require Node.js 22 (#1243)Sindre Sorhusbefore adoption04b4454

lines 44–45why, one step back
44const handleStdinDestroy = (stream, {originalStreams, subprocess}) => {
45 const [originalStdin] = originalStreams;

Rename files (#977)ehmickybefore adoption4b2e316

lines 46–55why, one step back
46 const state = {stdinCleanedUp: false};
47 if (stream === originalStdin) {48 spyOnStdinDestroy(stream, subprocess, state);49 }5051 return state;52};5354const spyOnStdinDestroy = (subprocessStdin, subprocess, state) => {55 const {_destroy} = subprocessStdin;

Upgrade xo (#980)ehmickybefore adoptionccfa412

line 56why, one step back
56 subprocessStdin._destroy = (...destroyArguments) => {

Rename files (#977)ehmickybefore adoption4b2e316

line 57why, one step back
57 setStdinCleanedUp(subprocess, state);

Upgrade xo (#980)ehmickybefore adoptionccfa412

line 58why, one step back
58 _destroy.call(subprocessStdin, ...destroyArguments);

Rename files (#977)ehmickybefore adoption4b2e316

lines 59–107why, one step back
59 };
60};6162const setStdinCleanedUp = ({exitCode, signalCode}, state) => {63 if (exitCode !== null || signalCode !== null) {64 state.stdinCleanedUp = true;65 }66};6768// We ignore EPIPEs on writable streams and aborts on readable streams since those can happen normally.69// When one stream errors, the error is propagated to the other streams on the same file descriptor.70// Those other streams might have a different direction due to the above.71// When this happens, the direction of both the initial stream and the others should then be taken into account.72// Therefore, we keep track of whether a stream error is currently propagating.73const handleStreamError = (error, fdNumber, streamInfo, isSameDirection) => {74 if (!shouldIgnoreStreamError(error, fdNumber, streamInfo, isSameDirection)) {75 throw error;76 }77};7879const shouldIgnoreStreamError = (error, fdNumber, streamInfo, isSameDirection = true) => {80 if (streamInfo.propagating) {81 return isStreamEpipe(error) || isStreamAbort(error);82 }8384 streamInfo.propagating = true;85 return isInputFileDescriptor(streamInfo, fdNumber) === isSameDirection86 ? isStreamEpipe(error)87 : isStreamAbort(error);88};8990// Unfortunately, we cannot use the stream's class or properties to know whether it is readable or writable.91// For example, `subprocess.stdin` is technically a Duplex, but can only be used as a writable.92// Therefore, we need to use the file descriptor's direction (`stdin` is input, `stdout` is output, etc.).93// However, while `subprocess.std*` and transforms follow that direction, any stream passed the `std*` option has the opposite direction.94// For example, `subprocess.stdin` is a writable, but the `stdin` option is a readable.95export const isInputFileDescriptor = ({fileDescriptors}, fdNumber) => fdNumber !== 'all' && fileDescriptors[fdNumber].direction === 'input';9697// When `stream.destroy()` is called without an `error` argument, stream is aborted.98// This is the only way to abort a readable stream, which can be useful in some instances.99// Therefore, we ignore this error on readable streams.100export const isStreamAbort = error => error?.code === 'ERR_STREAM_PREMATURE_CLOSE';101102// When `stream.write()` is called but the underlying source has been closed, `EPIPE` is emitted.103// When piping subprocesses, the source subprocess usually decides when to stop piping.104// However, there are some instances when the destination does instead, such as `... | head -n1`.105// It notifies the source by using `EPIPE`.106// Therefore, we ignore this error on writable streams.107const isStreamEpipe = error => error?.code === 'EPIPE';