Skip to content
Myr

wait.js

This file

Path

lib/stream/wait.js

96 lines · 4.9 KiB · JavaScript

Last changed by

Simplify implementation (#955)ehmickybefore adoption8ad9ee7

History of this file

Take it

Split files (#837)ehmickybefore adoption672c2d7

lines 1–3why, one step back
1import {finished} from 'node:stream/promises';
23// Wraps `finished(stream)` to handle the following case:

Rename `spawned` and `child process` to `subprocess` (#897)ehmickybefore adoption8fe2343

lines 4–5why, one step back
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.

Rename `index` to `fdNumber` (#862)ehmickybefore adoption295ef40

line 6why, one step back
6export const waitForStream = async (stream, fdNumber, streamInfo, {isSameDirection, stopOnExit = false} = {}) => {

Fix race condition with `subprocess.stdin.destroy()` (#904)ehmickybefore adoption588bf16

line 7why, one step back
7 const state = handleStdinDestroy(stream, streamInfo);

Split files (#837)ehmickybefore adoption672c2d7

lines 8–10why, one step back
8 const abortController = new AbortController();
9 try {10 await Promise.race([

Fix race condition with `subprocess.stdin.destroy()` (#904)ehmickybefore adoption588bf16

line 11why, one step back
11 ...(stopOnExit ? [streamInfo.exitPromise] : []),

Split files (#837)ehmickybefore adoption672c2d7

lines 12–14why, one step back
12 finished(stream, {cleanup: true, signal: abortController.signal}),
13 ]);14 } catch (error) {

Fix race condition with `subprocess.stdin.destroy()` (#904)ehmickybefore adoption588bf16

lines 15–17why, one step back
15 if (!state.stdinCleanedUp) {
16 handleStreamError(error, fdNumber, streamInfo, isSameDirection);17 }

Split files (#837)ehmickybefore adoption672c2d7

lines 18–19why, one step back
18 } finally {
19 abortController.abort();

Fix race condition with `subprocess.stdin.destroy()` (#904)ehmickybefore adoption588bf16

lines 20–53why, one step back
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;45 subprocessStdin._destroy = (...args) => {46 setStdinCleanedUp(subprocess, state);47 _destroy.call(subprocessStdin, ...args);48 };49};5051const setStdinCleanedUp = ({exitCode, signalCode}, state) => {52 if (exitCode !== null || signalCode !== null) {53 state.stdinCleanedUp = true;

Split files (#837)ehmickybefore adoption672c2d7

lines 54–60why, one step back
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.

Allow piping process to any file descriptor (#903)ehmickybefore adoption6642cd2

line 61why, one step back
61// Therefore, we keep track of whether a stream error is currently propagating.

Rename `index` to `fdNumber` (#862)ehmickybefore adoption295ef40

lines 62–63why, one step back
62export const handleStreamError = (error, fdNumber, streamInfo, isSameDirection) => {
63 if (!shouldIgnoreStreamError(error, fdNumber, streamInfo, isSameDirection)) {

Split files (#837)ehmickybefore adoption672c2d7

lines 64–67why, one step back
64 throw error;
65 }66};67

Allow piping process to any file descriptor (#903)ehmickybefore adoption6642cd2

lines 68–69why, one step back
68const shouldIgnoreStreamError = (error, fdNumber, streamInfo, isSameDirection = true) => {
69 if (streamInfo.propagating) {

Split files (#837)ehmickybefore adoption672c2d7

lines 70–72why, one step back
70 return isStreamEpipe(error) || isStreamAbort(error);
71 }72

Allow piping process to any file descriptor (#903)ehmickybefore adoption6642cd2

line 73why, one step back
73 streamInfo.propagating = true;

Simplify `lines` option (#929)ehmickybefore adoptiond30fcbc

line 74why, one step back
74 return isInputFileDescriptor(streamInfo, fdNumber) === isSameDirection

Split files (#837)ehmickybefore adoption672c2d7

lines 75–79why, one step back
75 ? 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.

Rename `spawned` and `child process` to `subprocess` (#897)ehmickybefore adoption8fe2343

line 80why, one step back
80// For example, `subprocess.stdin` is technically a Duplex, but can only be used as a writable.

Split files (#837)ehmickybefore adoption672c2d7

line 81why, one step back
81// Therefore, we need to use the file descriptor's direction (`stdin` is input, `stdout` is output, etc.).

Rename `spawned` and `child process` to `subprocess` (#897)ehmickybefore adoption8fe2343

lines 82–83why, one step back
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.

Simplify implementation (#955)ehmickybefore adoption8ad9ee7

line 84why, one step back
84export const isInputFileDescriptor = ({fileDescriptors}, fdNumber) => fileDescriptors[fdNumber].direction === 'input';

Split files (#837)ehmickybefore adoption672c2d7

lines 85–88why, one step back
85
86// 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.

Add `.readable()`, `.writable()` and `.duplex()` methods (#912)ehmickybefore adoption666f7f9

line 89why, one step back
89export const isStreamAbort = error => error?.code === 'ERR_STREAM_PREMATURE_CLOSE';

Split files (#837)ehmickybefore adoption672c2d7

lines 90–91why, one step back
90
91// When `stream.write()` is called but the underlying source has been closed, `EPIPE` is emitted.

Rename `spawned` and `child process` to `subprocess` (#897)ehmickybefore adoption8fe2343

line 92why, one step back
92// When piping subprocesses, the source subprocess usually decides when to stop piping.

Split files (#837)ehmickybefore adoption672c2d7

lines 93–96why, one step back
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';