Commit 5edffb5

Browse files
mcollinaaduh95
authored andcommitted
stream: speed up async iteration of Readable
Replace the async generator backing Symbol.asyncIterator with a hand-rolled iterator. The generator machinery costs several extra promise allocations and microtask hops per chunk: yield awaits the yielded value and resolves the pending request through separate promises. Buffered chunks are now delivered as an already-resolved promise, one microtask sooner than before. Thenable chunks are still awaited before delivery, requests received while a next() is outstanding are queued, and return()/throw() before the first next() complete the iterator without touching the stream. The earlier delivery is observable by code racing an abort against the first chunk. The flatMap AbortSignal test relied on such a race; it is reworked to abort deterministically while two mappers are in flight, asserting the concurrency limit, in-flight cancellation and rejection, without depending on delivery timing or timers. streams/readable-async-iterator.js sync='yes': +32.59% (***) streams/readable-async-iterator.js sync='no': +9.84% (***) Assisted-by: Claude Fable 5 Signed-off-by: Matteo Collina <matteo.collina@gmail.com> PR-URL: #64447 Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day> Reviewed-By: Mattias Buelens <mattias@buelens.com> Reviewed-By: Robert Nagy <ronagy@icloud.com>
1 parent 6302168 commit 5edffb5

3 files changed

Lines changed: 351 additions & 35 deletions

File tree

β€Žlib/internal/streams/readable.jsβ€Ž

Lines changed: 215 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,18 @@
2323

