Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stream: fix pipeline pump #39006

Closed
wants to merge 13 commits into from
47 changes: 38 additions & 9 deletions lib/internal/streams/pipeline.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
const {
ArrayIsArray,
SymbolAsyncIterator,
Promise,
ronag marked this conversation as resolved.
Show resolved Hide resolved
} = primordials;

let eos;
Expand All @@ -16,18 +17,21 @@ const {
ERR_INVALID_ARG_TYPE,
ERR_INVALID_RETURN_VALUE,
ERR_MISSING_ARGS,
ronag marked this conversation as resolved.
Show resolved Hide resolved
ERR_STREAM_DESTROYED
ERR_STREAM_DESTROYED,
ERR_STREAM_PREMATURE_CLOSE
ronag marked this conversation as resolved.
Show resolved Hide resolved
} = require('internal/errors').codes;

const { validateCallback } = require('internal/validators');

function noop() {}

const {
isIterable,
isReadable,
isStream,
} = require('internal/streams/utils');
const assert = require('internal/assert');

let EE;
let PassThrough;
let Readable;

Expand Down Expand Up @@ -102,25 +106,50 @@ async function* fromReadable(val) {
}

async function pump(iterable, writable, finish) {
if (!EE) {
EE = require('events');
}
let error;
let callback = noop;
const resume = (err) => {
error ||= err;
aduh95 marked this conversation as resolved.
Show resolved Hide resolved
const _callback = callback;
callback = noop;
_callback();
};
const onClose = () => {
resume(new ERR_STREAM_PREMATURE_CLOSE());
};

const waitForDrain = () => new Promise((resolve) => {
ronag marked this conversation as resolved.
Show resolved Hide resolved
assert(callback === noop);
ronag marked this conversation as resolved.
Show resolved Hide resolved
if (error || writable.destroyed) {
resolve();
} else {
callback = resolve;
}
});

writable
.on('drain', resume)
.on('error', resume)
.on('close', onClose);

try {
if (writable.writableNeedDrain === true) {
await EE.once(writable, 'drain');
if (writable.writableNeedDrain) {
await waitForDrain();
}

for await (const chunk of iterable) {
if (!writable.write(chunk)) {
if (writable.destroyed) return;
await EE.once(writable, 'drain');
await waitForDrain();
}
}
writable.end();
} catch (err) {
error = err;
ronag marked this conversation as resolved.
Show resolved Hide resolved
} finally {
writable
.off('drain', resume)
.off('error', resume)
.off('close', onClose);
finish(error);
}
}
Expand Down