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: read a single stream/iter merge() source without a generator · nodejs/node@e6995cf

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • lib/internal/streams/iter
    • consumers.js
    • utils.js
  • test/parallel
    • test-stream-iter-consumers-merge.js
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎lib/internal/streams/iter/consumers.js‎

Copy file name to clipboardExpand all lines: lib/internal/streams/iter/consumers.js
+104-10Lines changed: 104 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,11 @@ const {
1717
ArrayPrototypeSlice,
1818
FunctionPrototypeCall,
1919
ObjectFreeze,
20+
ObjectSetPrototypeOf,
2021
Promise,
2122
PromisePrototypeThen,
23+
PromiseReject,
24+
PromiseResolve,
2225
SafePromiseAllReturnVoid,
2326
SafeSet,
2427
SuppressedError,
@@ -55,6 +58,7 @@ const {
5558
} = require('internal/streams/iter/from');
5659

5760
const {
61+
IterResult,
5862
kNullOnceOption,
5963
concatBytes,
6064
getProtocolMethod,
@@ -499,6 +503,84 @@ MergeEntry.prototype = ObjectFreeze({ __proto__: null });
499503
* @param {...(AsyncIterable<Uint8Array[]>|object)} args
500504
* @returns {AsyncIterable<Uint8Array[]>}
501505
*/
506+
/**
507+
* The iterator of merge() of a single source without a signal: what an
508+
* async generator doing `for await (const batch of source) yield batch;`
509+
* gives, without its layer for every batch. Calls to next() are passed to
510+
* the source's iterator, from from(), which queues them as an async
511+
* generator does. return() and throw() wait for the last next() before
512+
* closing the source, as the generator would queue them, and later calls
513+
* wait for them in turn. The source is opened by the first next().
514+
*/
515+
class MergeSourceIterator {
516+
#source;
517+
#iterator = null;
518+
// The last next() of the source's iterator, and the promise of return()
519+
// or throw() once one is called.
520+
#last = null;
521+
#closing = null;
522+
523+
constructor(source) {
524+
this.#source = source;
525+
}
526+
527+
next() {
528+
if (this.#closing !== null) {
529+
return PromisePrototypeThen(this.#closing, doneResult, doneResult);
530+
}
531+
try {
532+
this.#iterator ??= this.#source[SymbolAsyncIterator]();
533+
const next = PromiseResolve(this.#iterator.next());
534+
this.#last = next;
535+
return next;
536+
} catch (error) {
537+
this.#closing = PromiseReject(error);
538+
markPromiseAsHandled(this.#closing);
539+
return this.#closing;
540+
}
541+
}
542+
543+
return(value) {
544+
return this.#close(() => new IterResult(true, value), false);
545+
}
546+
547+
throw(error) {
548+
return this.#close(() => { throw error; }, true);
549+
}
550+
551+
// Close the source once the last next() has settled, if it was opened,
552+
// then settle with `settle()`. Errors closing it are ignored if `quiet`,
553+
// as for await ignores them when its body throws.
554+
#close(settle, quiet) {
555+
if (this.#closing !== null) {
556+
return PromisePrototypeThen(this.#closing, settle, settle);
557+
}
558+
const iterator = this.#iterator;
559+
if (iterator === null) {
560+
this.#closing = PromiseResolve();
561+
return PromisePrototypeThen(this.#closing, settle);
562+
}
563+
const close = () => {
564+
const closed = PromiseResolve(iterator.return?.());
565+
return quiet ? PromisePrototypeThen(closed, undefined, () => {}) : closed;
566+
};
567+
const closing = PromisePrototypeThen(this.#last ?? PromiseResolve(),
568+
close, close);
569+
this.#closing = closing;
570+
markPromiseAsHandled(closing);
571+
return PromisePrototypeThen(closing, settle);
572+
}
573+
574+
[SymbolAsyncIterator]() {
575+
return this;
576+
}
577+
}
578+
ObjectSetPrototypeOf(MergeSourceIterator.prototype, null);
579+
580+
function doneResult() {
581+
return new IterResult(true, undefined);
582+
}
583+
502584
function merge(...args) {
503585
let sources;
504586
let options;
@@ -518,6 +600,28 @@ function merge(...args) {
518600
// Normalize each source via from()
519601
const normalized = ArrayPrototypeMap(sources, (source) => from(source));
520602

603+
if (normalized.length === 1) {
604+
// A single source is read without an async generator layer for every
605+
// batch (see MergeSourceIterator). With a signal, the source is read through
606+
// yieldAbortable(), which rejects a pending read when the signal aborts
607+
// (also before the first read), closes the source, and then ends. An
608+
// async iterable is made abortable before from(), so that an abort
609+
// closes it even while from() is reading it.
610+
const { signal } = options;
611+
return {
612+
__proto__: null,
613+
[SymbolAsyncIterator]() {
614+
if (signal === undefined) {
615+
return new MergeSourceIterator(normalized[0]);
616+
}
617+
const source = isAsyncIterable(sources[0]) ?
618+
from(yieldAbortable(sources[0], signal)) :
619+
yieldAbortable(normalized[0], signal);
620+
return source[SymbolAsyncIterator]();
621+
},
622+
};
623+
}
624+
521625
return {
522626
__proto__: null,
523627
async *[SymbolAsyncIterator]() {
@@ -527,16 +631,6 @@ function merge(...args) {
527631

528632
if (normalized.length === 0) return;
529633

530-
if (normalized.length === 1) {
531-
const source = signal !== undefined && isAsyncIterable(sources[0]) ?
532-
from(yieldAbortable(sources[0], signal)) :
533-
yieldAbortable(normalized[0], signal);
534-
for await (const batch of source) {
535-
yield batch;
536-
}
537-
return;
538-
}
539-
540634
// Multiple sources - use a ready queue so that batches that settle
541635
// between consumer pulls are drained synchronously without an extra
542636
// async tick per batch. Each source has at most one pending .next()
Collapse file

‎lib/internal/streams/iter/utils.js‎

Copy file name to clipboardExpand all lines: lib/internal/streams/iter/utils.js
+9-2Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -279,8 +279,8 @@ function yieldAbortable(source, signal) {
279279
* weakly so that the signal does not keep the iterator alive, and each
280280
* next() waits with a single promise that an abort rejects. As with the
281281
* generator:
282-
* - the source is opened by the first next(), and calls made while one is in
283-
* progress are queued;
282+
* - the source is opened by the first next(), unless the signal has aborted
283+
* by then, and calls made while one is in progress are queued;
284284
* - an abort before or while reading a value, or once it has been read,
285285
* rejects with the abort reason;
286286
* - unless the source has ended, an error (including an abort) closes it:
@@ -390,6 +390,13 @@ function createAbortableIterator(source, signal) {
390390
return PromiseResolve(new IterResult(true, undefined));
391391
}
392392
if (state === kStart) {
393+
// An abort before the first read ends the iteration without opening
394+
// the source.
395+
if (signal.aborted) {
396+
state = kDone;
397+
operations.settled();
398+
return PromiseReject(signal.reason);
399+
}
393400
try {
394401
iterator = source[SymbolAsyncIterator]();
395402
} catch (error) {
Collapse file

‎test/parallel/test-stream-iter-consumers-merge.js‎

Copy file name to clipboardExpand all lines: test/parallel/test-stream-iter-consumers-merge.js
+72Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -461,7 +461,79 @@ async function testMergeMultiSourceBreakWithCleanupError() {
461461
);
462462
}
463463

464+
// merge() of a single source behaves as an async generator reading it:
465+
// an abort rejects the pending read, closes the source and ends the
466+
// iteration; an abort before the first read does not open the source;
467+
// return() is queued behind pending reads.
468+
async function testMergeSingleSourceProtocol() {
469+
const log = [];
470+
function source(name, values, { hang = false } = {}) {
471+
let i = 0;
472+
return {
473+
[Symbol.asyncIterator]() {
474+
log.push(`${name} iterator`);
475+
return {
476+
next() {
477+
log.push(`${name} next ${i}`);
478+
if (hang && i === values.length) return new Promise(() => {});
479+
return Promise.resolve(i < values.length ?
480+
{ done: false, value: values[i++] } : { done: true });
481+
},
482+
return() {
483+
log.push(`${name} return`);
484+
return Promise.resolve({ done: true });
485+
},
486+
};
487+
},
488+
};
489+
}
490+
491+
async function settle(label, promise) {
492+
try {
493+
const result = await promise;
494+
log.push(`${label}: ${result.done ? 'done' : result.value[0][0]}`);
495+
} catch (error) {
496+
log.push(`${label}: ${error.name}`);
497+
}
498+
}
499+
const chunk = (n) => [Uint8Array.of(n)];
500+
501+
const aborted = AbortSignal.abort();
502+
let it = merge(source('a', [chunk(1)]), { signal: aborted })[
503+
Symbol.asyncIterator]();
504+
await settle('a 1', it.next());
505+
await settle('a 2', it.next());
506+
507+
const ac = new AbortController();
508+
it = merge(source('b', [chunk(1)], { hang: true }), { signal: ac.signal })[
509+
Symbol.asyncIterator]();
510+
await settle('b 1', it.next());
511+
const pending = it.next();
512+
await setImmediate();
513+
ac.abort();
514+
await settle('b 2', pending);
515+
await settle('b 3', it.next());
516+
517+
it = merge(source('c', [chunk(1), 'x', chunk(3)]))[Symbol.asyncIterator]();
518+
const results = [it.next(), it.next(), it.return(), it.next()];
519+
for (let i = 0; i < results.length; i++) await settle(`c ${i}`, results[i]);
520+
521+
it = merge(source('d', [chunk(1)]))[Symbol.asyncIterator]();
522+
await settle('d return', it.return());
523+
await assert.rejects(it.throw(new Error('thrown')), { message: 'thrown' });
524+
525+
assert.deepStrictEqual(log, [
526+
'a 1: AbortError', 'a 2: done',
527+
'b iterator', 'b next 0', 'b 1: 1', 'b next 1', 'b return',
528+
'b 2: AbortError', 'b 3: done',
529+
'c iterator', 'c next 0', 'c next 1', 'c 0: 1', 'c 1: 120', 'c return',
530+
'c 2: done', 'c 3: done',
531+
'd return: done',
532+
]);
533+
}
534+
464535
Promise.all([
536+
testMergeSingleSourceProtocol(),
465537
testMergeTwoSources(),
466538
testMergeSingleSource(),
467539
testMergeEmpty(),

0 commit comments

Comments
0 (0)
You are visitor 01402775 — 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.