Skip to content

Commit

Permalink
stream: avoid premature close when will not emit close
Browse files Browse the repository at this point in the history
Fixes: nodejs#45281
PR-URL: nodejs#45301
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Reviewed-By: Minwoo Jung <nodecorelab@gmail.com>
  • Loading branch information
ronag authored and marco-ippolito committed Nov 23, 2022
1 parent b0f822e commit d8d0102
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
20 changes: 16 additions & 4 deletions lib/internal/streams/end-of-stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,18 @@ function eos(stream, options, callback) {
callback.call(stream);
};

const onclosed = () => {
closed = true;

const errored = isWritableErrored(stream) || isReadableErrored(stream);

if (errored && typeof errored !== 'boolean') {
return callback.call(stream, errored);
}

callback.call(stream);
};

const onrequest = () => {
stream.req.on('finish', onfinish);
};
Expand Down Expand Up @@ -186,22 +198,22 @@ function eos(stream, options, callback) {
process.nextTick(onclose);
} else if (wState?.errorEmitted || rState?.errorEmitted) {
if (!willEmitClose) {
process.nextTick(onclose);
process.nextTick(onclosed);
}
} else if (
!readable &&
(!willEmitClose || isReadable(stream)) &&
(writableFinished || isWritable(stream) === false)
) {
process.nextTick(onclose);
process.nextTick(onclosed);
} else if (
!writable &&
(!willEmitClose || isWritable(stream)) &&
(readableFinished || isReadable(stream) === false)
) {
process.nextTick(onclose);
process.nextTick(onclosed);
} else if ((rState && stream.req && stream.aborted)) {
process.nextTick(onclose);
process.nextTick(onclosed);
}

const cleanup = () => {
Expand Down
14 changes: 14 additions & 0 deletions test/parallel/test-stream-finished.js
Original file line number Diff line number Diff line change
Expand Up @@ -667,3 +667,17 @@ testClosed((opts) => new Writable({ write() {}, ...opts }));
).end();
});
}

{
const stream = new Duplex({
write(chunk, enc, cb) {
setImmediate(cb);
}
});

stream.end('foo');

finished(stream, { readable: false }, common.mustCall((err) => {
assert(!err);
}));
}

0 comments on commit d8d0102

Please sign in to comment.