GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — stream: more iter streams fixes by jasnell · Pull Request #66030 · nodejs/node

stream: more iter streams fixes #66030

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.

Sign up for GitHub

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

Closed
jasnell wants to merge 7 commits into nodejs:main from jasnell:jasnell/moar-iter-streams-2

Uh oh!

There was an error while loading. Please reload this page.

Closed

stream: more iter streams fixes #66030

Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
7 commits
Select commit Hold shift + click to select a range
37bec3d
stream: ensure nested async iterators are cancellation aware
jasnell Aug 30, 2026
4acd6f1
stream: make broadcast waiters use SafeSet
jasnell Aug 30, 2026
00f4652
stream: ensure protocol and transform accessors are called once
jasnell Aug 30, 2026
8cc140e
stream: have broadcast clean factory listeners on cancel
jasnell Aug 30, 2026
efc2f37
stream: ensure streamable protocols precede array/validated-source fa…
jasnell Aug 30, 2026
a409c52
stream: make Broadcast.from() only return the Broadcast
jasnell Aug 30, 2026
d0ff99c
stream: update ShareImpl to retain factory abort listener
jasnell Sep 17, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view
Prev Previous commit
Next Next commit
stream: have broadcast clean factory listeners on cancel
Signed-off-by: James M Snell <[email protected]>
Assisted-by: Opencode
  • Loading branch information

Uh oh!

There was an error while loading. Please reload this page.

@jasnell
jasnell committed Sep 17, 2026
commit 8cc140e49e01c77ae62851911787abbedce0b0db

There are no files selected for viewing

23 changes: 18 additions & 5 deletions 23 lib/internal/streams/iter/broadcast.js
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ const kOnEndDrained = Symbol('kOnEndDrained');
const kOnCancel = Symbol('kOnCancel');
const kPendingWriteRemoved = Symbol('kPendingWriteRemoved');
const kNoBroadcastError = Symbol('kNoBroadcastError');
const kSetFactorySignal = Symbol('kSetFactorySignal');