2424
const{
2525
ArrayPrototypeIndexOf,
26+
AsyncIteratorPrototype,
27+
FunctionPrototypeCall,
2628
NumberIsInteger,
2729
NumberIsNaN,
2830
NumberParseInt,
2931
ObjectDefineProperties,
3032
ObjectKeys,
3133
ObjectSetPrototypeOf,
3234
Promise,
35+
PromisePrototypeThen,
36+
PromiseReject,
37+
PromiseResolve,
3338
ReflectApply,
3439
SafeSet,
3540
Symbol,
@@ -100,6 +105,7 @@ const FastBuffer = Buffer[SymbolSpecies];
100105

101106
const{ StringDecoder }=require('string_decoder');
102107
constfrom=require('internal/streams/from');
108+
constFixedQueue=require('internal/fixed_queue');
103109

104110
ObjectSetPrototypeOf(Readable.prototype,Stream.prototype);
105111
ObjectSetPrototypeOf(Readable,Stream);
@@ -1386,10 +1392,22 @@ function streamToAsyncIterator(stream, options) {
13861392
returniter;
13871393
}
13881394

1389-
asyncfunction*createAsyncIterator(stream,options){
1395+
// Async iterator over a Readable. Requests received while another is
1396+
// outstanding are queued and processed in order.
1397+
functioncreateAsyncIterator(stream,options){
13901398
letcallback=nop;
1391-
1392-
functionnext(resolve){
1399+
leterror;// undefined: active, null: ended cleanly, else: Error
1400+
letstarted=false;
1401+
letcompleted=false;
1402+
letinFlight=false;// An asynchronous request is outstanding
1403+
letqueue=null;// Requests received while inFlight
1404+
letdraining=false;
1405+
letcleanup;
1406+
1407+
// Used both as the 'readable' listener (where `this === stream`) and
1408+
// as a promise executor storing the resolver that wakes up a pending
1409+
// pump().
1410+
functionwakeup(resolve){
13931411
if(this===stream){
13941412
callback();
13951413
callback=nop;
@@ -1398,32 +1416,23 @@ async function* createAsyncIterator(stream, options) {
13981416
}
13991417
}
14001418

1401-
stream.on('readable',next);
1419+
functionstart(){
1420+
started=true;
14021421

1403-
leterror;
1404-
constcleanup=eos(stream,{writable: false},(err)=>{
1405-
error=err ? aggregateTwoErrors(error,err) : null;
1406-
callback();
1407-
callback=nop;
1408-
});
1422+
stream.on('readable',wakeup);
1423+
1424+
cleanup=eos(stream,{writable: false},(err)=>{
1425+
error=err ? aggregateTwoErrors(error,err) : null;
1426+
callback();
1427+
callback=nop;
1428+
});
1429+
}
1430+
1431+
// Complete the iterator and either destroy the stream or detach
1432+
// from it.
1433+
functionfinalize(){
1434+
completed=true;
14091435

1410-
try{
1411-
while(true){
1412-
constchunk=stream.destroyed ? null : stream.read();
1413-
if(chunk!==null){
1414-
yieldchunk;
1415-
}elseif(error){
1416-
throwerror;
1417-
}elseif(error===null){
1418-
return;
1419-
}else{
1420-
awaitnewPromise(next);
1421-
}
1422-
}
1423-
}catch(err){
1424-
error=aggregateTwoErrors(error,err);
1425-
throwerror;
1426-
}finally{
14271436
constpreserveHalfOpenDuplex=
14281437
error===null&&
14291438
stream.allowHalfOpen===true&&
@@ -1437,10 +1446,188 @@ async function* createAsyncIterator(stream, options) {
14371446
){
14381447
destroyImpl.destroyer(stream,null);
14391448
}else{
1440-
stream.off('readable',next);
1449+
stream.off('readable',wakeup);
14411450
cleanup();
14421451
}
14431452
}
1453+
1454+
functionsettleError(err,reject){
1455+
error=aggregateTwoErrors(error,err);
1456+
finalize();
1457+
reject(error);
1458+
}
1459+
1460+
functiondrain(){
1461+
// Requests settled synchronously call back into drain(); the guard
1462+
// keeps a single loop going instead of recursing once per request.
1463+
if(draining){
1464+
return;
1465+
}
1466+
draining=true;
1467+
try{
1468+
while(!inFlight&&!queue.isEmpty()){
1469+
constreq=queue.shift();
1470+
if(req.type==='next'){
1471+
processNext(req.resolve,req.reject);
1472+
}elseif(req.type==='return'){
1473+
processReturn(req.value,req.resolve);
1474+
}else{
1475+
processThrow(req.value,req.reject);
1476+
}
1477+
}
1478+
}finally{
1479+
draining=false;
1480+
}
1481+
}
1482+
1483+
// Thenable chunks are unwrapped before delivery; a rejection tears
1484+
// down the iterator and the stream.
1485+
functiononChunkFulfilled(value){
1486+
inFlight=false;
1487+
if(queue!==null)drain();
1488+
return{done: false, value };
1489+
}
1490+
1491+
functiononChunkRejected(err){
1492+
inFlight=false;
1493+
error=aggregateTwoErrors(error,err);
1494+
finalize();
1495+
if(queue!==null)drain();
1496+
throwerror;
1497+
}
1498+
1499+
// Runs with inFlight === true; settles the request and hands over to
1500+
// any requests that queued up behind it.
1501+
functionpump(resolve,reject){
1502+
constchunk=stream.destroyed ? null : stream.read();
1503+
if(chunk!==null){
1504+
// Read `then` only once so that a getter cannot observe (or throw
1505+
// on) a second access.
1506+
constthen=chunk.then;
1507+
if(typeofthen==='function'){
1508+
FunctionPrototypeCall(then,chunk,(value)=>{
1509+
inFlight=false;
1510+
resolve({done: false, value });
1511+
if(queue!==null)drain();
1512+
},(err)=>{
1513+
inFlight=false;
1514+
settleError(err,reject);
1515+
if(queue!==null)drain();
1516+
});
1517+
return;
1518+
}
1519+
inFlight=false;
1520+
resolve({done: false,value: chunk});
1521+
if(queue!==null)drain();
1522+
}elseif(error){
1523+
inFlight=false;
1524+
settleError(error,reject);
1525+
if(queue!==null)drain();
1526+
}elseif(error===null){
1527+
inFlight=false;
1528+
finalize();
1529+
resolve({done: true,value: undefined});
1530+
if(queue!==null)drain();
1531+
}else{
1532+
// No data buffered yet; wait for 'readable' or end-of-stream and
1533+
// retry.
1534+
PromisePrototypeThen(newPromise(wakeup),()=>pump(resolve,reject));
1535+
}
1536+
}
1537+
1538+
functionprocessNext(resolve,reject){
1539+
if(completed){
1540+
resolve({done: true,value: undefined});
1541+
return;
1542+
}
1543+
if(!started)start();
1544+
inFlight=true;
1545+
pump(resolve,reject);
1546+
}
1547+
1548+
functionprocessReturn(value,resolve){
1549+
if(!completed){
1550+
if(started){
1551+
finalize();
1552+
}else{
1553+
// Never started: complete without touching the stream.
1554+
completed=true;
1555+
}
1556+
}
1557+
resolve({done: true, value });
1558+
}
1559+
1560+
functionprocessThrow(err,reject){
1561+
if(completed||!started){
1562+
completed=true;
1563+
reject(err);
1564+
return;
1565+
}
1566+
settleError(err,reject);
1567+
}
1568+
1569+
return{
1570+
__proto__: AsyncIteratorPrototype,
1571+
next(){
1572+
if(!inFlight&&!completed){
1573+
if(!started)start();
1574+
// Fast path: a chunk is already buffered.
1575+
constchunk=stream.destroyed ? null : stream.read();
1576+
if(chunk!==null){
1577+
// Read `then` only once so that a getter cannot observe (or
1578+
// throw on) a second access.
1579+
constthen=chunk.then;
1580+
if(typeofthen==='function'){
1581+
inFlight=true;
1582+
returnFunctionPrototypeCall(
1583+
then,chunk,onChunkFulfilled,onChunkRejected);
1584+
}
1585+
returnPromiseResolve({done: false,value: chunk});
1586+
}
1587+
if(error){
1588+
finalize();
1589+
returnPromiseReject(error);
1590+
}
1591+
if(error===null){
1592+
finalize();
1593+
returnPromiseResolve({done: true,value: undefined});
1594+
}
1595+
// No data buffered yet; wait for 'readable' or end-of-stream.
1596+
inFlight=true;
1597+
returnnewPromise((resolve,reject)=>{
1598+
PromisePrototypeThen(newPromise(wakeup),()=>pump(resolve,reject));
1599+
});
1600+
}
1601+
returnnewPromise((resolve,reject)=>{
1602+
if(inFlight){
1603+
queue??=newFixedQueue();
1604+
queue.push({__proto__: null,type: 'next',value: undefined, resolve, reject });
1605+
}else{
1606+
resolve({done: true,value: undefined});
1607+
}
1608+
});
1609+
},
1610+
return(value){
1611+
returnnewPromise((resolve,reject)=>{
1612+
if(inFlight){
1613+
queue??=newFixedQueue();
1614+
queue.push({__proto__: null,type: 'return', value, resolve, reject });
1615+
}else{
1616+
processReturn(value,resolve);
1617+
}
1618+
});
1619+
},
1620+
throw(err){
1621+
returnnewPromise((resolve,reject)=>{
1622+
if(inFlight){
1623+
queue??=newFixedQueue();
1624+
queue.push({__proto__: null,type: 'throw',value: err, resolve, reject });
1625+
}else{
1626+
processThrow(err,reject);
1627+
}
1628+
});
1629+
},
1630+
};
14441631
}
14451632

14461633
letcomposeImpl;

β€Žtest/parallel/test-stream-flatMap.jsβ€Ž

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,23 @@ function oneTo5() {
7272

7373
{
7474
// Concurrency + AbortSignal
75+
// Two mappers are started concurrently and block until their signal
76+
// is aborted. Aborting while both are in flight must cancel them and
77+
// reject the iteration, without ever starting a third mapper.
7578
constac=newAbortController();
76-
conststream=oneTo5().flatMap(common.mustNotCall(async(_,{ signal })=>{
77-
awaitsetTimeout(100,{ signal });
78-
}),{signal: ac.signal,concurrency: 2});
79+
conststream=oneTo5().flatMap(common.mustCall(async(x,{ signal })=>{
80+
if(x===2){
81+
// Both mappers allowed by `concurrency` are now in flight.
82+
ac.abort();
83+
}
84+
const{ promise, reject }=Promise.withResolvers();
85+
if(signal.aborted){
86+
reject(signal.reason);
87+
}
88+
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
89+
// Promise is expected to reject.
90+
awaitpromise;
91+
},2),{signal: ac.signal,concurrency: 2});
7992
// pump
8093
assert.rejects(async()=>{
8194
forawait(constitemofstream){
@@ -85,10 +98,6 @@ function oneTo5() {
8598
},{
8699
name: 'AbortError',
87100
}).then(common.mustCall());
88-
89-
queueMicrotask(()=>{
90-
ac.abort();
91-
});
92101
}
93102

94103
{

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Commit 5edffb5

Browse files
mcollinaaduh95
authored andcommitted
stream: speed up async iteration of Readable
Replace the async generator backing Symbol.asyncIterator with a hand-rolled iterator. The generator machinery costs several extra promise allocations and microtask hops per chunk: yield awaits the yielded value and resolves the pending request through separate promises. Buffered chunks are now delivered as an already-resolved promise, one microtask sooner than before. Thenable chunks are still awaited before delivery, requests received while a next() is outstanding are queued, and return()/throw() before the first next() complete the iterator without touching the stream. The earlier delivery is observable by code racing an abort against the first chunk. The flatMap AbortSignal test relied on such a race; it is reworked to abort deterministically while two mappers are in flight, asserting the concurrency limit, in-flight cancellation and rejection, without depending on delivery timing or timers. streams/readable-async-iterator.js sync='yes': +32.59% (***) streams/readable-async-iterator.js sync='no': +9.84% (***) Assisted-by: Claude Fable 5 Signed-off-by: Matteo Collina <matteo.collina@gmail.com> PR-URL: #64447 Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day> Reviewed-By: Mattias Buelens <mattias@buelens.com> Reviewed-By: Robert Nagy <ronagy@icloud.com>
1 parent 6302168 commit 5edffb5

3 files changed

Lines changed: 351 additions & 35 deletions

File tree

β€Žlib/internal/streams/readable.jsβ€Ž

Lines changed: 215 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,18 @@
2323

2424
const{
2525
ArrayPrototypeIndexOf,
26+
AsyncIteratorPrototype,
27+
FunctionPrototypeCall,
2628
NumberIsInteger,
2729
NumberIsNaN,
2830
NumberParseInt,
2931
ObjectDefineProperties,
3032
ObjectKeys,
3133
ObjectSetPrototypeOf,
3234
Promise,
35+
PromisePrototypeThen,
36+
PromiseReject,
37+
PromiseResolve,
3338
ReflectApply,
3439
SafeSet,
3540
Symbol,
@@ -100,6 +105,7 @@ const FastBuffer = Buffer[SymbolSpecies];
100105

101106
const{ StringDecoder }=require('string_decoder');
102107
constfrom=require('internal/streams/from');
108+
constFixedQueue=require('internal/fixed_queue');
103109

104110
ObjectSetPrototypeOf(Readable.prototype,Stream.prototype);
105111
ObjectSetPrototypeOf(Readable,Stream);
@@ -1386,10 +1392,22 @@ function streamToAsyncIterator(stream, options) {
13861392
returniter;
13871393
}
13881394

1389-
asyncfunction*createAsyncIterator(stream,options){
1395+
// Async iterator over a Readable. Requests received while another is
1396+
// outstanding are queued and processed in order.
1397+
functioncreateAsyncIterator(stream,options){
13901398
letcallback=nop;
1391-
1392-
functionnext(resolve){
1399+
leterror;// undefined: active, null: ended cleanly, else: Error
1400+
letstarted=false;
1401+
letcompleted=false;
1402+
letinFlight=false;// An asynchronous request is outstanding
1403+
letqueue=null;// Requests received while inFlight
1404+
letdraining=false;
1405+
letcleanup;
1406+
1407+
// Used both as the 'readable' listener (where `this === stream`) and
1408+
// as a promise executor storing the resolver that wakes up a pending
1409+
// pump().
1410+
functionwakeup(resolve){
13931411
if(this===stream){
13941412
callback();
13951413
callback=nop;
@@ -1398,32 +1416,23 @@ async function* createAsyncIterator(stream, options) {
13981416
}
13991417
}
14001418

1401-
stream.on('readable',next);
1419+
functionstart(){
1420+
started=true;
14021421

1403-
leterror;
1404-
constcleanup=eos(stream,{writable: false},(err)=>{
1405-
error=err ? aggregateTwoErrors(error,err) : null;
1406-
callback();
1407-
callback=nop;
1408-
});
1422+
stream.on('readable',wakeup);
1423+
1424+
cleanup=eos(stream,{writable: false},(err)=>{
1425+
error=err ? aggregateTwoErrors(error,err) : null;
1426+
callback();
1427+
callback=nop;
1428+
});
1429+
}
1430+
1431+
// Complete the iterator and either destroy the stream or detach
1432+
// from it.
1433+
functionfinalize(){
1434+
completed=true;
14091435

1410-
try{
1411-
while(true){
1412-
constchunk=stream.destroyed ? null : stream.read();
1413-
if(chunk!==null){
1414-
yieldchunk;
1415-
}elseif(error){
1416-
throwerror;
1417-
}elseif(error===null){
1418-
return;
1419-
}else{
1420-
awaitnewPromise(next);
1421-
}
1422-
}
1423-
}catch(err){
1424-
error=aggregateTwoErrors(error,err);
1425-
throwerror;
1426-
}finally{
14271436
constpreserveHalfOpenDuplex=
14281437
error===null&&
14291438
stream.allowHalfOpen===true&&
@@ -1437,10 +1446,188 @@ async function* createAsyncIterator(stream, options) {
14371446
){
14381447
destroyImpl.destroyer(stream,null);
14391448
}else{
1440-
stream.off('readable',next);
1449+
stream.off('readable',wakeup);
14411450
cleanup();
14421451
}
14431452
}
1453+
1454+
functionsettleError(err,reject){
1455+
error=aggregateTwoErrors(error,err);
1456+
finalize();
1457+
reject(error);
1458+
}
1459+
1460+
functiondrain(){
1461+
// Requests settled synchronously call back into drain(); the guard
1462+
// keeps a single loop going instead of recursing once per request.
1463+
if(draining){
1464+
return;
1465+
}
1466+
draining=true;
1467+
try{
1468+
while(!inFlight&&!queue.isEmpty()){
1469+
constreq=queue.shift();
1470+
if(req.type==='next'){
1471+
processNext(req.resolve,req.reject);
1472+
}elseif(req.type==='return'){
1473+
processReturn(req.value,req.resolve);
1474+
}else{
1475+
processThrow(req.value,req.reject);
1476+
}
1477+
}
1478+
}finally{
1479+
draining=false;
1480+
}
1481+
}
1482+
1483+
// Thenable chunks are unwrapped before delivery; a rejection tears
1484+
// down the iterator and the stream.
1485+
functiononChunkFulfilled(value){
1486+
inFlight=false;
1487+
if(queue!==null)drain();
1488+
return{done: false, value };
1489+
}
1490+
1491+
functiononChunkRejected(err){
1492+
inFlight=false;
1493+
error=aggregateTwoErrors(error,err);
1494+
finalize();
1495+
if(queue!==null)drain();
1496+
throwerror;
1497+
}
1498+
1499+
// Runs with inFlight === true; settles the request and hands over to
1500+
// any requests that queued up behind it.
1501+
functionpump(resolve,reject){
1502+
constchunk=stream.destroyed ? null : stream.read();
1503+
if(chunk!==null){
1504+
// Read `then` only once so that a getter cannot observe (or throw
1505+
// on) a second access.
1506+
constthen=chunk.then;
1507+
if(typeofthen==='function'){
1508+
FunctionPrototypeCall(then,chunk,(value)=>{
1509+
inFlight=false;
1510+
resolve({done: false, value });
1511+
if(queue!==null)drain();
1512+
},(err)=>{
1513+
inFlight=false;
1514+
settleError(err,reject);
1515+
if(queue!==null)drain();
1516+
});
1517+
return;
1518+
}
1519+
inFlight=false;
1520+
resolve({done: false,value: chunk});
1521+
if(queue!==null)drain();
1522+
}elseif(error){
1523+
inFlight=false;
1524+
settleError(error,reject);
1525+
if(queue!==null)drain();
1526+
}elseif(error===null){
1527+
inFlight=false;
1528+
finalize();
1529+
resolve({done: true,value: undefined});
1530+
if(queue!==null)drain();
1531+
}else{
1532+
// No data buffered yet; wait for 'readable' or end-of-stream and
1533+
// retry.
1534+
PromisePrototypeThen(newPromise(wakeup),()=>pump(resolve,reject));
1535+
}
1536+
}
1537+
1538+
functionprocessNext(resolve,reject){
1539+
if(completed){
1540+
resolve({done: true,value: undefined});
1541+
return;
1542+
}
1543+
if(!started)start();
1544+
inFlight=true;
1545+
pump(resolve,reject);
1546+
}
1547+
1548+
functionprocessReturn(value,resolve){
1549+
if(!completed){
1550+
if(started){
1551+
finalize();
1552+
}else{
1553+
// Never started: complete without touching the stream.
1554+
completed=true;
1555+
}
1556+
}
1557+
resolve({done: true, value });
1558+
}
1559+
1560+
functionprocessThrow(err,reject){
1561+
if(completed||!started){
1562+
completed=true;
1563+
reject(err);
1564+
return;
1565+
}
1566+
settleError(err,reject);
1567+
}
1568+
1569+
return{
1570+
__proto__: AsyncIteratorPrototype,
1571+
next(){
1572+
if(!inFlight&&!completed){
1573+
if(!started)start();
1574+
// Fast path: a chunk is already buffered.
1575+
constchunk=stream.destroyed ? null : stream.read();
1576+
if(chunk!==null){
1577+
// Read `then` only once so that a getter cannot observe (or
1578+
// throw on) a second access.
1579+
constthen=chunk.then;
1580+
if(typeofthen==='function'){
1581+
inFlight=true;
1582+
returnFunctionPrototypeCall(
1583+
then,chunk,onChunkFulfilled,onChunkRejected);
1584+
}
1585+
returnPromiseResolve({done: false,value: chunk});
1586+
}
1587+
if(error){
1588+
finalize();
1589+
returnPromiseReject(error);
1590+
}
1591+
if(error===null){
1592+
finalize();
1593+
returnPromiseResolve({done: true,value: undefined});
1594+
}
1595+
// No data buffered yet; wait for 'readable' or end-of-stream.
1596+
inFlight=true;
1597+
returnnewPromise((resolve,reject)=>{
1598+
PromisePrototypeThen(newPromise(wakeup),()=>pump(resolve,reject));
1599+
});
1600+
}
1601+
returnnewPromise((resolve,reject)=>{
1602+
if(inFlight){
1603+
queue??=newFixedQueue();
1604+
queue.push({__proto__: null,type: 'next',value: undefined, resolve, reject });
1605+
}else{
1606+
resolve({done: true,value: undefined});
1607+
}
1608+
});
1609+
},
1610+
return(value){
1611+
returnnewPromise((resolve,reject)=>{
1612+
if(inFlight){
1613+
queue??=newFixedQueue();
1614+
queue.push({__proto__: null,type: 'return', value, resolve, reject });
1615+
}else{
1616+
processReturn(value,resolve);
1617+
}
1618+
});
1619+
},
1620+
throw(err){
1621+
returnnewPromise((resolve,reject)=>{
1622+
if(inFlight){
1623+
queue??=newFixedQueue();
1624+
queue.push({__proto__: null,type: 'throw',value: err, resolve, reject });
1625+
}else{
1626+
processThrow(err,reject);
1627+
}
1628+
});
1629+
},
1630+
};
14441631
}
14451632

14461633
letcomposeImpl;

β€Žtest/parallel/test-stream-flatMap.jsβ€Ž

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,23 @@ function oneTo5() {
7272

7373
{
7474
// Concurrency + AbortSignal
75+
// Two mappers are started concurrently and block until their signal
76+
// is aborted. Aborting while both are in flight must cancel them and
77+
// reject the iteration, without ever starting a third mapper.
7578
constac=newAbortController();
76-
conststream=oneTo5().flatMap(common.mustNotCall(async(_,{ signal })=>{
77-
awaitsetTimeout(100,{ signal });
78-
}),{signal: ac.signal,concurrency: 2});
79+
conststream=oneTo5().flatMap(common.mustCall(async(x,{ signal })=>{
80+
if(x===2){
81+
// Both mappers allowed by `concurrency` are now in flight.
82+
ac.abort();
83+
}
84+
const{ promise, reject }=Promise.withResolvers();
85+
if(signal.aborted){
86+
reject(signal.reason);
87+
}
88+
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
89+
// Promise is expected to reject.
90+
awaitpromise;
91+
},2),{signal: ac.signal,concurrency: 2});
7992
// pump
8093
assert.rejects(async()=>{
8194
forawait(constitemofstream){
@@ -85,10 +98,6 @@ function oneTo5() {
8598
},{
8699
name: 'AbortError',
87100
}).then(common.mustCall());
88-
89-
queueMicrotask(()=>{
90-
ac.abort();
91-
});
92101
}
93102

94103
{

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 5edffb5

Browse files
mcollinaaduh95
authored andcommitted
stream: speed up async iteration of Readable
Replace the async generator backing Symbol.asyncIterator with a hand-rolled iterator. The generator machinery costs several extra promise allocations and microtask hops per chunk: yield awaits the yielded value and resolves the pending request through separate promises. Buffered chunks are now delivered as an already-resolved promise, one microtask sooner than before. Thenable chunks are still awaited before delivery, requests received while a next() is outstanding are queued, and return()/throw() before the first next() complete the iterator without touching the stream. The earlier delivery is observable by code racing an abort against the first chunk. The flatMap AbortSignal test relied on such a race; it is reworked to abort deterministically while two mappers are in flight, asserting the concurrency limit, in-flight cancellation and rejection, without depending on delivery timing or timers. streams/readable-async-iterator.js sync='yes': +32.59% (***) streams/readable-async-iterator.js sync='no': +9.84% (***) Assisted-by: Claude Fable 5 Signed-off-by: Matteo Collina <matteo.collina@gmail.com> PR-URL: #64447 Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day> Reviewed-By: Mattias Buelens <mattias@buelens.com> Reviewed-By: Robert Nagy <ronagy@icloud.com>
1 parent 6302168 commit 5edffb5

3 files changed

Lines changed: 351 additions & 35 deletions

File tree

β€Žlib/internal/streams/readable.jsβ€Ž

Lines changed: 215 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,18 @@
2323

2424
const{
2525
ArrayPrototypeIndexOf,
26+
AsyncIteratorPrototype,
27+
FunctionPrototypeCall,
2628
NumberIsInteger,
2729
NumberIsNaN,
2830
NumberParseInt,
2931
ObjectDefineProperties,
3032
ObjectKeys,
3133
ObjectSetPrototypeOf,
3234
Promise,
35+
PromisePrototypeThen,
36+
PromiseReject,
37+
PromiseResolve,
3338
ReflectApply,
3439
SafeSet,
3540
Symbol,
@@ -100,6 +105,7 @@ const FastBuffer = Buffer[SymbolSpecies];
100105

101106
const{ StringDecoder }=require('string_decoder');
102107
constfrom=require('internal/streams/from');
108+
constFixedQueue=require('internal/fixed_queue');
103109

104110
ObjectSetPrototypeOf(Readable.prototype,Stream.prototype);
105111
ObjectSetPrototypeOf(Readable,Stream);
@@ -1386,10 +1392,22 @@ function streamToAsyncIterator(stream, options) {
13861392
returniter;
13871393
}
13881394

1389-
asyncfunction*createAsyncIterator(stream,options){
1395+
// Async iterator over a Readable. Requests received while another is
1396+
// outstanding are queued and processed in order.
1397+
functioncreateAsyncIterator(stream,options){
13901398
letcallback=nop;
1391-
1392-
functionnext(resolve){
1399+
leterror;// undefined: active, null: ended cleanly, else: Error
1400+
letstarted=false;
1401+
letcompleted=false;
1402+
letinFlight=false;// An asynchronous request is outstanding
1403+
letqueue=null;// Requests received while inFlight
1404+
letdraining=false;
1405+
letcleanup;
1406+
1407+
// Used both as the 'readable' listener (where `this === stream`) and
1408+
// as a promise executor storing the resolver that wakes up a pending
1409+
// pump().
1410+
functionwakeup(resolve){
13931411
if(this===stream){
13941412
callback();
13951413
callback=nop;
@@ -1398,32 +1416,23 @@ async function* createAsyncIterator(stream, options) {
13981416
}
13991417
}
14001418

1401-
stream.on('readable',next);
1419+
functionstart(){
1420+
started=true;
14021421

1403-
leterror;
1404-
constcleanup=eos(stream,{writable: false},(err)=>{
1405-
error=err ? aggregateTwoErrors(error,err) : null;
1406-
callback();
1407-
callback=nop;
1408-
});
1422+
stream.on('readable',wakeup);
1423+
1424+
cleanup=eos(stream,{writable: false},(err)=>{
1425+
error=err ? aggregateTwoErrors(error,err) : null;
1426+
callback();
1427+
callback=nop;
1428+
});
1429+
}
1430+
1431+
// Complete the iterator and either destroy the stream or detach
1432+
// from it.
1433+
functionfinalize(){
1434+
completed=true;
14091435

1410-
try{
1411-
while(true){
1412-
constchunk=stream.destroyed ? null : stream.read();
1413-
if(chunk!==null){
1414-
yieldchunk;
1415-
}elseif(error){
1416-
throwerror;
1417-
}elseif(error===null){
1418-
return;
1419-
}else{
1420-
awaitnewPromise(next);
1421-
}
1422-
}
1423-
}catch(err){
1424-
error=aggregateTwoErrors(error,err);
1425-
throwerror;
1426-
}finally{
14271436
constpreserveHalfOpenDuplex=
14281437
error===null&&
14291438
stream.allowHalfOpen===true&&
@@ -1437,10 +1446,188 @@ async function* createAsyncIterator(stream, options) {
14371446
){
14381447
destroyImpl.destroyer(stream,null);
14391448
}else{
1440-
stream.off('readable',next);
1449+
stream.off('readable',wakeup);
14411450
cleanup();
14421451
}
14431452
}
1453+
1454+
functionsettleError(err,reject){
1455+
error=aggregateTwoErrors(error,err);
1456+
finalize();
1457+
reject(error);
1458+
}
1459+
1460+
functiondrain(){
1461+
// Requests settled synchronously call back into drain(); the guard
1462+
// keeps a single loop going instead of recursing once per request.
1463+
if(draining){
1464+
return;
1465+
}
1466+
draining=true;
1467+
try{
1468+
while(!inFlight&&!queue.isEmpty()){
1469+
constreq=queue.shift();
1470+
if(req.type==='next'){
1471+
processNext(req.resolve,req.reject);
1472+
}elseif(req.type==='return'){
1473+
processReturn(req.value,req.resolve);
1474+
}else{
1475+
processThrow(req.value,req.reject);
1476+
}
1477+
}
1478+
}finally{
1479+
draining=false;
1480+
}
1481+
}
1482+
1483+
// Thenable chunks are unwrapped before delivery; a rejection tears
1484+
// down the iterator and the stream.
1485+
functiononChunkFulfilled(value){
1486+
inFlight=false;
1487+
if(queue!==null)drain();
1488+
return{done: false, value };
1489+
}
1490+
1491+
functiononChunkRejected(err){
1492+
inFlight=false;
1493+
error=aggregateTwoErrors(error,err);
1494+
finalize();
1495+
if(queue!==null)drain();
1496+
throwerror;
1497+
}
1498+
1499+
// Runs with inFlight === true; settles the request and hands over to
1500+
// any requests that queued up behind it.
1501+
functionpump(resolve,reject){
1502+
constchunk=stream.destroyed ? null : stream.read();
1503+
if(chunk!==null){
1504+
// Read `then` only once so that a getter cannot observe (or throw
1505+
// on) a second access.
1506+
constthen=chunk.then;
1507+
if(typeofthen==='function'){
1508+
FunctionPrototypeCall(then,chunk,(value)=>{
1509+
inFlight=false;
1510+
resolve({done: false, value });
1511+
if(queue!==null)drain();
1512+
},(err)=>{
1513+
inFlight=false;
1514+
settleError(err,reject);
1515+
if(queue!==null)drain();
1516+
});
1517+
return;
1518+
}
1519+
inFlight=false;
1520+
resolve({done: false,value: chunk});
1521+
if(queue!==null)drain();
1522+
}elseif(error){
1523+
inFlight=false;
1524+
settleError(error,reject);
1525+
if(queue!==null)drain();
1526+
}elseif(error===null){
1527+
inFlight=false;
1528+
finalize();
1529+
resolve({done: true,value: undefined});
1530+
if(queue!==null)drain();
1531+
}else{
1532+
// No data buffered yet; wait for 'readable' or end-of-stream and
1533+
// retry.
1534+
PromisePrototypeThen(newPromise(wakeup),()=>pump(resolve,reject));
1535+
}
1536+
}
1537+
1538+
functionprocessNext(resolve,reject){
1539+
if(completed){
1540+
resolve({done: true,value: undefined});
1541+
return;
1542+
}
1543+
if(!started)start();
1544+
inFlight=true;
1545+
pump(resolve,reject);
1546+
}
1547+
1548+
functionprocessReturn(value,resolve){
1549+
if(!completed){
1550+
if(started){
1551+
finalize();
1552+
}else{
1553+
// Never started: complete without touching the stream.
1554+
completed=true;
1555+
}
1556+
}
1557+
resolve({done: true, value });
1558+
}
1559+
1560+
functionprocessThrow(err,reject){
1561+
if(completed||!started){
1562+
completed=true;
1563+
reject(err);
1564+
return;
1565+
}
1566+
settleError(err,reject);
1567+
}
1568+
1569+
return{
1570+
__proto__: AsyncIteratorPrototype,
1571+
next(){
1572+
if(!inFlight&&!completed){
1573+
if(!started)start();
1574+
// Fast path: a chunk is already buffered.
1575+
constchunk=stream.destroyed ? null : stream.read();
1576+
if(chunk!==null){
1577+
// Read `then` only once so that a getter cannot observe (or
1578+
// throw on) a second access.
1579+
constthen=chunk.then;
1580+
if(typeofthen==='function'){
1581+
inFlight=true;
1582+
returnFunctionPrototypeCall(
1583+
then,chunk,onChunkFulfilled,onChunkRejected);
1584+
}
1585+
returnPromiseResolve({done: false,value: chunk});
1586+
}
1587+
if(error){
1588+
finalize();
1589+
returnPromiseReject(error);
1590+
}
1591+
if(error===null){
1592+
finalize();
1593+
returnPromiseResolve({done: true,value: undefined});
1594+
}
1595+
// No data buffered yet; wait for 'readable' or end-of-stream.
1596+
inFlight=true;
1597+
returnnewPromise((resolve,reject)=>{
1598+
PromisePrototypeThen(newPromise(wakeup),()=>pump(resolve,reject));
1599+
});
1600+
}
1601+
returnnewPromise((resolve,reject)=>{
1602+
if(inFlight){
1603+
queue??=newFixedQueue();
1604+
queue.push({__proto__: null,type: 'next',value: undefined, resolve, reject });
1605+
}else{
1606+
resolve({done: true,value: undefined});
1607+
}
1608+
});
1609+
},
1610+
return(value){
1611+
returnnewPromise((resolve,reject)=>{
1612+
if(inFlight){
1613+
queue??=newFixedQueue();
1614+
queue.push({__proto__: null,type: 'return', value, resolve, reject });
1615+
}else{
1616+
processReturn(value,resolve);
1617+
}
1618+
});
1619+
},
1620+
throw(err){
1621+
returnnewPromise((resolve,reject)=>{
1622+
if(inFlight){
1623+
queue??=newFixedQueue();
1624+
queue.push({__proto__: null,type: 'throw',value: err, resolve, reject });
1625+
}else{
1626+
processThrow(err,reject);
1627+
}
1628+
});
1629+
},
1630+
};
14441631
}
14451632

14461633
letcomposeImpl;

β€Žtest/parallel/test-stream-flatMap.jsβ€Ž

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,23 @@ function oneTo5() {
7272

7373
{
7474
// Concurrency + AbortSignal
75+
// Two mappers are started concurrently and block until their signal
76+
// is aborted. Aborting while both are in flight must cancel them and
77+
// reject the iteration, without ever starting a third mapper.
7578
constac=newAbortController();
76-
conststream=oneTo5().flatMap(common.mustNotCall(async(_,{ signal })=>{
77-
awaitsetTimeout(100,{ signal });
78-
}),{signal: ac.signal,concurrency: 2});
79+
conststream=oneTo5().flatMap(common.mustCall(async(x,{ signal })=>{
80+
if(x===2){
81+
// Both mappers allowed by `concurrency` are now in flight.
82+
ac.abort();
83+
}
84+
const{ promise, reject }=Promise.withResolvers();
85+
if(signal.aborted){
86+
reject(signal.reason);
87+
}
88+
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
89+
// Promise is expected to reject.
90+
awaitpromise;
91+
},2),{signal: ac.signal,concurrency: 2});
7992
// pump
8093
assert.rejects(async()=>{
8194
forawait(constitemofstream){
@@ -85,10 +98,6 @@ function oneTo5() {
8598
},{
8699
name: 'AbortError',
87100
}).then(common.mustCall());
88-
89-
queueMicrotask(()=>{
90-
ac.abort();
91-
});
92101
}
93102

94103
{

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 5edffb5

Browse files
mcollinaaduh95
authored andcommitted
stream: speed up async iteration of Readable
Replace the async generator backing Symbol.asyncIterator with a hand-rolled iterator. The generator machinery costs several extra promise allocations and microtask hops per chunk: yield awaits the yielded value and resolves the pending request through separate promises. Buffered chunks are now delivered as an already-resolved promise, one microtask sooner than before. Thenable chunks are still awaited before delivery, requests received while a next() is outstanding are queued, and return()/throw() before the first next() complete the iterator without touching the stream. The earlier delivery is observable by code racing an abort against the first chunk. The flatMap AbortSignal test relied on such a race; it is reworked to abort deterministically while two mappers are in flight, asserting the concurrency limit, in-flight cancellation and rejection, without depending on delivery timing or timers. streams/readable-async-iterator.js sync='yes': +32.59% (***) streams/readable-async-iterator.js sync='no': +9.84% (***) Assisted-by: Claude Fable 5 Signed-off-by: Matteo Collina <matteo.collina@gmail.com> PR-URL: #64447 Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day> Reviewed-By: Mattias Buelens <mattias@buelens.com> Reviewed-By: Robert Nagy <ronagy@icloud.com>
1 parent 6302168 commit 5edffb5

3 files changed

Lines changed: 351 additions & 35 deletions

File tree

β€Žlib/internal/streams/readable.jsβ€Ž

Lines changed: 215 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,18 @@
2323

2424
const{
2525
ArrayPrototypeIndexOf,
26+
AsyncIteratorPrototype,
27+
FunctionPrototypeCall,
2628
NumberIsInteger,
2729
NumberIsNaN,
2830
NumberParseInt,
2931
ObjectDefineProperties,
3032
ObjectKeys,
3133
ObjectSetPrototypeOf,
3234
Promise,
35+
PromisePrototypeThen,
36+
PromiseReject,
37+
PromiseResolve,
3338
ReflectApply,
3439
SafeSet,
3540
Symbol,
@@ -100,6 +105,7 @@ const FastBuffer = Buffer[SymbolSpecies];
100105

101106
const{ StringDecoder }=require('string_decoder');
102107
constfrom=require('internal/streams/from');
108+
constFixedQueue=require('internal/fixed_queue');
103109

104110
ObjectSetPrototypeOf(Readable.prototype,Stream.prototype);
105111
ObjectSetPrototypeOf(Readable,Stream);
@@ -1386,10 +1392,22 @@ function streamToAsyncIterator(stream, options) {
13861392
returniter;
13871393
}
13881394

1389-
asyncfunction*createAsyncIterator(stream,options){
1395+
// Async iterator over a Readable. Requests received while another is
1396+
// outstanding are queued and processed in order.
1397+
functioncreateAsyncIterator(stream,options){
13901398
letcallback=nop;
1391-
1392-
functionnext(resolve){
1399+
leterror;// undefined: active, null: ended cleanly, else: Error
1400+
letstarted=false;
1401+
letcompleted=false;
1402+
letinFlight=false;// An asynchronous request is outstanding
1403+
letqueue=null;// Requests received while inFlight
1404+
letdraining=false;
1405+
letcleanup;
1406+
1407+
// Used both as the 'readable' listener (where `this === stream`) and
1408+
// as a promise executor storing the resolver that wakes up a pending
1409+
// pump().
1410+
functionwakeup(resolve){
13931411
if(this===stream){
13941412
callback();
13951413
callback=nop;
@@ -1398,32 +1416,23 @@ async function* createAsyncIterator(stream, options) {
13981416
}
13991417
}
14001418

1401-
stream.on('readable',next);
1419+
functionstart(){
1420+
started=true;
14021421

1403-
leterror;
1404-
constcleanup=eos(stream,{writable: false},(err)=>{
1405-
error=err ? aggregateTwoErrors(error,err) : null;
1406-
callback();
1407-
callback=nop;
1408-
});
1422+
stream.on('readable',wakeup);
1423+
1424+
cleanup=eos(stream,{writable: false},(err)=>{
1425+
error=err ? aggregateTwoErrors(error,err) : null;
1426+
callback();
1427+
callback=nop;
1428+
});
1429+
}
1430+
1431+
// Complete the iterator and either destroy the stream or detach
1432+
// from it.
1433+
functionfinalize(){
1434+
completed=true;
14091435

1410-
try{
1411-
while(true){
1412-
constchunk=stream.destroyed ? null : stream.read();
1413-
if(chunk!==null){
1414-
yieldchunk;
1415-
}elseif(error){
1416-
throwerror;
1417-
}elseif(error===null){
1418-
return;
1419-
}else{
1420-
awaitnewPromise(next);
1421-
}
1422-
}
1423-
}catch(err){
1424-
error=aggregateTwoErrors(error,err);
1425-
throwerror;
1426-
}finally{
14271436
constpreserveHalfOpenDuplex=
14281437
error===null&&
14291438
stream.allowHalfOpen===true&&
@@ -1437,10 +1446,188 @@ async function* createAsyncIterator(stream, options) {
14371446
){
14381447
destroyImpl.destroyer(stream,null);
14391448
}else{
1440-
stream.off('readable',next);
1449+
stream.off('readable',wakeup);
14411450
cleanup();
14421451
}
14431452
}
1453+
1454+
functionsettleError(err,reject){
1455+
error=aggregateTwoErrors(error,err);
1456+
finalize();
1457+
reject(error);
1458+
}
1459+
1460+
functiondrain(){
1461+
// Requests settled synchronously call back into drain(); the guard
1462+
// keeps a single loop going instead of recursing once per request.
1463+
if(draining){
1464+
return;
1465+
}
1466+
draining=true;
1467+
try{
1468+
while(!inFlight&&!queue.isEmpty()){
1469+
constreq=queue.shift();
1470+
if(req.type==='next'){
1471+
processNext(req.resolve,req.reject);
1472+
}elseif(req.type==='return'){
1473+
processReturn(req.value,req.resolve);
1474+
}else{
1475+
processThrow(req.value,req.reject);
1476+
}
1477+
}
1478+
}finally{
1479+
draining=false;
1480+
}
1481+
}
1482+
1483+
// Thenable chunks are unwrapped before delivery; a rejection tears
1484+
// down the iterator and the stream.
1485+
functiononChunkFulfilled(value){
1486+
inFlight=false;
1487+
if(queue!==null)drain();
1488+
return{done: false, value };
1489+
}
1490+
1491+
functiononChunkRejected(err){
1492+
inFlight=false;
1493+
error=aggregateTwoErrors(error,err);
1494+
finalize();
1495+
if(queue!==null)drain();
1496+
throwerror;
1497+
}
1498+
1499+
// Runs with inFlight === true; settles the request and hands over to
1500+
// any requests that queued up behind it.
1501+
functionpump(resolve,reject){
1502+
constchunk=stream.destroyed ? null : stream.read();
1503+
if(chunk!==null){
1504+
// Read `then` only once so that a getter cannot observe (or throw
1505+
// on) a second access.
1506+
constthen=chunk.then;
1507+
if(typeofthen==='function'){
1508+
FunctionPrototypeCall(then,chunk,(value)=>{
1509+
inFlight=false;
1510+
resolve({done: false, value });
1511+
if(queue!==null)drain();
1512+
},(err)=>{
1513+
inFlight=false;
1514+
settleError(err,reject);
1515+
if(queue!==null)drain();
1516+
});
1517+
return;
1518+
}
1519+
inFlight=false;
1520+
resolve({done: false,value: chunk});
1521+
if(queue!==null)drain();
1522+
}elseif(error){
1523+
inFlight=false;
1524+
settleError(error,reject);
1525+
if(queue!==null)drain();
1526+
}elseif(error===null){
1527+
inFlight=false;
1528+
finalize();
1529+
resolve({done: true,value: undefined});
1530+
if(queue!==null)drain();
1531+
}else{
1532+
// No data buffered yet; wait for 'readable' or end-of-stream and
1533+
// retry.
1534+
PromisePrototypeThen(newPromise(wakeup),()=>pump(resolve,reject));
1535+
}
1536+
}
1537+
1538+
functionprocessNext(resolve,reject){
1539+
if(completed){
1540+
resolve({done: true,value: undefined});
1541+
return;
1542+
}
1543+
if(!started)start();
1544+
inFlight=true;
1545+
pump(resolve,reject);
1546+
}
1547+
1548+
functionprocessReturn(value,resolve){
1549+
if(!completed){
1550+
if(started){
1551+
finalize();
1552+
}else{
1553+
// Never started: complete without touching the stream.
1554+
completed=true;
1555+
}
1556+
}
1557+
resolve({done: true, value });
1558+
}
1559+
1560+
functionprocessThrow(err,reject){
1561+
if(completed||!started){
1562+
completed=true;
1563+
reject(err);
1564+
return;
1565+
}
1566+
settleError(err,reject);
1567+
}
1568+
1569+
return{
1570+
__proto__: AsyncIteratorPrototype,
1571+
next(){
1572+
if(!inFlight&&!completed){
1573+
if(!started)start();
1574+
// Fast path: a chunk is already buffered.
1575+
constchunk=stream.destroyed ? null : stream.read();
1576+
if(chunk!==null){
1577+
// Read `then` only once so that a getter cannot observe (or
1578+
// throw on) a second access.
1579+
constthen=chunk.then;
1580+
if(typeofthen==='function'){
1581+
inFlight=true;
1582+
returnFunctionPrototypeCall(
1583+
then,chunk,onChunkFulfilled,onChunkRejected);
1584+
}
1585+
returnPromiseResolve({done: false,value: chunk});
1586+
}
1587+
if(error){
1588+
finalize();
1589+
returnPromiseReject(error);
1590+
}
1591+
if(error===null){
1592+
finalize();
1593+
returnPromiseResolve({done: true,value: undefined});
1594+
}
1595+
// No data buffered yet; wait for 'readable' or end-of-stream.
1596+
inFlight=true;
1597+
returnnewPromise((resolve,reject)=>{
1598+
PromisePrototypeThen(newPromise(wakeup),()=>pump(resolve,reject));
1599+
});
1600+
}
1601+
returnnewPromise((resolve,reject)=>{
1602+
if(inFlight){
1603+
queue??=newFixedQueue();
1604+
queue.push({__proto__: null,type: 'next',value: undefined, resolve, reject });
1605+
}else{
1606+
resolve({done: true,value: undefined});
1607+
}
1608+
});
1609+
},
1610+
return(value){
1611+
returnnewPromise((resolve,reject)=>{
1612+
if(inFlight){
1613+
queue??=newFixedQueue();
1614+
queue.push({__proto__: null,type: 'return', value, resolve, reject });
1615+
}else{
1616+
processReturn(value,resolve);
1617+
}
1618+
});
1619+
},
1620+
throw(err){
1621+
returnnewPromise((resolve,reject)=>{
1622+
if(inFlight){
1623+
queue??=newFixedQueue();
1624+
queue.push({__proto__: null,type: 'throw',value: err, resolve, reject });
1625+
}else{
1626+
processThrow(err,reject);
1627+
}
1628+
});
1629+
},
1630+
};
14441631
}
14451632

14461633
letcomposeImpl;

β€Žtest/parallel/test-stream-flatMap.jsβ€Ž

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,23 @@ function oneTo5() {
7272

7373
{
7474
// Concurrency + AbortSignal
75+
// Two mappers are started concurrently and block until their signal
76+
// is aborted. Aborting while both are in flight must cancel them and
77+
// reject the iteration, without ever starting a third mapper.
7578
constac=newAbortController();
76-
conststream=oneTo5().flatMap(common.mustNotCall(async(_,{ signal })=>{
77-
awaitsetTimeout(100,{ signal });
78-
}),{signal: ac.signal,concurrency: 2});
79+
conststream=oneTo5().flatMap(common.mustCall(async(x,{ signal })=>{
80+
if(x===2){
81+
// Both mappers allowed by `concurrency` are now in flight.
82+
ac.abort();
83+
}
84+
const{ promise, reject }=Promise.withResolvers();
85+
if(signal.aborted){
86+
reject(signal.reason);
87+
}
88+
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
89+
// Promise is expected to reject.
90+
awaitpromise;
91+
},2),{signal: ac.signal,concurrency: 2});
7992
// pump
8093
assert.rejects(async()=>{
8194
forawait(constitemofstream){
@@ -85,10 +98,6 @@ function oneTo5() {
8598
},{
8699
name: 'AbortError',
87100
}).then(common.mustCall());
88-
89-
queueMicrotask(()=>{
90-
ac.abort();
91-
});
92101
}
93102

94103
{

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Commit 5edffb5

Browse files
mcollinaaduh95
authored andcommitted
stream: speed up async iteration of Readable
Replace the async generator backing Symbol.asyncIterator with a hand-rolled iterator. The generator machinery costs several extra promise allocations and microtask hops per chunk: yield awaits the yielded value and resolves the pending request through separate promises. Buffered chunks are now delivered as an already-resolved promise, one microtask sooner than before. Thenable chunks are still awaited before delivery, requests received while a next() is outstanding are queued, and return()/throw() before the first next() complete the iterator without touching the stream. The earlier delivery is observable by code racing an abort against the first chunk. The flatMap AbortSignal test relied on such a race; it is reworked to abort deterministically while two mappers are in flight, asserting the concurrency limit, in-flight cancellation and rejection, without depending on delivery timing or timers. streams/readable-async-iterator.js sync='yes': +32.59% (***) streams/readable-async-iterator.js sync='no': +9.84% (***) Assisted-by: Claude Fable 5 Signed-off-by: Matteo Collina <matteo.collina@gmail.com> PR-URL: #64447 Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day> Reviewed-By: Mattias Buelens <mattias@buelens.com> Reviewed-By: Robert Nagy <ronagy@icloud.com>
1 parent 6302168 commit 5edffb5

3 files changed

Lines changed: 351 additions & 35 deletions

File tree

β€Žlib/internal/streams/readable.jsβ€Ž

Lines changed: 215 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,18 @@
2323

2424
const{
2525
ArrayPrototypeIndexOf,
26+
AsyncIteratorPrototype,
27+
FunctionPrototypeCall,
2628
NumberIsInteger,
2729
NumberIsNaN,
2830
NumberParseInt,
2931
ObjectDefineProperties,
3032
ObjectKeys,
3133
ObjectSetPrototypeOf,
3234
Promise,
35+
PromisePrototypeThen,
36+
PromiseReject,
37+
PromiseResolve,
3338
ReflectApply,
3439
SafeSet,
3540
Symbol,
@@ -100,6 +105,7 @@ const FastBuffer = Buffer[SymbolSpecies];
100105

101106
const{ StringDecoder }=require('string_decoder');
102107
constfrom=require('internal/streams/from');
108+
constFixedQueue=require('internal/fixed_queue');
103109

104110
ObjectSetPrototypeOf(Readable.prototype,Stream.prototype);
105111
ObjectSetPrototypeOf(Readable,Stream);
@@ -1386,10 +1392,22 @@ function streamToAsyncIterator(stream, options) {
13861392
returniter;
13871393
}
13881394

1389-
asyncfunction*createAsyncIterator(stream,options){
1395+
// Async iterator over a Readable. Requests received while another is
1396+
// outstanding are queued and processed in order.
1397+
functioncreateAsyncIterator(stream,options){
13901398
letcallback=nop;
1391-
1392-
functionnext(resolve){
1399+
leterror;// undefined: active, null: ended cleanly, else: Error
1400+
letstarted=false;
1401+
letcompleted=false;
1402+
letinFlight=false;// An asynchronous request is outstanding
1403+
letqueue=null;// Requests received while inFlight
1404+
letdraining=false;
1405+
letcleanup;
1406+
1407+
// Used both as the 'readable' listener (where `this === stream`) and
1408+
// as a promise executor storing the resolver that wakes up a pending
1409+
// pump().
1410+
functionwakeup(resolve){
13931411
if(this===stream){
13941412
callback();
13951413
callback=nop;
@@ -1398,32 +1416,23 @@ async function* createAsyncIterator(stream, options) {
13981416
}
13991417
}
14001418

1401-
stream.on('readable',next);
1419+
functionstart(){
1420+
started=true;
14021421

1403-
leterror;
1404-
constcleanup=eos(stream,{writable: false},(err)=>{
1405-
error=err ? aggregateTwoErrors(error,err) : null;
1406-
callback();
1407-
callback=nop;
1408-
});
1422+
stream.on('readable',wakeup);
1423+
1424+
cleanup=eos(stream,{writable: false},(err)=>{
1425+
error=err ? aggregateTwoErrors(error,err) : null;
1426+
callback();
1427+
callback=nop;
1428+
});
1429+
}
1430+
1431+
// Complete the iterator and either destroy the stream or detach
1432+
// from it.
1433+
functionfinalize(){
1434+
completed=true;
14091435

1410-
try{
1411-
while(true){
1412-
constchunk=stream.destroyed ? null : stream.read();
1413-
if(chunk!==null){
1414-
yieldchunk;
1415-
}elseif(error){
1416-
throwerror;
1417-
}elseif(error===null){
1418-
return;
1419-
}else{
1420-
awaitnewPromise(next);
1421-
}
1422-
}
1423-
}catch(err){
1424-
error=aggregateTwoErrors(error,err);
1425-
throwerror;
1426-
}finally{
14271436
constpreserveHalfOpenDuplex=
14281437
error===null&&
14291438
stream.allowHalfOpen===true&&
@@ -1437,10 +1446,188 @@ async function* createAsyncIterator(stream, options) {
14371446
){
14381447
destroyImpl.destroyer(stream,null);
14391448
}else{
1440-
stream.off('readable',next);
1449+
stream.off('readable',wakeup);
14411450
cleanup();
14421451
}
14431452
}
1453+
1454+
functionsettleError(err,reject){
1455+
error=aggregateTwoErrors(error,err);
1456+
finalize();
1457+
reject(error);
1458+
}
1459+
1460+
functiondrain(){
1461+
// Requests settled synchronously call back into drain(); the guard
1462+
// keeps a single loop going instead of recursing once per request.
1463+
if(draining){
1464+
return;
1465+
}
1466+
draining=true;
1467+
try{
1468+
while(!inFlight&&!queue.isEmpty()){
1469+
constreq=queue.shift();
1470+
if(req.type==='next'){
1471+
processNext(req.resolve,req.reject);
1472+
}elseif(req.type==='return'){
1473+
processReturn(req.value,req.resolve);
1474+
}else{
1475+
processThrow(req.value,req.reject);
1476+
}
1477+
}
1478+
}finally{
1479+
draining=false;
1480+
}
1481+
}
1482+
1483+
// Thenable chunks are unwrapped before delivery; a rejection tears
1484+
// down the iterator and the stream.
1485+
functiononChunkFulfilled(value){
1486+
inFlight=false;
1487+
if(queue!==null)drain();
1488+
return{done: false, value };
1489+
}
1490+
1491+
functiononChunkRejected(err){
1492+
inFlight=false;
1493+
error=aggregateTwoErrors(error,err);
1494+
finalize();
1495+
if(queue!==null)drain();
1496+
throwerror;
1497+
}
1498+
1499+
// Runs with inFlight === true; settles the request and hands over to
1500+
// any requests that queued up behind it.
1501+
functionpump(resolve,reject){
1502+
constchunk=stream.destroyed ? null : stream.read();
1503+
if(chunk!==null){
1504+
// Read `then` only once so that a getter cannot observe (or throw
1505+
// on) a second access.
1506+
constthen=chunk.then;
1507+
if(typeofthen==='function'){
1508+
FunctionPrototypeCall(then,chunk,(value)=>{
1509+
inFlight=false;
1510+
resolve({done: false, value });
1511+
if(queue!==null)drain();
1512+
},(err)=>{
1513+
inFlight=false;
1514+
settleError(err,reject);
1515+
if(queue!==null)drain();
1516+
});
1517+
return;
1518+
}
1519+
inFlight=false;
1520+
resolve({done: false,value: chunk});
1521+
if(queue!==null)drain();
1522+
}elseif(error){
1523+
inFlight=false;
1524+
settleError(error,reject);
1525+
if(queue!==null)drain();
1526+
}elseif(error===null){
1527+
inFlight=false;
1528+
finalize();
1529+
resolve({done: true,value: undefined});
1530+
if(queue!==null)drain();
1531+
}else{
1532+
// No data buffered yet; wait for 'readable' or end-of-stream and
1533+
// retry.
1534+
PromisePrototypeThen(newPromise(wakeup),()=>pump(resolve,reject));
1535+
}
1536+
}
1537+
1538+
functionprocessNext(resolve,reject){
1539+
if(completed){
1540+
resolve({done: true,value: undefined});
1541+
return;
1542+
}
1543+
if(!started)start();
1544+
inFlight=true;
1545+
pump(resolve,reject);
1546+
}
1547+
1548+
functionprocessReturn(value,resolve){
1549+
if(!completed){
1550+
if(started){
1551+
finalize();
1552+
}else{
1553+
// Never started: complete without touching the stream.
1554+
completed=true;
1555+
}
1556+
}
1557+
resolve({done: true, value });
1558+
}
1559+
1560+
functionprocessThrow(err,reject){
1561+
if(completed||!started){
1562+
completed=true;
1563+
reject(err);
1564+
return;
1565+
}
1566+
settleError(err,reject);
1567+
}
1568+
1569+
return{
1570+
__proto__: AsyncIteratorPrototype,
1571+
next(){
1572+
if(!inFlight&&!completed){
1573+
if(!started)start();
1574+
// Fast path: a chunk is already buffered.
1575+
constchunk=stream.destroyed ? null : stream.read();
1576+
if(chunk!==null){
1577+
// Read `then` only once so that a getter cannot observe (or
1578+
// throw on) a second access.
1579+
constthen=chunk.then;
1580+
if(typeofthen==='function'){
1581+
inFlight=true;
1582+
returnFunctionPrototypeCall(
1583+
then,chunk,onChunkFulfilled,onChunkRejected);
1584+
}
1585+
returnPromiseResolve({done: false,value: chunk});
1586+
}
1587+
if(error){
1588+
finalize();
1589+
returnPromiseReject(error);
1590+
}
1591+
if(error===null){
1592+
finalize();
1593+
returnPromiseResolve({done: true,value: undefined});
1594+
}
1595+
// No data buffered yet; wait for 'readable' or end-of-stream.
1596+
inFlight=true;
1597+
returnnewPromise((resolve,reject)=>{
1598+
PromisePrototypeThen(newPromise(wakeup),()=>pump(resolve,reject));
1599+
});
1600+
}
1601+
returnnewPromise((resolve,reject)=>{
1602+
if(inFlight){
1603+
queue??=newFixedQueue();
1604+
queue.push({__proto__: null,type: 'next',value: undefined, resolve, reject });
1605+
}else{
1606+
resolve({done: true,value: undefined});
1607+
}
1608+
});
1609+
},
1610+
return(value){
1611+
returnnewPromise((resolve,reject)=>{
1612+
if(inFlight){
1613+
queue??=newFixedQueue();
1614+
queue.push({__proto__: null,type: 'return', value, resolve, reject });
1615+
}else{
1616+
processReturn(value,resolve);
1617+
}
1618+
});
1619+
},
1620+
throw(err){
1621+
returnnewPromise((resolve,reject)=>{
1622+
if(inFlight){
1623+
queue??=newFixedQueue();
1624+
queue.push({__proto__: null,type: 'throw',value: err, resolve, reject });
1625+
}else{
1626+
processThrow(err,reject);
1627+
}
1628+
});
1629+
},
1630+
};
14441631
}
14451632

14461633
letcomposeImpl;

β€Žtest/parallel/test-stream-flatMap.jsβ€Ž

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,23 @@ function oneTo5() {
7272

7373
{
7474
// Concurrency + AbortSignal
75+
// Two mappers are started concurrently and block until their signal
76+
// is aborted. Aborting while both are in flight must cancel them and
77+
// reject the iteration, without ever starting a third mapper.
7578
constac=newAbortController();
76-
conststream=oneTo5().flatMap(common.mustNotCall(async(_,{ signal })=>{
77-
awaitsetTimeout(100,{ signal });
78-
}),{signal: ac.signal,concurrency: 2});
79+
conststream=oneTo5().flatMap(common.mustCall(async(x,{ signal })=>{
80+
if(x===2){
81+
// Both mappers allowed by `concurrency` are now in flight.
82+
ac.abort();
83+
}
84+
const{ promise, reject }=Promise.withResolvers();
85+
if(signal.aborted){
86+
reject(signal.reason);
87+
}
88+
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
89+
// Promise is expected to reject.
90+
awaitpromise;
91+
},2),{signal: ac.signal,concurrency: 2});
7992
// pump
8093
assert.rejects(async()=>{
8194
forawait(constitemofstream){
@@ -85,10 +98,6 @@ function oneTo5() {
8598
},{
8699
name: 'AbortError',
87100
}).then(common.mustCall());
88-
89-
queueMicrotask(()=>{
90-
ac.abort();
91-
});
92101
}
93102

94103
{

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 5edffb5

Browse files
mcollinaaduh95
authored andcommitted
stream: speed up async iteration of Readable
Replace the async generator backing Symbol.asyncIterator with a hand-rolled iterator. The generator machinery costs several extra promise allocations and microtask hops per chunk: yield awaits the yielded value and resolves the pending request through separate promises. Buffered chunks are now delivered as an already-resolved promise, one microtask sooner than before. Thenable chunks are still awaited before delivery, requests received while a next() is outstanding are queued, and return()/throw() before the first next() complete the iterator without touching the stream. The earlier delivery is observable by code racing an abort against the first chunk. The flatMap AbortSignal test relied on such a race; it is reworked to abort deterministically while two mappers are in flight, asserting the concurrency limit, in-flight cancellation and rejection, without depending on delivery timing or timers. streams/readable-async-iterator.js sync='yes': +32.59% (***) streams/readable-async-iterator.js sync='no': +9.84% (***) Assisted-by: Claude Fable 5 Signed-off-by: Matteo Collina <matteo.collina@gmail.com> PR-URL: #64447 Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day> Reviewed-By: Mattias Buelens <mattias@buelens.com> Reviewed-By: Robert Nagy <ronagy@icloud.com>
1 parent 6302168 commit 5edffb5

3 files changed

Lines changed: 351 additions & 35 deletions

File tree

β€Žlib/internal/streams/readable.jsβ€Ž

Lines changed: 215 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,18 @@
2323

2424
const{
2525
ArrayPrototypeIndexOf,
26+
AsyncIteratorPrototype,
27+
FunctionPrototypeCall,
2628
NumberIsInteger,
2729
NumberIsNaN,
2830
NumberParseInt,
2931
ObjectDefineProperties,
3032
ObjectKeys,
3133
ObjectSetPrototypeOf,
3234
Promise,
35+
PromisePrototypeThen,
36+
PromiseReject,
37+
PromiseResolve,
3338
ReflectApply,
3439
SafeSet,
3540
Symbol,
@@ -100,6 +105,7 @@ const FastBuffer = Buffer[SymbolSpecies];
100105

101106
const{ StringDecoder }=require('string_decoder');
102107
constfrom=require('internal/streams/from');
108+
constFixedQueue=require('internal/fixed_queue');
103109

104110
ObjectSetPrototypeOf(Readable.prototype,Stream.prototype);
105111
ObjectSetPrototypeOf(Readable,Stream);
@@ -1386,10 +1392,22 @@ function streamToAsyncIterator(stream, options) {
13861392
returniter;
13871393
}
13881394

1389-
asyncfunction*createAsyncIterator(stream,options){
1395+
// Async iterator over a Readable. Requests received while another is
1396+
// outstanding are queued and processed in order.
1397+
functioncreateAsyncIterator(stream,options){
13901398
letcallback=nop;
1391-
1392-
functionnext(resolve){
1399+
leterror;// undefined: active, null: ended cleanly, else: Error
1400+
letstarted=false;
1401+
letcompleted=false;
1402+
letinFlight=false;// An asynchronous request is outstanding
1403+
letqueue=null;// Requests received while inFlight
1404+
letdraining=false;
1405+
letcleanup;
1406+
1407+
// Used both as the 'readable' listener (where `this === stream`) and
1408+
// as a promise executor storing the resolver that wakes up a pending
1409+
// pump().
1410+
functionwakeup(resolve){
13931411
if(this===stream){
13941412
callback();
13951413
callback=nop;
@@ -1398,32 +1416,23 @@ async function* createAsyncIterator(stream, options) {
13981416
}
13991417
}
14001418

1401-
stream.on('readable',next);
1419+
functionstart(){
1420+
started=true;
14021421

1403-
leterror;
1404-
constcleanup=eos(stream,{writable: false},(err)=>{
1405-
error=err ? aggregateTwoErrors(error,err) : null;
1406-
callback();
1407-
callback=nop;
1408-
});
1422+
stream.on('readable',wakeup);
1423+
1424+
cleanup=eos(stream,{writable: false},(err)=>{
1425+
error=err ? aggregateTwoErrors(error,err) : null;
1426+
callback();
1427+
callback=nop;
1428+
});
1429+
}
1430+
1431+
// Complete the iterator and either destroy the stream or detach
1432+
// from it.
1433+
functionfinalize(){
1434+
completed=true;
14091435

1410-
try{
1411-
while(true){
1412-
constchunk=stream.destroyed ? null : stream.read();
1413-
if(chunk!==null){
1414-
yieldchunk;
1415-
}elseif(error){
1416-
throwerror;
1417-
}elseif(error===null){
1418-
return;
1419-
}else{
1420-
awaitnewPromise(next);
1421-
}
1422-
}
1423-
}catch(err){
1424-
error=aggregateTwoErrors(error,err);
1425-
throwerror;
1426-
}finally{
14271436
constpreserveHalfOpenDuplex=
14281437
error===null&&
14291438
stream.allowHalfOpen===true&&
@@ -1437,10 +1446,188 @@ async function* createAsyncIterator(stream, options) {
14371446
){
14381447
destroyImpl.destroyer(stream,null);
14391448
}else{
1440-
stream.off('readable',next);
1449+
stream.off('readable',wakeup);
14411450
cleanup();
14421451
}
14431452
}
1453+
1454+
functionsettleError(err,reject){
1455+
error=aggregateTwoErrors(error,err);
1456+
finalize();
1457+
reject(error);
1458+
}
1459+
1460+
functiondrain(){
1461+
// Requests settled synchronously call back into drain(); the guard
1462+
// keeps a single loop going instead of recursing once per request.
1463+
if(draining){
1464+
return;
1465+
}
1466+
draining=true;
1467+
try{
1468+
while(!inFlight&&!queue.isEmpty()){
1469+
constreq=queue.shift();
1470+
if(req.type==='next'){
1471+
processNext(req.resolve,req.reject);
1472+
}elseif(req.type==='return'){
1473+
processReturn(req.value,req.resolve);
1474+
}else{
1475+
processThrow(req.value,req.reject);
1476+
}
1477+
}
1478+
}finally{
1479+
draining=false;
1480+
}
1481+
}
1482+
1483+
// Thenable chunks are unwrapped before delivery; a rejection tears
1484+
// down the iterator and the stream.
1485+
functiononChunkFulfilled(value){
1486+
inFlight=false;
1487+
if(queue!==null)drain();
1488+
return{done: false, value };
1489+
}
1490+
1491+
functiononChunkRejected(err){
1492+
inFlight=false;
1493+
error=aggregateTwoErrors(error,err);
1494+
finalize();
1495+
if(queue!==null)drain();
1496+
throwerror;
1497+
}
1498+
1499+
// Runs with inFlight === true; settles the request and hands over to
1500+
// any requests that queued up behind it.
1501+
functionpump(resolve,reject){
1502+
constchunk=stream.destroyed ? null : stream.read();
1503+
if(chunk!==null){
1504+
// Read `then` only once so that a getter cannot observe (or throw
1505+
// on) a second access.
1506+
constthen=chunk.then;
1507+
if(typeofthen==='function'){
1508+
FunctionPrototypeCall(then,chunk,(value)=>{
1509+
inFlight=false;
1510+
resolve({done: false, value });
1511+
if(queue!==null)drain();
1512+
},(err)=>{
1513+
inFlight=false;
1514+
settleError(err,reject);
1515+
if(queue!==null)drain();
1516+
});
1517+
return;
1518+
}
1519+
inFlight=false;
1520+
resolve({done: false,value: chunk});
1521+
if(queue!==null)drain();
1522+
}elseif(error){
1523+
inFlight=false;
1524+
settleError(error,reject);
1525+
if(queue!==null)drain();
1526+
}elseif(error===null){
1527+
inFlight=false;
1528+
finalize();
1529+
resolve({done: true,value: undefined});
1530+
if(queue!==null)drain();
1531+
}else{
1532+
// No data buffered yet; wait for 'readable' or end-of-stream and
1533+
// retry.
1534+
PromisePrototypeThen(newPromise(wakeup),()=>pump(resolve,reject));
1535+
}
1536+
}
1537+
1538+
functionprocessNext(resolve,reject){
1539+
if(completed){
1540+
resolve({done: true,value: undefined});
1541+
return;
1542+
}
1543+
if(!started)start();
1544+
inFlight=true;
1545+
pump(resolve,reject);
1546+
}
1547+
1548+
functionprocessReturn(value,resolve){
1549+
if(!completed){
1550+
if(started){
1551+
finalize();
1552+
}else{
1553+
// Never started: complete without touching the stream.
1554+
completed=true;
1555+
}
1556+
}
1557+
resolve({done: true, value });
1558+
}
1559+
1560+
functionprocessThrow(err,reject){
1561+
if(completed||!started){
1562+
completed=true;
1563+
reject(err);
1564+
return;
1565+
}
1566+
settleError(err,reject);
1567+
}
1568+
1569+
return{
1570+
__proto__: AsyncIteratorPrototype,
1571+
next(){
1572+
if(!inFlight&&!completed){
1573+
if(!started)start();
1574+
// Fast path: a chunk is already buffered.
1575+
constchunk=stream.destroyed ? null : stream.read();
1576+
if(chunk!==null){
1577+
// Read `then` only once so that a getter cannot observe (or
1578+
// throw on) a second access.
1579+
constthen=chunk.then;
1580+
if(typeofthen==='function'){
1581+
inFlight=true;
1582+
returnFunctionPrototypeCall(
1583+
then,chunk,onChunkFulfilled,onChunkRejected);
1584+
}
1585+
returnPromiseResolve({done: false,value: chunk});
1586+
}
1587+
if(error){
1588+
finalize();
1589+
returnPromiseReject(error);
1590+
}
1591+
if(error===null){
1592+
finalize();
1593+
returnPromiseResolve({done: true,value: undefined});
1594+
}
1595+
// No data buffered yet; wait for 'readable' or end-of-stream.
1596+
inFlight=true;
1597+
returnnewPromise((resolve,reject)=>{
1598+
PromisePrototypeThen(newPromise(wakeup),()=>pump(resolve,reject));
1599+
});
1600+
}
1601+
returnnewPromise((resolve,reject)=>{
1602+
if(inFlight){
1603+
queue??=newFixedQueue();
1604+
queue.push({__proto__: null,type: 'next',value: undefined, resolve, reject });
1605+
}else{
1606+
resolve({done: true,value: undefined});
1607+
}
1608+
});
1609+
},
1610+
return(value){
1611+
returnnewPromise((resolve,reject)=>{
1612+
if(inFlight){
1613+
queue??=newFixedQueue();
1614+
queue.push({__proto__: null,type: 'return', value, resolve, reject });
1615+
}else{
1616+
processReturn(value,resolve);
1617+
}
1618+
});
1619+
},
1620+
throw(err){
1621+
returnnewPromise((resolve,reject)=>{
1622+
if(inFlight){
1623+
queue??=newFixedQueue();
1624+
queue.push({__proto__: null,type: 'throw',value: err, resolve, reject });
1625+
}else{
1626+
processThrow(err,reject);
1627+
}
1628+
});
1629+
},
1630+
};
14441631
}
14451632

14461633
letcomposeImpl;

β€Žtest/parallel/test-stream-flatMap.jsβ€Ž

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,23 @@ function oneTo5() {
7272

7373
{
7474
// Concurrency + AbortSignal
75+
// Two mappers are started concurrently and block until their signal
76+
// is aborted. Aborting while both are in flight must cancel them and
77+
// reject the iteration, without ever starting a third mapper.
7578
constac=newAbortController();
76-
conststream=oneTo5().flatMap(common.mustNotCall(async(_,{ signal })=>{
77-
awaitsetTimeout(100,{ signal });
78-
}),{signal: ac.signal,concurrency: 2});
79+
conststream=oneTo5().flatMap(common.mustCall(async(x,{ signal })=>{
80+
if(x===2){
81+
// Both mappers allowed by `concurrency` are now in flight.
82+
ac.abort();
83+
}
84+
const{ promise, reject }=Promise.withResolvers();
85+
if(signal.aborted){
86+
reject(signal.reason);
87+
}
88+
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
89+
// Promise is expected to reject.
90+
awaitpromise;
91+
},2),{signal: ac.signal,concurrency: 2});
7992
// pump
8093
assert.rejects(async()=>{
8194
forawait(constitemofstream){
@@ -85,10 +98,6 @@ function oneTo5() {
8598
},{
8699
name: 'AbortError',
87100
}).then(common.mustCall());
88-
89-
queueMicrotask(()=>{
90-
ac.abort();
91-
});
92101
}
93102

94103
{

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 5edffb5

Browse files
mcollinaaduh95
authored andcommitted
stream: speed up async iteration of Readable
Replace the async generator backing Symbol.asyncIterator with a hand-rolled iterator. The generator machinery costs several extra promise allocations and microtask hops per chunk: yield awaits the yielded value and resolves the pending request through separate promises. Buffered chunks are now delivered as an already-resolved promise, one microtask sooner than before. Thenable chunks are still awaited before delivery, requests received while a next() is outstanding are queued, and return()/throw() before the first next() complete the iterator without touching the stream. The earlier delivery is observable by code racing an abort against the first chunk. The flatMap AbortSignal test relied on such a race; it is reworked to abort deterministically while two mappers are in flight, asserting the concurrency limit, in-flight cancellation and rejection, without depending on delivery timing or timers. streams/readable-async-iterator.js sync='yes': +32.59% (***) streams/readable-async-iterator.js sync='no': +9.84% (***) Assisted-by: Claude Fable 5 Signed-off-by: Matteo Collina <matteo.collina@gmail.com> PR-URL: #64447 Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day> Reviewed-By: Mattias Buelens <mattias@buelens.com> Reviewed-By: Robert Nagy <ronagy@icloud.com>
1 parent 6302168 commit 5edffb5

3 files changed

Lines changed: 351 additions & 35 deletions

File tree

β€Žlib/internal/streams/readable.jsβ€Ž

Lines changed: 215 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,18 @@
2323

2424
const{
2525
ArrayPrototypeIndexOf,
26+
AsyncIteratorPrototype,
27+
FunctionPrototypeCall,
2628
NumberIsInteger,
2729
NumberIsNaN,
2830
NumberParseInt,
2931
ObjectDefineProperties,
3032
ObjectKeys,
3133
ObjectSetPrototypeOf,
3234
Promise,
35+
PromisePrototypeThen,
36+
PromiseReject,
37+
PromiseResolve,
3338
ReflectApply,
3439
SafeSet,
3540
Symbol,
@@ -100,6 +105,7 @@ const FastBuffer = Buffer[SymbolSpecies];
100105

101106
const{ StringDecoder }=require('string_decoder');
102107
constfrom=require('internal/streams/from');
108+
constFixedQueue=require('internal/fixed_queue');
103109

104110
ObjectSetPrototypeOf(Readable.prototype,Stream.prototype);
105111
ObjectSetPrototypeOf(Readable,Stream);
@@ -1386,10 +1392,22 @@ function streamToAsyncIterator(stream, options) {
13861392
returniter;
13871393
}
13881394

1389-
asyncfunction*createAsyncIterator(stream,options){
1395+
// Async iterator over a Readable. Requests received while another is
1396+
// outstanding are queued and processed in order.
1397+
functioncreateAsyncIterator(stream,options){
13901398
letcallback=nop;
1391-
1392-
functionnext(resolve){
1399+
leterror;// undefined: active, null: ended cleanly, else: Error
1400+
letstarted=false;
1401+
letcompleted=false;
1402+
letinFlight=false;// An asynchronous request is outstanding
1403+
letqueue=null;// Requests received while inFlight
1404+
letdraining=false;
1405+
letcleanup;
1406+
1407+
// Used both as the 'readable' listener (where `this === stream`) and
1408+
// as a promise executor storing the resolver that wakes up a pending
1409+
// pump().
1410+
functionwakeup(resolve){
13931411
if(this===stream){
13941412
callback();
13951413
callback=nop;
@@ -1398,32 +1416,23 @@ async function* createAsyncIterator(stream, options) {
13981416
}
13991417
}
14001418

1401-
stream.on('readable',next);
1419+
functionstart(){
1420+
started=true;
14021421

1403-
leterror;
1404-
constcleanup=eos(stream,{writable: false},(err)=>{
1405-
error=err ? aggregateTwoErrors(error,err) : null;
1406-
callback();
1407-
callback=nop;
1408-
});
1422+
stream.on('readable',wakeup);
1423+
1424+
cleanup=eos(stream,{writable: false},(err)=>{
1425+
error=err ? aggregateTwoErrors(error,err) : null;
1426+
callback();
1427+
callback=nop;
1428+
});
1429+
}
1430+
1431+
// Complete the iterator and either destroy the stream or detach
1432+
// from it.
1433+
functionfinalize(){
1434+
completed=true;
14091435

1410-
try{
1411-
while(true){
1412-
constchunk=stream.destroyed ? null : stream.read();
1413-
if(chunk!==null){
1414-
yieldchunk;
1415-
}elseif(error){
1416-
throwerror;
1417-
}elseif(error===null){
1418-
return;
1419-
}else{
1420-
awaitnewPromise(next);
1421-
}
1422-
}
1423-
}catch(err){
1424-
error=aggregateTwoErrors(error,err);
1425-
throwerror;
1426-
}finally{
14271436
constpreserveHalfOpenDuplex=
14281437
error===null&&
14291438
stream.allowHalfOpen===true&&
@@ -1437,10 +1446,188 @@ async function* createAsyncIterator(stream, options) {
14371446
){
14381447
destroyImpl.destroyer(stream,null);
14391448
}else{
1440-
stream.off('readable',next);
1449+
stream.off('readable',wakeup);
14411450
cleanup();
14421451
}
14431452
}
1453+
1454+
functionsettleError(err,reject){
1455+
error=aggregateTwoErrors(error,err);
1456+
finalize();
1457+
reject(error);
1458+
}
1459+
1460+
functiondrain(){
1461+
// Requests settled synchronously call back into drain(); the guard
1462+
// keeps a single loop going instead of recursing once per request.
1463+
if(draining){
1464+
return;
1465+
}
1466+
draining=true;
1467+
try{
1468+
while(!inFlight&&!queue.isEmpty()){
1469+
constreq=queue.shift();
1470+
if(req.type==='next'){
1471+
processNext(req.resolve,req.reject);
1472+
}elseif(req.type==='return'){
1473+
processReturn(req.value,req.resolve);
1474+
}else{
1475+
processThrow(req.value,req.reject);
1476+
}
1477+
}
1478+
}finally{
1479+
draining=false;
1480+
}
1481+
}
1482+
1483+
// Thenable chunks are unwrapped before delivery; a rejection tears
1484+
// down the iterator and the stream.
1485+
functiononChunkFulfilled(value){
1486+
inFlight=false;
1487+
if(queue!==null)drain();
1488+
return{done: false, value };
1489+
}
1490+
1491+
functiononChunkRejected(err){
1492+
inFlight=false;
1493+
error=aggregateTwoErrors(error,err);
1494+
finalize();
1495+
if(queue!==null)drain();
1496+
throwerror;
1497+
}
1498+
1499+
// Runs with inFlight === true; settles the request and hands over to
1500+
// any requests that queued up behind it.
1501+
functionpump(resolve,reject){
1502+
constchunk=stream.destroyed ? null : stream.read();
1503+
if(chunk!==null){
1504+
// Read `then` only once so that a getter cannot observe (or throw
1505+
// on) a second access.
1506+
constthen=chunk.then;
1507+
if(typeofthen==='function'){
1508+
FunctionPrototypeCall(then,chunk,(value)=>{
1509+
inFlight=false;
1510+
resolve({done: false, value });
1511+
if(queue!==null)drain();
1512+
},(err)=>{
1513+
inFlight=false;
1514+
settleError(err,reject);
1515+
if(queue!==null)drain();
1516+
});
1517+
return;
1518+
}
1519+
inFlight=false;
1520+
resolve({done: false,value: chunk});
1521+
if(queue!==null)drain();
1522+
}elseif(error){
1523+
inFlight=false;
1524+
settleError(error,reject);
1525+
if(queue!==null)drain();
1526+
}elseif(error===null){
1527+
inFlight=false;
1528+
finalize();
1529+
resolve({done: true,value: undefined});
1530+
if(queue!==null)drain();
1531+
}else{
1532+
// No data buffered yet; wait for 'readable' or end-of-stream and
1533+
// retry.
1534+
PromisePrototypeThen(newPromise(wakeup),()=>pump(resolve,reject));
1535+
}
1536+
}
1537+
1538+
functionprocessNext(resolve,reject){
1539+
if(completed){
1540+
resolve({done: true,value: undefined});
1541+
return;
1542+
}
1543+
if(!started)start();
1544+
inFlight=true;
1545+
pump(resolve,reject);
1546+
}
1547+
1548+
functionprocessReturn(value,resolve){
1549+
if(!completed){
1550+
if(started){
1551+
finalize();
1552+
}else{
1553+
// Never started: complete without touching the stream.
1554+
completed=true;
1555+
}
1556+
}
1557+
resolve({done: true, value });
1558+
}
1559+
1560+
functionprocessThrow(err,reject){
1561+
if(completed||!started){
1562+
completed=true;
1563+
reject(err);
1564+
return;
1565+
}
1566+
settleError(err,reject);
1567+
}
1568+
1569+
return{
1570+
__proto__: AsyncIteratorPrototype,
1571+
next(){
1572+
if(!inFlight&&!completed){
1573+
if(!started)start();
1574+
// Fast path: a chunk is already buffered.
1575+
constchunk=stream.destroyed ? null : stream.read();
1576+
if(chunk!==null){
1577+
// Read `then` only once so that a getter cannot observe (or
1578+
// throw on) a second access.
1579+
constthen=chunk.then;
1580+
if(typeofthen==='function'){
1581+
inFlight=true;
1582+
returnFunctionPrototypeCall(
1583+
then,chunk,onChunkFulfilled,onChunkRejected);
1584+
}
1585+
returnPromiseResolve({done: false,value: chunk});
1586+
}
1587+
if(error){
1588+
finalize();
1589+
returnPromiseReject(error);
1590+
}
1591+
if(error===null){
1592+
finalize();
1593+
returnPromiseResolve({done: true,value: undefined});
1594+
}
1595+
// No data buffered yet; wait for 'readable' or end-of-stream.
1596+
inFlight=true;
1597+
returnnewPromise((resolve,reject)=>{
1598+
PromisePrototypeThen(newPromise(wakeup),()=>pump(resolve,reject));
1599+
});
1600+
}
1601+
returnnewPromise((resolve,reject)=>{
1602+
if(inFlight){
1603+
queue??=newFixedQueue();
1604+
queue.push({__proto__: null,type: 'next',value: undefined, resolve, reject });
1605+
}else{
1606+
resolve({done: true,value: undefined});
1607+
}
1608+
});
1609+
},
1610+
return(value){
1611+
returnnewPromise((resolve,reject)=>{
1612+
if(inFlight){
1613+
queue??=newFixedQueue();
1614+
queue.push({__proto__: null,type: 'return', value, resolve, reject });
1615+
}else{
1616+
processReturn(value,resolve);
1617+
}
1618+
});
1619+
},
1620+
throw(err){
1621+
returnnewPromise((resolve,reject)=>{
1622+
if(inFlight){
1623+
queue??=newFixedQueue();
1624+
queue.push({__proto__: null,type: 'throw',value: err, resolve, reject });
1625+
}else{
1626+
processThrow(err,reject);
1627+
}
1628+
});
1629+
},
1630+
};
14441631
}
14451632

14461633
letcomposeImpl;

β€Žtest/parallel/test-stream-flatMap.jsβ€Ž

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,23 @@ function oneTo5() {
7272

7373
{
7474
// Concurrency + AbortSignal
75+
// Two mappers are started concurrently and block until their signal
76+
// is aborted. Aborting while both are in flight must cancel them and
77+
// reject the iteration, without ever starting a third mapper.
7578
constac=newAbortController();
76-
conststream=oneTo5().flatMap(common.mustNotCall(async(_,{ signal })=>{
77-
awaitsetTimeout(100,{ signal });
78-
}),{signal: ac.signal,concurrency: 2});
79+
conststream=oneTo5().flatMap(common.mustCall(async(x,{ signal })=>{
80+
if(x===2){
81+
// Both mappers allowed by `concurrency` are now in flight.
82+
ac.abort();
83+
}
84+
const{ promise, reject }=Promise.withResolvers();
85+
if(signal.aborted){
86+
reject(signal.reason);
87+
}
88+
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
89+
// Promise is expected to reject.
90+
awaitpromise;
91+
},2),{signal: ac.signal,concurrency: 2});
7992
// pump
8093
assert.rejects(async()=>{
8194
forawait(constitemofstream){
@@ -85,10 +98,6 @@ function oneTo5() {
8598
},{
8699
name: 'AbortError',
87100
}).then(common.mustCall());
88-
89-
queueMicrotask(()=>{
90-
ac.abort();
91-
});
92101
}
93102

94103
{

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Commit 5edffb5

Browse files
mcollinaaduh95
authored andcommitted
stream: speed up async iteration of Readable
Replace the async generator backing Symbol.asyncIterator with a hand-rolled iterator. The generator machinery costs several extra promise allocations and microtask hops per chunk: yield awaits the yielded value and resolves the pending request through separate promises. Buffered chunks are now delivered as an already-resolved promise, one microtask sooner than before. Thenable chunks are still awaited before delivery, requests received while a next() is outstanding are queued, and return()/throw() before the first next() complete the iterator without touching the stream. The earlier delivery is observable by code racing an abort against the first chunk. The flatMap AbortSignal test relied on such a race; it is reworked to abort deterministically while two mappers are in flight, asserting the concurrency limit, in-flight cancellation and rejection, without depending on delivery timing or timers. streams/readable-async-iterator.js sync='yes': +32.59% (***) streams/readable-async-iterator.js sync='no': +9.84% (***) Assisted-by: Claude Fable 5 Signed-off-by: Matteo Collina <matteo.collina@gmail.com> PR-URL: #64447 Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day> Reviewed-By: Mattias Buelens <mattias@buelens.com> Reviewed-By: Robert Nagy <ronagy@icloud.com>
1 parent 6302168 commit 5edffb5

3 files changed

Lines changed: 351 additions & 35 deletions

File tree

β€Žlib/internal/streams/readable.jsβ€Ž

Lines changed: 215 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,18 @@
2323

2424
const{
2525
ArrayPrototypeIndexOf,
26+
AsyncIteratorPrototype,
27+
FunctionPrototypeCall,
2628
NumberIsInteger,
2729
NumberIsNaN,
2830
NumberParseInt,
2931
ObjectDefineProperties,
3032
ObjectKeys,
3133
ObjectSetPrototypeOf,
3234
Promise,
35+
PromisePrototypeThen,
36+
PromiseReject,
37+
PromiseResolve,
3338
ReflectApply,
3439
SafeSet,
3540
Symbol,
@@ -100,6 +105,7 @@ const FastBuffer = Buffer[SymbolSpecies];
100105

101106
const{ StringDecoder }=require('string_decoder');
102107
constfrom=require('internal/streams/from');
108+
constFixedQueue=require('internal/fixed_queue');
103109

104110
ObjectSetPrototypeOf(Readable.prototype,Stream.prototype);
105111
ObjectSetPrototypeOf(Readable,Stream);
@@ -1386,10 +1392,22 @@ function streamToAsyncIterator(stream, options) {
13861392
returniter;
13871393
}
13881394

1389-
asyncfunction*createAsyncIterator(stream,options){
1395+
// Async iterator over a Readable. Requests received while another is
1396+
// outstanding are queued and processed in order.
1397+
functioncreateAsyncIterator(stream,options){
13901398
letcallback=nop;
1391-
1392-
functionnext(resolve){
1399+
leterror;// undefined: active, null: ended cleanly, else: Error
1400+
letstarted=false;
1401+
letcompleted=false;
1402+
letinFlight=false;// An asynchronous request is outstanding
1403+
letqueue=null;// Requests received while inFlight
1404+
letdraining=false;
1405+
letcleanup;
1406+
1407+
// Used both as the 'readable' listener (where `this === stream`) and
1408+
// as a promise executor storing the resolver that wakes up a pending
1409+
// pump().
1410+
functionwakeup(resolve){
13931411
if(this===stream){
13941412
callback();
13951413
callback=nop;
@@ -1398,32 +1416,23 @@ async function* createAsyncIterator(stream, options) {
13981416
}
13991417
}
14001418

1401-
stream.on('readable',next);
1419+
functionstart(){
1420+
started=true;
14021421

1403-
leterror;
1404-
constcleanup=eos(stream,{writable: false},(err)=>{
1405-
error=err ? aggregateTwoErrors(error,err) : null;
1406-
callback();
1407-
callback=nop;
1408-
});
1422+
stream.on('readable',wakeup);
1423+
1424+
cleanup=eos(stream,{writable: false},(err)=>{
1425+
error=err ? aggregateTwoErrors(error,err) : null;
1426+
callback();
1427+
callback=nop;
1428+
});
1429+
}
1430+
1431+
// Complete the iterator and either destroy the stream or detach
1432+
// from it.
1433+
functionfinalize(){
1434+
completed=true;
14091435

1410-
try{
1411-
while(true){
1412-
constchunk=stream.destroyed ? null : stream.read();
1413-
if(chunk!==null){
1414-
yieldchunk;
1415-
}elseif(error){
1416-
throwerror;
1417-
}elseif(error===null){
1418-
return;
1419-
}else{
1420-
awaitnewPromise(next);
1421-
}
1422-
}
1423-
}catch(err){
1424-
error=aggregateTwoErrors(error,err);
1425-
throwerror;
1426-
}finally{
14271436
constpreserveHalfOpenDuplex=
14281437
error===null&&
14291438
stream.allowHalfOpen===true&&
@@ -1437,10 +1446,188 @@ async function* createAsyncIterator(stream, options) {
14371446
){
14381447
destroyImpl.destroyer(stream,null);
14391448
}else{
1440-
stream.off('readable',next);
1449+
stream.off('readable',wakeup);
14411450
cleanup();
14421451
}
14431452
}
1453+
1454+
functionsettleError(err,reject){
1455+
error=aggregateTwoErrors(error,err);
1456+
finalize();
1457+
reject(error);
1458+
}
1459+
1460+
functiondrain(){
1461+
// Requests settled synchronously call back into drain(); the guard
1462+
// keeps a single loop going instead of recursing once per request.
1463+
if(draining){
1464+
return;
1465+
}
1466+
draining=true;
1467+
try{
1468+
while(!inFlight&&!queue.isEmpty()){
1469+
constreq=queue.shift();
1470+
if(req.type==='next'){
1471+
processNext(req.resolve,req.reject);
1472+
}elseif(req.type==='return'){
1473+
processReturn(req.value,req.resolve);
1474+
}else{
1475+
processThrow(req.value,req.reject);
1476+
}
1477+
}
1478+
}finally{
1479+
draining=false;
1480+
}
1481+
}
1482+
1483+
// Thenable chunks are unwrapped before delivery; a rejection tears
1484+
// down the iterator and the stream.
1485+
functiononChunkFulfilled(value){
1486+
inFlight=false;
1487+
if(queue!==null)drain();
1488+
return{done: false, value };
1489+
}
1490+
1491+
functiononChunkRejected(err){
1492+
inFlight=false;
1493+
error=aggregateTwoErrors(error,err);
1494+
finalize();
1495+
if(queue!==null)drain();
1496+
throwerror;
1497+
}
1498+
1499+
// Runs with inFlight === true; settles the request and hands over to
1500+
// any requests that queued up behind it.
1501+
functionpump(resolve,reject){
1502+
constchunk=stream.destroyed ? null : stream.read();
1503+
if(chunk!==null){
1504+
// Read `then` only once so that a getter cannot observe (or throw
1505+
// on) a second access.
1506+
constthen=chunk.then;
1507+
if(typeofthen==='function'){
1508+
FunctionPrototypeCall(then,chunk,(value)=>{
1509+
inFlight=false;
1510+
resolve({done: false, value });
1511+
if(queue!==null)drain();
1512+
},(err)=>{
1513+
inFlight=false;
1514+
settleError(err,reject);
1515+
if(queue!==null)drain();
1516+
});
1517+
return;
1518+
}
1519+
inFlight=false;
1520+
resolve({done: false,value: chunk});
1521+
if(queue!==null)drain();
1522+
}elseif(error){
1523+
inFlight=false;
1524+
settleError(error,reject);
1525+
if(queue!==null)drain();
1526+
}elseif(error===null){
1527+
inFlight=false;
1528+
finalize();
1529+
resolve({done: true,value: undefined});
1530+
if(queue!==null)drain();
1531+
}else{
1532+
// No data buffered yet; wait for 'readable' or end-of-stream and
1533+
// retry.
1534+
PromisePrototypeThen(newPromise(wakeup),()=>pump(resolve,reject));
1535+
}
1536+
}
1537+
1538+
functionprocessNext(resolve,reject){
1539+
if(completed){
1540+
resolve({done: true,value: undefined});
1541+
return;
1542+
}
1543+
if(!started)start();
1544+
inFlight=true;
1545+
pump(resolve,reject);
1546+
}
1547+
1548+
functionprocessReturn(value,resolve){
1549+
if(!completed){
1550+
if(started){
1551+
finalize();
1552+
}else{
1553+
// Never started: complete without touching the stream.
1554+
completed=true;
1555+
}
1556+
}
1557+
resolve({done: true, value });
1558+
}
1559+
1560+
functionprocessThrow(err,reject){
1561+
if(completed||!started){
1562+
completed=true;
1563+
reject(err);
1564+
return;
1565+
}
1566+
settleError(err,reject);
1567+
}
1568+
1569+
return{
1570+
__proto__: AsyncIteratorPrototype,
1571+
next(){
1572+
if(!inFlight&&!completed){
1573+
if(!started)start();
1574+
// Fast path: a chunk is already buffered.
1575+
constchunk=stream.destroyed ? null : stream.read();
1576+
if(chunk!==null){
1577+
// Read `then` only once so that a getter cannot observe (or
1578+
// throw on) a second access.
1579+
constthen=chunk.then;
1580+
if(typeofthen==='function'){
1581+
inFlight=true;
1582+
returnFunctionPrototypeCall(
1583+
then,chunk,onChunkFulfilled,onChunkRejected);
1584+
}
1585+
returnPromiseResolve({done: false,value: chunk});
1586+
}
1587+
if(error){
1588+
finalize();
1589+
returnPromiseReject(error);
1590+
}
1591+
if(error===null){
1592+
finalize();
1593+
returnPromiseResolve({done: true,value: undefined});
1594+
}
1595+
// No data buffered yet; wait for 'readable' or end-of-stream.
1596+
inFlight=true;
1597+
returnnewPromise((resolve,reject)=>{
1598+
PromisePrototypeThen(newPromise(wakeup),()=>pump(resolve,reject));
1599+
});
1600+
}
1601+
returnnewPromise((resolve,reject)=>{
1602+
if(inFlight){
1603+
queue??=newFixedQueue();
1604+
queue.push({__proto__: null,type: 'next',value: undefined, resolve, reject });
1605+
}else{
1606+
resolve({done: true,value: undefined});
1607+
}
1608+
});
1609+
},
1610+
return(value){
1611+
returnnewPromise((resolve,reject)=>{
1612+
if(inFlight){
1613+
queue??=newFixedQueue();
1614+
queue.push({__proto__: null,type: 'return', value, resolve, reject });
1615+
}else{
1616+
processReturn(value,resolve);
1617+
}
1618+
});
1619+
},
1620+
throw(err){
1621+
returnnewPromise((resolve,reject)=>{
1622+
if(inFlight){
1623+
queue??=newFixedQueue();
1624+
queue.push({__proto__: null,type: 'throw',value: err, resolve, reject });
1625+
}else{
1626+
processThrow(err,reject);
1627+
}
1628+
});
1629+
},
1630+
};
14441631
}
14451632

14461633
letcomposeImpl;

β€Žtest/parallel/test-stream-flatMap.jsβ€Ž

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,23 @@ function oneTo5() {
7272

7373
{
7474
// Concurrency + AbortSignal
75+
// Two mappers are started concurrently and block until their signal
76+
// is aborted. Aborting while both are in flight must cancel them and
77+
// reject the iteration, without ever starting a third mapper.
7578
constac=newAbortController();
76-
conststream=oneTo5().flatMap(common.mustNotCall(async(_,{ signal })=>{
77-
awaitsetTimeout(100,{ signal });
78-
}),{signal: ac.signal,concurrency: 2});
79+
conststream=oneTo5().flatMap(common.mustCall(async(x,{ signal })=>{
80+
if(x===2){
81+
// Both mappers allowed by `concurrency` are now in flight.
82+
ac.abort();
83+
}
84+
const{ promise, reject }=Promise.withResolvers();
85+
if(signal.aborted){
86+
reject(signal.reason);
87+
}
88+
signal.addEventListener('abort',()=>reject(signal.reason),{once: true});
89+
// Promise is expected to reject.
90+
awaitpromise;
91+
},2),{signal: ac.signal,concurrency: 2});
7992
// pump
8093
assert.rejects(async()=>{
8194
forawait(constitemofstream){
@@ -85,10 +98,6 @@ function oneTo5() {
8598
},{
8699
name: 'AbortError',
87100
}).then(common.mustCall());
88-
89-
queueMicrotask(()=>{
90-
ac.abort();
91-
});
92101
}
93102

94103
{

0 commit comments

Comments
Β (0)