diff --git a/lib/internal/webstreams/readablestream.js b/lib/internal/webstreams/readablestream.js index b05cb7c257e..ed7b8fd8776 100644 --- a/lib/internal/webstreams/readablestream.js +++ b/lib/internal/webstreams/readablestream.js @@ -101,6 +101,7 @@ const { cloneAsUint8Array, copyArrayBuffer, createPromiseCallback1Param, + createRawCallback1Param, customInspect, defaultSizeAlgorithm, dequeueValue, @@ -110,6 +111,7 @@ const { getNonWritablePropertyDescriptor, isBrandCheck, kEmptyQueue, + kResolvedPromise, kState, kType, lazyTransfer, @@ -121,6 +123,7 @@ const { resetQueue, resolvedRecord, setPromiseHandled, + thenAlgorithmResult, } = require('internal/webstreams/util'); const { @@ -137,7 +140,6 @@ const { writableStreamDefaultWriterRelease, writableStreamDefaultWriterWriteWithRequest, writerClosedPromise, - writerReadyPromise, } = require('internal/webstreams/writablestream'); const { Buffer } = require('buffer'); @@ -1664,11 +1666,31 @@ function readableStreamPipeTo( // the chunk travels through `pendingChunk`. let pendingChunk; let readRequest; + let readyHook; // Ready promise rejection is handled by the destination-errored // watcher. function ignoreReadyRejection() {} + // Parks the pump on the destination's backpressure by installing a + // record that duck-types the writer's lazily-materialized + // [[readyPromise]] record: writableStreamUpdateBackpressure resolves it + // when backpressure clears (after publishing the new backpressure + // state), which re-enters the pump directly instead of rotating a + // fresh promise record plus reaction per flip. The pipe holds the only + // reference to the writer, so the record is never observable as a real + // ready promise; the erroring/release paths probe `promise` via + // isPromisePending() and call `reject`, so it carries a real + // forever-pending promise and a no-op reject. + function parkOnReady() { + readyHook ??= { + promise: new Promise(nonOpCallback), + resolve: pump, + reject: ignoreReadyRejection, + }; + writer[kState].ready = readyHook; + } + function forwardChunk() { const chunk = pendingChunk; pendingChunk = undefined; @@ -1680,10 +1702,7 @@ function readableStreamPipeTo( if (shuttingDown) return; if (dest[kState].backpressure) { - PromisePrototypeThen( - writerReadyPromise(writer).promise, - pump, - ignoreReadyRejection); + parkOnReady(); return; } @@ -1728,9 +1747,18 @@ function readableStreamPipeTo( return; } - // Yield to microtask queue between batches to allow events/signals - // to fire - queueMicrotask(pump); + // Park on backpressure directly: the ready hook resumes the pump + // when a completed write clears it. + if (dest[kState].backpressure) { + parkOnReady(); + return; + } + + // Yield to the microtask queue between batches so completed-write + // reactions and events/signals fire; a shared resolved promise + // enqueues the continuation at the same position as queueMicrotask + // without the per-batch scheduling overhead. + PromisePrototypeThen(kResolvedPromise, pump); return; } @@ -1742,7 +1770,7 @@ function readableStreamPipeTo( // synchronous write during enqueue(). See WHATWG Streams spec // "ReadableStreamPipeTo" step 15's "chunk steps". pendingChunk = chunk; - queueMicrotask(forwardChunk); + PromisePrototypeThen(kResolvedPromise, forwardChunk); }, [kClose]() {}, [kError]() {}, @@ -1857,7 +1885,7 @@ function readableStreamDefaultTee(stream, cloneForBranch2) { // The microtask is required by the spec (ReadableStreamTee's // "chunk steps" queue one). pendingChunk = value; - queueMicrotask(forwardChunk); + PromisePrototypeThen(kResolvedPromise, forwardChunk); }, [kClose]() { // The `process.nextTick()` is not part of the spec. @@ -2010,7 +2038,7 @@ function readableByteStreamTee(stream) { defaultReadRequest ??= { [kChunk](chunk) { pendingChunk = chunk; - queueMicrotask(forwardChunk); + PromisePrototypeThen(kResolvedPromise, forwardChunk); }, [kClose]() { reading = false; @@ -2699,8 +2727,18 @@ function readableStreamDefaultControllerPull(controller) { controller[kState].pullRejected = (error) => readableStreamDefaultControllerError(controller, error); } - PromisePrototypeThen( - controller[kState].pullAlgorithm(controller), + // The pull algorithm may be a raw callback (a wrapped user source.pull + // returns its result uncoerced; a synchronous throw surfaces here) or an + // internal algorithm that always returns a promise; thenAlgorithmResult + // handles both. + let result; + try { + result = controller[kState].pullAlgorithm(controller); + } catch (error) { + result = PromiseReject(error); + } + thenAlgorithmResult( + result, controller[kState].pullFulfilled, controller[kState].pullRejected); } @@ -2826,7 +2864,7 @@ function setupReadableStreamDefaultControllerFromSource( FunctionPrototypeBind(start, source, controller) : nonOpStart; const pullAlgorithm = pull ? - createPromiseCallback1Param('source.pull', pull, source) : + createRawCallback1Param('source.pull', pull, source) : nonOpPull; const cancelAlgorithm = cancel ? createPromiseCallback1Param('source.cancel', cancel, source) : @@ -3519,8 +3557,15 @@ function readableByteStreamControllerCallPullIfNeeded(controller) { controller[kState].pullRejected = (error) => readableByteStreamControllerError(controller, error); } - PromisePrototypeThen( - controller[kState].pullAlgorithm(controller), + // See readableStreamDefaultControllerPull for the raw-callback contract. + let result; + try { + result = controller[kState].pullAlgorithm(controller); + } catch (error) { + result = PromiseReject(error); + } + thenAlgorithmResult( + result, controller[kState].pullFulfilled, controller[kState].pullRejected); } @@ -3700,7 +3745,7 @@ function setupReadableByteStreamControllerFromSource( FunctionPrototypeBind(start, source, controller) : nonOpStart; const pullAlgorithm = pull ? - createPromiseCallback1Param('source.pull', pull, source) : + createRawCallback1Param('source.pull', pull, source) : nonOpPull; const cancelAlgorithm = cancel ? createPromiseCallback1Param('source.cancel', cancel, source) : diff --git a/lib/internal/webstreams/util.js b/lib/internal/webstreams/util.js index 8bc4c02be31..b3a8e7827e3 100644 --- a/lib/internal/webstreams/util.js +++ b/lib/internal/webstreams/util.js @@ -338,6 +338,40 @@ function createPromiseCallbackNoParams(name, fn, thisArg) { return async () => FunctionPrototypeCall(fn, thisArg); } +// Raw variants that skip the async wrapper's implicit result promise. +// Consumers of a raw callback invoke it inside try/catch and route the +// result through thenAlgorithmResult() below. +function createRawCallback1Param(name, fn, thisArg) { + validateFunction(fn, name); + return (arg) => FunctionPrototypeCall(fn, thisArg, arg); +} + +function createRawCallback2Params(name, fn, thisArg) { + validateFunction(fn, name); + return (arg1, arg2) => FunctionPrototypeCall(fn, thisArg, arg1, arg2); +} + +// A single shared, forever-resolved promise used to enqueue a reaction at +// the next microtask checkpoint without allocating a fresh promise. +const kResolvedPromise = PromiseResolve(); + +// Wires the (possibly non-thenable) result of an underlying algorithm +// callback to its fulfilled/rejected continuations. A non-thenable result +// means fulfillment is guaranteed and no then() lookup is observable, so +// the fulfillment step is enqueued directly at the exact microtask +// position the coerced promise's reaction would have had, skipping the +// per-chunk promise allocation. For thenable results PromiseResolve() +// matches the spec's "a promise resolved with" conversion (identity for +// native promises). +function thenAlgorithmResult(result, onFulfilled, onRejected) { + if (result === null || + (typeof result !== 'object' && typeof result !== 'function')) { + PromisePrototypeThen(kResolvedPromise, onFulfilled); + } else { + PromisePrototypeThen(PromiseResolve(result), onFulfilled, onRejected); + } +} + function createPromiseCallback1Param(name, fn, thisArg) { validateFunction(fn, name); return async (arg) => FunctionPrototypeCall(fn, thisArg, arg); @@ -386,11 +420,14 @@ async function nonOpFlush() {} function nonOpStart() {} -async function nonOpPull() {} +// nonOpPull and nonOpWrite are raw callbacks (see createRawCallback*): +// their non-thenable return takes the allocation-free fast path in +// thenAlgorithmResult(). +function nonOpPull() {} async function nonOpCancel() {} -async function nonOpWrite() {} +function nonOpWrite() {} let transfer; function lazyTransfer() { @@ -411,6 +448,8 @@ module.exports = { createPromiseCallbackNoParams, createPromiseCallback1Param, createPromiseCallback2Params, + createRawCallback1Param, + createRawCallback2Params, customInspect, defaultSizeAlgorithm, dequeueValue, @@ -421,6 +460,7 @@ module.exports = { isBrandCheck, isPromisePending, kEmptyQueue, + kResolvedPromise, kState, kType, lazyTransfer, @@ -435,4 +475,5 @@ module.exports = { resetQueue, resolvedRecord, setPromiseHandled, + thenAlgorithmResult, }; diff --git a/lib/internal/webstreams/writablestream.js b/lib/internal/webstreams/writablestream.js index 10b7dbcf277..5c73f0fe757 100644 --- a/lib/internal/webstreams/writablestream.js +++ b/lib/internal/webstreams/writablestream.js @@ -56,7 +56,7 @@ const { Queue, createPromiseCallbackNoParams, createPromiseCallback1Param, - createPromiseCallback2Params, + createRawCallback2Params, customInspect, defaultSizeAlgorithm, dequeueValue, @@ -78,6 +78,7 @@ const { resetQueue, resolvedRecord, setPromiseHandled, + thenAlgorithmResult, } = require('internal/webstreams/util'); const { @@ -769,7 +770,12 @@ function writableStreamUpdateBackpressure(controller, streamState) { const backpressure = controllerState.highWaterMark - controllerState.queueTotalSize <= 0; const writer = streamState.writer; - if (writer !== undefined && streamState.backpressure !== backpressure) { + const changed = streamState.backpressure !== backpressure; + // The state field is published before the ready record is resolved so + // that a ready resolve hook (pipeTo's pump continuation) observes the + // new value. + streamState.backpressure = backpressure; + if (writer !== undefined && changed) { if (backpressure) { // The spec replaces [[readyPromise]] with a fresh pending promise; // dropping the cache lets the next observation derive it. @@ -778,7 +784,6 @@ function writableStreamUpdateBackpressure(controller, streamState) { writer[kState].ready?.resolve(); } } - streamState.backpressure = backpressure; } function writableStreamStartErroring(stream, reason) { @@ -1197,8 +1202,18 @@ function writableStreamDefaultControllerProcessWrite(controller, chunk) { }; } - PromisePrototypeThen( - writeAlgorithm(chunk, controller), + // The write algorithm may be a raw callback (a wrapped user sink.write + // returns its result uncoerced; a synchronous throw surfaces here) or an + // internal algorithm that always returns a promise; thenAlgorithmResult + // handles both. + let result; + try { + result = writeAlgorithm(chunk, controller); + } catch (error) { + result = PromiseReject(error); + } + thenAlgorithmResult( + result, controller[kState].writeFulfilled, controller[kState].writeRejected); } @@ -1323,7 +1338,7 @@ function setupWritableStreamDefaultControllerFromSink( FunctionPrototypeBind(start, sink, controller) : nonOpStart; const writeAlgorithm = write ? - createPromiseCallback2Params('sink.write', write, sink) : + createRawCallback2Params('sink.write', write, sink) : nonOpWrite; const closeAlgorithm = close ? createPromiseCallbackNoParams('sink.close', close, sink) :