stream: avoid duplicated endReadableNT scheduling

Calling read() on an ended stream multiple times before the microtask
queue drains scheduled one endReadableNT tick per call, as the only
guard was endEmitted, which is set inside the tick itself. A hello-world
HTTP server was scheduling it four times per request while dumping the
unread request body.

Introduce a kEndScheduled flag armed when the tick is scheduled and
cleared when it runs. Clearing it unconditionally matters for reused
sockets: undestroy() resets endEmitted through the state descriptors
but cannot reach this flag, and a stale value would block the 'end'
event after a net.Socket reconnect.

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: https://github.com/nodejs/node/pull/65310
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
Reviewed-By: Paolo Insogna <paolo@cowtech.it>
This commit is contained in:
Matteo Collina authored and Antoine du Hamel committed 2026-09-07 11:53:57 +02:00
1 parent a98e27f2a9
commit 4ec4fab367
1 file changed
+9 -2
+9 -2
View File
@@ -130,6 +130,7 @@ const kFlowing = 1 << 24;
const kHasPaused = 1 << 25;
const kPaused = 1 << 26;
const kDataListening = 1 << 27;
const kEndScheduled = 1 << 28;
// TODO(benjamingr) it is likely slower to do it this way than with free functions
function makeBitMapDescriptor(bit) {
@@ -1742,8 +1743,8 @@ function endReadable(stream) {
const state = stream._readableState;
debug('endReadable');
if ((state[kState] & kEndEmitted) === 0) {
state[kState] |= kEnded;
if ((state[kState] & (kEndEmitted | kEndScheduled)) === 0) {
state[kState] |= kEnded | kEndScheduled;
process.nextTick(endReadableNT, state, stream);
}
}
@@ -1751,6 +1752,12 @@ function endReadable(stream) {
function endReadableNT(state, stream) {
debug('endReadableNT');
// The scheduled tick is running; allow endReadable() to schedule again.
// This matters both when the 'end' emission is skipped below (e.g. after
// an unshift()) and when the stream is later reset for reuse
// (see undestroy()), which clears kEndEmitted but not this flag.
state[kState] &= ~kEndScheduled;
// Check that we didn't get one last unshift.
if ((state[kState] & (kErrored | kCloseEmitted | kEndEmitted)) === 0 && state.length === 0) {
state[kState] |= kEndEmitted;