Skip to content
Myr

wait-stream.js

This file

Path

lib/resolve/wait-stream.js

96 lines · 5.0 KiB · JavaScript

Last changed by

Upgrade xo (#980)ehmickybefore adoptionccfa412

History of this file

Take it

Rename files (#977)ehmickybefore adoption4b2e316

lines 1–44why, 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.6export const waitForStream = async (stream, fdNumber, streamInfo, {isSameDirection, stopOnExit = false} = {}) => {7 const state = handleStdinDestroy(stream, streamInfo);8 const abortController = new AbortController();9 try {10 await Promise.race([11 ...(stopOnExit ? [streamInfo.exitPromise] : []),12 finished(stream, {cleanup: true, signal: abortController.signal}),13 ]);14 } catch (error) {15 if (!state.stdinCleanedUp) {16 handleStreamError(error, fdNumber, streamInfo, isSameDirection);17 }18 } finally {19 abortController.abort();20 }21};2223// If `subprocess.stdin` is destroyed before being fully written to, it is considered aborted and should throw an error.24// This can happen for example when user called `subprocess.stdin.destroy()` before `subprocess.stdin.end()`.25// However, Node.js calls `subprocess.stdin.destroy()` on exit for cleanup purposes.26// https://github.com/nodejs/node/blob/0b4cdb4b42956cbd7019058e409e06700a199e11/lib/internal/child_process.js#L27827// This is normal and should not throw an error.28// Therefore, we need to differentiate between both situations to know whether to throw an error.29// Unfortunately, events (`close`, `error`, `end`, `exit`) cannot be used because `.destroy()` can take an arbitrary amount of time.30// For example, `stdin: 'pipe'` is implemented as a TCP socket, and its `.destroy()` method waits for TCP disconnection.31// Therefore `.destroy()` might end before or after subprocess exit, based on OS speed and load.32// The only way to detect this is to spy on `subprocess.stdin._destroy()` by wrapping it.33// If `subprocess.exitCode` or `subprocess.signalCode` is set, it means `.destroy()` is being called by Node.js itself.34const handleStdinDestroy = (stream, {originalStreams: [originalStdin], subprocess}) => {35 const state = {stdinCleanedUp: false};36 if (stream === originalStdin) {37 spyOnStdinDestroy(stream, subprocess, state);38 }3940 return state;41};4243const spyOnStdinDestroy = (subprocessStdin, subprocess, state) => {44 const {_destroy} = subprocessStdin;

Upgrade xo (#980)ehmickybefore adoptionccfa412

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

Rename files (#977)ehmickybefore adoption4b2e316

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

Upgrade xo (#980)ehmickybefore adoptionccfa412

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

Rename files (#977)ehmickybefore adoption4b2e316

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