Skip to content

Commit 31f099b

Browse files
committed
stream: do not detach error listener when stream is already destroyed
When an async iterator runs on a Readable stream with autoDestroy: false that was destroyed before iteration started, finalize() took the detach branch because autoDestroy was false. This called cleanup(), removing the eos error listener before the stream's asynchronous _destroy completed. When _destroy subsequently finished, emitErrorNT emitted an unhandled 'error' event on a stream with no listeners, crashing the process even though the iteration error was caught by the consumer. Allow already-destroyed streams to take the finalize path without prematurely detaching the error listener. Fixes: #67418 Signed-off-by: rudy-07 <kanhaiffco2007@gmail.com>
1 parent 50ce73f commit 31f099b

2 files changed

Lines changed: 29 additions & 1 deletion

File tree

‎lib/internal/streams/readable.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1613,7 +1613,7 @@ function createAsyncIterator(stream, options) {
16131613

16141614
if (
16151615
(error || options?.destroyOnReturn !== false) &&
1616-
(error === undefined || stream._readableState.autoDestroy)
1616+
(error === undefined || stream._readableState.autoDestroy || stream.destroyed)
16171617
) {
16181618
destroyImpl.destroyer(stream, null);
16191619
} else {

‎test/parallel/test-stream-readable-async-iterators.js‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -631,6 +631,34 @@ async function tests() {
631631
assert.strictEqual(r.destroyed, true);
632632
}
633633

634+
{
635+
// An already destroyed stream with autoDestroy: false and an async _destroy
636+
// must not emit an unhandled 'error' event after the iterator finishes.
637+
// Refs: https://github.com/nodejs/node/issues/67418
638+
639+
const stream = new Readable({
640+
read() {},
641+
autoDestroy: false,
642+
destroy(err, cb) {
643+
setTimeout(common.mustCall(() => cb(err)), 10);
644+
},
645+
});
646+
647+
const expectedErr = new Error('stream error');
648+
stream.destroy(expectedErr);
649+
650+
(async () => {
651+
let caught = false;
652+
try {
653+
for await (const chunk of stream) {} // eslint-disable-line no-unused-vars
654+
} catch (err) {
655+
caught = true;
656+
assert.strictEqual(err, expectedErr);
657+
}
658+
assert.strictEqual(caught, true);
659+
})().then(common.mustCall());
660+
}
661+
634662
{
635663
// Don't destroy before 'end'.
636664

0 commit comments

Comments
 (0)