Skip to content

Commit 03a2cbc

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 03a2cbc

2 files changed

Lines changed: 24 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: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -631,6 +631,29 @@ 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(() => cb(err), 10);
644+
},
645+
});
646+
647+
const expectedErr = new Error('stream error');
648+
stream.destroy(expectedErr);
649+
650+
await assert.rejects(async () => {
651+
for await (const chunk of stream) {
652+
assert.fail(`unexpected chunk: ${chunk}`);
653+
}
654+
}, expectedErr);
655+
}
656+
634657
{
635658
// Don't destroy before 'end'.
636659

0 commit comments

Comments
 (0)