function raceEndWithSignal(promise, signal) {
if (!signal) return promise;
Expand Down Expand Up @@ -120,6 +121,7 @@ class BroadcastImpl {
#writer = null;
#cachedMinCursor = 0;
#cachedMinCursorConsumers = 0;
#abortHandler;
/** Cumulative byte size of buffered entries */
#bufferedBytes = 0;

Expand All @@ -134,6 +136,11 @@ class BroadcastImpl {
this.#writer = writer;
}

[kSetFactorySignal](signal) {
this.#abortHandler = () => this.cancel(signal.reason);
onSignalAbort(signal, this.#abortHandler);
}

get backpressurePolicy() {
return this.#options.backpressure;
}
Expand Down Expand Up @@ -317,6 +324,7 @@ class BroadcastImpl {
this.#consumers.clear();
this.#waiters.clear();
this.#cachedMinCursorConsumers = 0;
this.#cleanupFactorySignal();
const onCancel = this[kOnCancel];
this[kOnCancel] = null;
onCancel?.(reason);
Expand Down Expand Up @@ -428,6 +436,7 @@ class BroadcastImpl {
this.#consumers.clear();
this.#waiters.clear();
this.#cachedMinCursorConsumers = 0;
this.#cleanupFactorySignal();
}

/**
Expand All @@ -447,10 +456,18 @@ class BroadcastImpl {

#notifyEndDrained() {
if (this.#ended && this.#consumers.size === 0) {
this.#cleanupFactorySignal();
this[kOnEndDrained]?.();
}
}

#cleanupFactorySignal() {
if (this.#abortHandler !== undefined) {
this.#options.signal.removeEventListener('abort', this.#abortHandler);
this.#abortHandler = undefined;
}
}

#recomputeMinCursor() {
const { minCursor, minCursorConsumers } = getMinCursor(
this.#consumers, this.#bufferStart + this.#buffer.length);
Expand Down Expand Up @@ -857,10 +874,6 @@ function wireBroadcastWriteSignal(entry, signal, resolve, reject, self) {
signal.addEventListener('abort', onAbort, { __proto__: null, once: true });
}

function onBroadcastCancel(broadcastImpl, signal) {
onSignalAbort(signal, () => broadcastImpl.cancel(signal.reason));
}

// =============================================================================
// Public API
// =============================================================================
Expand Down Expand Up @@ -894,7 +907,7 @@ function broadcast(options = { __proto__: null }) {
broadcastImpl.setWriter(writer);

if (signal) {
onBroadcastCancel(broadcastImpl, signal);
broadcastImpl[kSetFactorySignal](signal);
}

return { __proto__: null, writer, broadcast: broadcastImpl };
Expand Down
41 changes: 26 additions & 15 deletions 41 lib/internal/streams/iter/duplex.js
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,10 @@ function duplex(options = { __proto__: null }) {
backpressure: b?.backpressure ?? backpressure,
});

const channelA = createDuplexChannel(aWriter, aReadable);
const channelB = createDuplexChannel(bWriter, bReadable);
let cleanupSignal;
const onClose = () => cleanupSignal?.();
const channelA = createDuplexChannel(aWriter, aReadable, onClose);
const channelB = createDuplexChannel(bWriter, bReadable, onClose);

// Signal handler: fail both writers with the abort reason so consumers
// see the error. This is an error-path shutdown, not a clean close.
Expand All @@ -55,6 +57,11 @@ function duplex(options = { __proto__: null }) {
const reason = signal.reason;
aWriter.fail(reason);
bWriter.fail(reason);
cleanupSignal?.();
};
cleanupSignal = () => {
signal.removeEventListener('abort', abortBoth);
cleanupSignal = undefined;
};
if (signal.aborted) {
abortBoth();
Expand All @@ -67,7 +74,7 @@ function duplex(options = { __proto__: null }) {
return [channelA, channelB];
}

function createDuplexChannel(writer, readable) {
function createDuplexChannel(writer, readable, onClose) {
// A push readable has one shared consumer state. Keeping an iterator from
// creation lets close() terminate that state even if no caller has iterated.
const closeIterator = readable[SymbolAsyncIterator]();
Expand All @@ -78,7 +85,7 @@ function createDuplexChannel(writer, readable) {
get writer() { return writer; },
get readable() { return readable; },
close() {
closePromise ??= closeDuplexChannel(writer, closeIterator);
closePromise ??= closeDuplexChannel(writer, closeIterator, onClose);
return closePromise;
},
[SymbolAsyncDispose]() {
Expand All @@ -87,19 +94,23 @@ function createDuplexChannel(writer, readable) {
};
}

async function closeDuplexChannel(writer, closeIterator) {
const result = writer.endSync();
const endPromise = result < 0 ? writer.end() : undefined;
const returnPromise = closeIterator.return();
async function closeDuplexChannel(writer, closeIterator, onClose) {
try {
const result = writer.endSync();
const endPromise = result < 0 ? writer.end() : undefined;
const returnPromise = closeIterator.return();

if (endPromise !== undefined) {
try {
await SafePromiseAllReturnVoid([endPromise, returnPromise]);
} catch (error) {
if (!isConsumerReturnError(error)) throw error;
if (endPromise !== undefined) {
try {
await SafePromiseAllReturnVoid([endPromise, returnPromise]);
} catch (error) {
if (!isConsumerReturnError(error)) throw error;
}
} else {
await returnPromise;
}
} else {
await returnPromise;
} finally {
onClose();
}
}

Expand Down
22 changes: 17 additions & 5 deletions 22 lib/internal/streams/iter/share.js
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ const {

const kNoShareError = Symbol('kNoShareError');
const kShareCancelled = Symbol('kShareCancelled');
const kSetFactorySignal = Symbol('kSetFactorySignal');

class ShareImpl {
#source;
Expand All @@ -89,6 +90,7 @@ class ShareImpl {
#cancelError = kNoShareError;
#cachedMinCursor = 0;
#cachedMinCursorConsumers = 0;
#abortHandler;
/** Cumulative byte size of buffered entries */
#bufferedBytes = 0;

Expand All @@ -104,6 +106,11 @@ class ShareImpl {
return this.#consumers.size;
}

[kSetFactorySignal](signal) {
this.#abortHandler = () => this.cancel(signal.reason);
onSignalAbort(signal, this.#abortHandler);
}

pull(...args) {
const parsed = parsePullArgs(args);
const { transforms } = parsed;
Expand Down Expand Up @@ -303,6 +310,7 @@ class ShareImpl {
this.#consumers.clear();
this.#buffer.clear();
this.#bufferedBytes = 0;
this.#cleanupFactorySignal();

for (let i = 0; i < this.#pullWaiters.length; i++) {
this.#pullWaiters[i]();
Expand Down Expand Up @@ -424,6 +432,7 @@ class ShareImpl {
this.#sourceError = error;
this.#sourceExhausted = true;
} finally {
if (this.#sourceExhausted) this.#cleanupFactorySignal();
Comment thread
jasnell marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

this.#pulling = false;
for (let i = 0; i < this.#pullWaiters.length; i++) {
this.#pullWaiters[i]();
Expand Down Expand Up @@ -470,6 +479,13 @@ class ShareImpl {
this.#cachedMinCursorConsumers = minCursorConsumers;
}

#cleanupFactorySignal() {
if (this.#abortHandler !== undefined) {
this.#options.signal.removeEventListener('abort', this.#abortHandler);
this.#abortHandler = undefined;
}
}

#deleteConsumerFromMin(consumer) {
if (consumer.cursor === this.#cachedMinCursor) {
this.#cachedMinCursorConsumers--;
Expand Down Expand Up @@ -768,10 +784,6 @@ class SyncShareImpl {
}
}

function onShareCancel(shareImpl, signal) {
onSignalAbort(signal, () => shareImpl.cancel(signal.reason));
}

// =============================================================================
// Public API
// =============================================================================
Expand Down Expand Up @@ -800,7 +812,7 @@ function share(source, options = { __proto__: null }) {
const shareImpl = new ShareImpl(normalized, opts);

if (signal) {
onShareCancel(shareImpl, signal);
shareImpl[kSetFactorySignal](signal);
}

return shareImpl;
Expand Down
84 changes: 84 additions & 0 deletions 84 test/parallel/test-stream-iter-factory-signal.js
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// Flags: --experimental-stream-iter
'use strict';

const common = require('../common');
const assert = require('assert');
const { getEventListeners } = require('events');
const {
broadcast,
duplex,
push,
share,
text,
} = require('stream/iter');

function abortListenerCount(signal) {
return getEventListeners(signal, 'abort').length;
}

async function testPushSignalLifetime() {
const controller = new AbortController();
const { writer, readable } = push({ signal: controller.signal });
const iterator = readable[Symbol.asyncIterator]();

assert.strictEqual(abortListenerCount(controller.signal), 1);
assert.strictEqual(writer.writeSync('x'), true);
const ending = writer.end();
assert.strictEqual(abortListenerCount(controller.signal), 1);

assert.strictEqual((await iterator.next()).done, false);
assert.strictEqual((await iterator.next()).done, true);
assert.strictEqual(await ending, 1);
assert.strictEqual(abortListenerCount(controller.signal), 0);
}

async function testBroadcastSignalLifetime() {
const controller = new AbortController();
const { writer, broadcast: shared } = broadcast({
signal: controller.signal,
});
const iterator = shared.push()[Symbol.asyncIterator]();

assert.strictEqual(abortListenerCount(controller.signal), 1);
assert.strictEqual(writer.writeSync('x'), true);
const ending = writer.end();
assert.strictEqual(abortListenerCount(controller.signal), 1);

assert.strictEqual((await iterator.next()).done, false);
assert.strictEqual((await iterator.next()).done, true);
assert.strictEqual(await ending, 1);
assert.strictEqual(abortListenerCount(controller.signal), 0);
}

async function testShareSignalLifetime() {
const controller = new AbortController();
const shared = share('x', { signal: controller.signal });
const iterator = shared.pull()[Symbol.asyncIterator]();

assert.strictEqual(abortListenerCount(controller.signal), 1);
assert.strictEqual((await iterator.next()).done, false);
assert.strictEqual(abortListenerCount(controller.signal), 1);
assert.strictEqual((await iterator.next()).done, true);
assert.strictEqual(abortListenerCount(controller.signal), 0);
}

async function testDuplexSignalLifetime() {
const controller = new AbortController();
const [channelA, channelB] = duplex({ signal: controller.signal });

assert.strictEqual(abortListenerCount(controller.signal), 1);
await channelA.writer.write('x');
const closing = channelA.close();
assert.strictEqual(abortListenerCount(controller.signal), 1);

assert.strictEqual(await text(channelB.readable), 'x');
await closing;
assert.strictEqual(abortListenerCount(controller.signal), 0);
}

Promise.all([
testPushSignalLifetime(),
testBroadcastSignalLifetime(),
testShareSignalLifetime(),
testDuplexSignalLifetime(),
]).then(common.mustCall());
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.