diff --git a/lib/internal/quic/quic.js b/lib/internal/quic/quic.js index 34e3cbf10a1..6082226edf4 100644 --- a/lib/internal/quic/quic.js +++ b/lib/internal/quic/quic.js @@ -1391,56 +1391,17 @@ function maybeGetCloseError(context, status, pendingError) { } class QuicStream { + // All mutable per-stream state is consolidated into a single object + // to minimize the number of V8 private field slots. Only #handle is + // kept as a private field for the brand check in #assertIsQuicStream. /** @type {object} */ #handle; - /** - * Flag set at the top of `destroy()` to make the method safely - * re-entrant. Distinct from `#handle === undefined` (which signals - * "fully destroyed" and is set inside `[kFinishClose]`) so that - * `[kFinishClose]`'s own destroyed-guard does not bail before the - * cleanup work runs. - * @type {boolean} - */ - #destroying = false; - /** @type {QuicSession} */ - #session; - /** @type {QuicStreamStats} */ - #stats; - /** @type {QuicStreamState} */ - #state; - /** @type {number} */ - #direction = undefined; - /** @type {Function|undefined} */ - #onerror = undefined; - /** @type {OnBlockedCallback|undefined} */ - #onblocked = undefined; - /** @type {OnStreamErrorCallback|undefined} */ - #onreset = undefined; - /** @type {Function|undefined} */ - #onheaders = undefined; - /** @type {Function|undefined} */ - #ontrailers = undefined; - /** @type {Function|undefined} */ - #oninfo = undefined; - /** @type {Function|undefined} */ - #onwanttrailers = undefined; - /** @type {object|undefined} */ - #headers = undefined; - /** @type {object|undefined} */ - #pendingTrailers = undefined; - /** @type {Promise} */ - #pendingClose = PromiseWithResolvers(); - #reader; - #iteratorLocked = false; - #writer = undefined; - #outboundSet = false; - /** @type {FileHandle|undefined} */ - #fileHandle = undefined; + #inner; static { getQuicStreamState = function(stream) { QuicStream.#assertIsQuicStream(stream); - return stream.#state; + return stream.#inner.state; }; } @@ -1451,7 +1412,7 @@ class QuicStream { } #assertHeadersSupported() { - if (getQuicSessionState(this.#session).headersSupported === 2) { + if (getQuicSessionState(this.#inner.session).headersSupported === 2) { throw new ERR_INVALID_STATE( 'The negotiated QUIC application protocol does not support headers'); } @@ -1462,31 +1423,47 @@ class QuicStream { * @param {object} handle * @param {QuicSession} session * @param {number} direction + * @param {boolean} [isLocal] True for locally-initiated streams */ - constructor(privateSymbol, handle, session, direction) { + constructor(privateSymbol, handle, session, direction, isLocal = false) { if (privateSymbol !== kPrivateConstructor) { throw new ERR_ILLEGAL_CONSTRUCTOR(); } this.#handle = handle; - this.#handle[kOwner] = this; - this.#session = session; - this.#direction = direction; - this.#stats = new QuicStreamStats( - kPrivateConstructor, this.#handle.stats, this.#handle.statsByteOffset); - this.#state = new QuicStreamState( - kPrivateConstructor, this.#handle.state, this.#handle.stateByteOffset); - this.#reader = this.#handle.getReader(); + handle[kOwner] = this; + this.#inner = { + __proto__: null, + session, + direction, + isLocal, + state: new QuicStreamState( + kPrivateConstructor, handle.state, handle.stateByteOffset), + stats: undefined, + pendingClose: undefined, + reader: undefined, + destroying: false, + iteratorLocked: false, + outboundSet: false, + writer: undefined, + fileHandle: undefined, + headers: undefined, + pendingTrailers: undefined, + // Callback slots + onerror: undefined, + onblocked: undefined, + onreset: undefined, + onheaders: undefined, + ontrailers: undefined, + oninfo: undefined, + onwanttrailers: undefined, + }; if (hasObserver('quic')) { startPerf(this, kPerfEntry, { type: 'quic', name: 'QuicStream' }); } - if (this.pending) { - debug(`pending ${this.direction} stream created`); - } else { - debug(`${this.direction} stream ${this.id} created`); - } + debug('stream created'); } get [kValidatedSource]() { return true; } @@ -1499,15 +1476,16 @@ class QuicStream { */ async *[SymbolAsyncIterator]() { QuicStream.#assertIsQuicStream(this); - if (this.#iteratorLocked) { + if (this.#inner.iteratorLocked) { throw new ERR_INVALID_STATE('Stream is already being read'); } - this.#iteratorLocked = true; + this.#inner.iteratorLocked = true; + this.#inner.reader ??= this.#handle?.getReader(); // Non-readable stream (outbound-only unidirectional, or closed) - if (!this.#reader) return; + if (!this.#inner.reader) return; - yield* createBlobReaderIterable(this.#reader, { + yield* createBlobReaderIterable(this.#inner.reader, { getReadError: () => { // The read side ends for one of three reasons: // * Clean FIN received from the peer (state.finReceived @@ -1521,8 +1499,8 @@ class QuicStream { // stream.stopSending(). Both paths run EndReadable in // C++, setting state.readEnded without setting // state.finReceived. There is no peer code to surface. - if (this.#state.readEnded && !this.#state.finReceived) { - const peerResetCode = this.#state.resetCode; + if (this.#inner.state.readEnded && !this.#inner.state.finReceived) { + const peerResetCode = this.#inner.state.resetCode; if (peerResetCode !== undefined && peerResetCode > 0n) { return new ERR_QUIC_STREAM_RESET(Number(peerResetCode)); } @@ -1541,7 +1519,7 @@ class QuicStream { */ get pending() { QuicStream.#assertIsQuicStream(this); - return this.#state.pending; + return this.#inner.state.pending; } /** @@ -1552,7 +1530,7 @@ class QuicStream { */ get early() { QuicStream.#assertIsQuicStream(this); - return this.#state.early; + return this.#inner.state.early; } /** @@ -1563,142 +1541,144 @@ class QuicStream { */ get highWaterMark() { QuicStream.#assertIsQuicStream(this); - return this.#state.highWaterMark; + return this.#inner.state.highWaterMark; } set highWaterMark(val) { QuicStream.#assertIsQuicStream(this); validateInteger(val, 'highWaterMark', 0, 0xFFFFFFFF); - this.#state.highWaterMark = val; + this.#inner.state.highWaterMark = val; // If writeDesiredSize hasn't been set yet (still 0 from initialization), // initialize it to the highWaterMark so the first write can proceed. - if (this.#state.writeDesiredSize === 0 && val > 0) { - this.#state.writeDesiredSize = val; + if (this.#inner.state.writeDesiredSize === 0 && val > 0) { + this.#inner.state.writeDesiredSize = val; } } /** @type {Function|undefined} */ get onerror() { QuicStream.#assertIsQuicStream(this); - return this.#onerror; + return this.#inner.onerror; } set onerror(fn) { QuicStream.#assertIsQuicStream(this); if (fn === undefined) { - this.#onerror = undefined; + this.#inner.onerror = undefined; } else { validateFunction(fn, 'onerror'); - this.#onerror = FunctionPrototypeBind(fn, this); - markPromiseAsHandled(this.#pendingClose.promise); + this.#inner.onerror = FunctionPrototypeBind(fn, this); + // Lazily create the close promise so it can be marked handled. + this.#inner.pendingClose ??= PromiseWithResolvers(); + markPromiseAsHandled(this.#inner.pendingClose.promise); } } /** @type {OnBlockedCallback} */ get onblocked() { QuicStream.#assertIsQuicStream(this); - return this.#onblocked; + return this.#inner.onblocked; } set onblocked(fn) { QuicStream.#assertIsQuicStream(this); if (fn === undefined) { - this.#onblocked = undefined; - this.#state.wantsBlock = false; + this.#inner.onblocked = undefined; + this.#inner.state.wantsBlock = false; } else { validateFunction(fn, 'onblocked'); - this.#onblocked = FunctionPrototypeBind(fn, this); - this.#state.wantsBlock = true; + this.#inner.onblocked = FunctionPrototypeBind(fn, this); + this.#inner.state.wantsBlock = true; } } /** @type {OnStreamErrorCallback} */ get onreset() { QuicStream.#assertIsQuicStream(this); - return this.#onreset; + return this.#inner.onreset; } set onreset(fn) { QuicStream.#assertIsQuicStream(this); if (fn === undefined) { - this.#onreset = undefined; - this.#state.wantsReset = false; + this.#inner.onreset = undefined; + this.#inner.state.wantsReset = false; } else { validateFunction(fn, 'onreset'); - this.#onreset = FunctionPrototypeBind(fn, this); - this.#state.wantsReset = true; + this.#inner.onreset = FunctionPrototypeBind(fn, this); + this.#inner.state.wantsReset = true; } } /** @type {OnHeadersCallback} */ get onheaders() { QuicStream.#assertIsQuicStream(this); - return this.#onheaders; + return this.#inner.onheaders; } set onheaders(fn) { QuicStream.#assertIsQuicStream(this); if (fn === undefined) { - this.#onheaders = undefined; - this.#state[kWantsHeaders] = false; + this.#inner.onheaders = undefined; + this.#inner.state[kWantsHeaders] = false; } else { this.#assertHeadersSupported(); validateFunction(fn, 'onheaders'); - this.#onheaders = FunctionPrototypeBind(fn, this); - this.#state[kWantsHeaders] = true; + this.#inner.onheaders = FunctionPrototypeBind(fn, this); + this.#inner.state[kWantsHeaders] = true; } } /** @type {Function|undefined} */ get oninfo() { QuicStream.#assertIsQuicStream(this); - return this.#oninfo; + return this.#inner.oninfo; } set oninfo(fn) { QuicStream.#assertIsQuicStream(this); if (fn === undefined) { - this.#oninfo = undefined; + this.#inner.oninfo = undefined; } else { this.#assertHeadersSupported(); validateFunction(fn, 'oninfo'); - this.#oninfo = FunctionPrototypeBind(fn, this); + this.#inner.oninfo = FunctionPrototypeBind(fn, this); } } /** @type {Function|undefined} */ get ontrailers() { QuicStream.#assertIsQuicStream(this); - return this.#ontrailers; + return this.#inner.ontrailers; } set ontrailers(fn) { QuicStream.#assertIsQuicStream(this); if (fn === undefined) { - this.#ontrailers = undefined; + this.#inner.ontrailers = undefined; } else { this.#assertHeadersSupported(); validateFunction(fn, 'ontrailers'); - this.#ontrailers = FunctionPrototypeBind(fn, this); + this.#inner.ontrailers = FunctionPrototypeBind(fn, this); } } /** @type {Function|undefined} */ get onwanttrailers() { QuicStream.#assertIsQuicStream(this); - return this.#onwanttrailers; + return this.#inner.onwanttrailers; } set onwanttrailers(fn) { QuicStream.#assertIsQuicStream(this); if (fn === undefined) { - this.#onwanttrailers = undefined; - this.#state[kWantsTrailers] = false; + this.#inner.onwanttrailers = undefined; + this.#inner.state[kWantsTrailers] = false; } else { this.#assertHeadersSupported(); validateFunction(fn, 'onwanttrailers'); - this.#onwanttrailers = FunctionPrototypeBind(fn, this); - this.#state[kWantsTrailers] = true; + this.#inner.onwanttrailers = FunctionPrototypeBind(fn, this); + this.#inner.state[kWantsTrailers] = true; } } @@ -1710,7 +1690,7 @@ class QuicStream { */ get headers() { QuicStream.#assertIsQuicStream(this); - return this.#headers; + return this.#inner.headers; } /** @@ -1719,21 +1699,21 @@ class QuicStream { */ get pendingTrailers() { QuicStream.#assertIsQuicStream(this); - return this.#pendingTrailers; + return this.#inner.pendingTrailers; } set pendingTrailers(headers) { QuicStream.#assertIsQuicStream(this); if (headers === undefined) { - this.#pendingTrailers = undefined; + this.#inner.pendingTrailers = undefined; return; } - if (getQuicSessionState(this.#session).headersSupported === 2) { + if (getQuicSessionState(this.#inner.session).headersSupported === 2) { throw new ERR_INVALID_STATE( 'The negotiated QUIC application protocol does not support headers'); } validateObject(headers, 'headers'); - this.#pendingTrailers = headers; + this.#inner.pendingTrailers = headers; } /** @@ -1742,7 +1722,11 @@ class QuicStream { */ get stats() { QuicStream.#assertIsQuicStream(this); - return this.#stats; + if (this.#inner.stats === undefined) { + this.#inner.stats = new QuicStreamStats( + kPrivateConstructor, this.#handle.stats, this.#handle.statsByteOffset); + } + return this.#inner.stats; } /** @@ -1753,7 +1737,7 @@ class QuicStream { get session() { QuicStream.#assertIsQuicStream(this); if (this.destroyed) return null; - return this.#session; + return this.#inner.session; } /** @@ -1764,7 +1748,7 @@ class QuicStream { get id() { QuicStream.#assertIsQuicStream(this); if (this.destroyed || this.pending) return null; - return this.#state.id; + return this.#inner.state.id; } /** @@ -1775,7 +1759,7 @@ class QuicStream { get direction() { QuicStream.#assertIsQuicStream(this); if (this.destroyed || this.pending) return null; - return this.#direction === kStreamDirectionBidirectional ? 'bidi' : 'uni'; + return this.#inner.direction === kStreamDirectionBidirectional ? 'bidi' : 'uni'; } /** @@ -1793,7 +1777,10 @@ class QuicStream { */ get closed() { QuicStream.#assertIsQuicStream(this); - return this.#pendingClose.promise; + if (this.#inner.pendingClose === undefined) { + this.#inner.pendingClose = PromiseWithResolvers(); + } + return this.#inner.pendingClose.promise; } /** @@ -1829,7 +1816,7 @@ class QuicStream { // `onStreamClose -> [kFinishClose]` path - which does NOT go // through `destroy()` and therefore never sets `#destroying`. // `[kFinishClose]` clears `#handle` at the end of its work. - if (this.#destroying || this.destroyed) return; + if (this.#inner.destroying || this.destroyed) return; // Validate options up front so a malformed `options` argument // throws before any side effects (mutating `#destroying`, // emitting wire frames, invoking `onerror`, settling the closed @@ -1845,7 +1832,7 @@ class QuicStream { if (reason !== undefined) { validateString(reason, 'options.reason'); } - this.#destroying = true; + this.#inner.destroying = true; // Resolve the wire error code for any RESET_STREAM / STOP_SENDING // frames emitted below. let abortCode; @@ -1854,21 +1841,16 @@ class QuicStream { } else if (error !== undefined) { abortCode = error instanceof QuicError ? error.errorCode : - getQuicSessionState(this.#session).internalErrorCode; + getQuicSessionState(this.#inner.session).internalErrorCode; } // When destroying with an error, ensure the peer stops sending // data we are about to discard by emitting STOP_SENDING. The // condition gates the emission to error-path destroys with a - // still-open readable side. Direction model for the readable - // side: - // * bidi: always has a readable side. - // * uni + #reader !== undefined: remote-initiated, read-only. - // * uni + #reader === undefined: locally-initiated, write-only; - // no readable side to stop. + // still-open readable side. The C++ state.readEnded flag is + // authoritative -- it is set for locally-initiated uni streams + // (which have no readable side) and when reading completes. if (abortCode !== undefined && - !this.#state.readEnded && - (this.#direction === kStreamDirectionBidirectional || - this.#reader !== undefined)) { + !this.#inner.state.readEnded) { this.#handle.stopSending(abortCode); } // When destroying with an error, ensure the peer learns about @@ -1877,22 +1859,14 @@ class QuicStream { // streams that destroy without ever accessing stream.writer // (e.g. used setBody or never wrote at all) need an explicit // RESET_STREAM here so the write side does not dangle on the - // wire. The condition gates the emission to error-path destroys - // with a still-open writable side. - // Direction model for the writable side: - // * bidi: always has a writable side. - // * uni + #reader === undefined: locally-initiated, write-only. - // * uni + #reader !== undefined: remote-initiated, read-only; - // no writable side to reset. + // wire. The C++ state.writeEnded flag is authoritative. if (abortCode !== undefined && - this.#writer === undefined && - !this.#state.writeEnded && - (this.#direction === kStreamDirectionBidirectional || - this.#reader === undefined)) { + this.#inner.writer === undefined && + !this.#inner.state.writeEnded) { this.#handle.resetStream(abortCode); } - if (error !== undefined && typeof this.#onerror === 'function') { - invokeOnerror(this.#onerror, error); + if (error !== undefined && typeof this.#inner.onerror === 'function') { + invokeOnerror(this.#inner.onerror, error); } const handle = this.#handle; this[kFinishClose](error); @@ -1912,7 +1886,7 @@ class QuicStream { if (this.destroyed) { throw new ERR_INVALID_STATE('Stream is destroyed'); } - if (this.#state.hasOutbound) { + if (this.#inner.state.hasOutbound) { throw new ERR_INVALID_STATE('Stream already has an outbound data source'); } this.#handle.attachSource(validateBody(outbound)); @@ -1928,7 +1902,7 @@ class QuicStream { sendHeaders(headers, options = kEmptyObject) { QuicStream.#assertIsQuicStream(this); if (this.destroyed) return false; - if (getQuicSessionState(this.#session).headersSupported === 2) { + if (getQuicSessionState(this.#inner.session).headersSupported === 2) { throw new ERR_INVALID_STATE( 'The negotiated QUIC application protocol does not support headers'); } @@ -1949,7 +1923,7 @@ class QuicStream { sendInformationalHeaders(headers) { QuicStream.#assertIsQuicStream(this); if (this.destroyed) return false; - if (getQuicSessionState(this.#session).headersSupported === 2) { + if (getQuicSessionState(this.#inner.session).headersSupported === 2) { throw new ERR_INVALID_STATE( 'The negotiated QUIC application protocol does not support headers'); } @@ -1970,7 +1944,7 @@ class QuicStream { sendTrailers(headers) { QuicStream.#assertIsQuicStream(this); if (this.destroyed) return false; - if (getQuicSessionState(this.#session).headersSupported === 2) { + if (getQuicSessionState(this.#inner.session).headersSupported === 2) { throw new ERR_INVALID_STATE( 'The negotiated QUIC application protocol does not support headers'); } @@ -1988,8 +1962,8 @@ class QuicStream { */ get writer() { QuicStream.#assertIsQuicStream(this); - if (this.#writer !== undefined) return this.#writer; - if (this.#outboundSet) { + if (this.#inner.writer !== undefined) return this.#inner.writer; + if (this.#inner.outboundSet) { throw new ERR_INVALID_STATE( 'Stream outbound already configured with a body source'); } @@ -2020,7 +1994,7 @@ class QuicStream { // more data. Refuse the sync write. // If a drain is already pending, another operation is waiting // for capacity. Refuse the sync write. - if (closed || errored || stream.#state.writeEnded || drainWakeup != null) { + if (closed || errored || stream.#inner.state.writeEnded || drainWakeup != null) { return false; } chunk = toUint8Array(chunk); @@ -2034,7 +2008,7 @@ class QuicStream { // at which point the standard drain mechanism takes over. // This follows the Web Streams model where writes beyond the HWM // succeed and backpressure applies to *subsequent* writes. - if (stream.#state.writeDesiredSize === 0) return false; + if (stream.#inner.state.writeDesiredSize === 0) return false; const result = handle.write([chunk]); if (result === undefined) return false; totalBytesWritten += len; @@ -2049,7 +2023,7 @@ class QuicStream { signal.throwIfAborted(); } if (errored) throw error; - if (closed || stream.#state.writeEnded) { + if (closed || stream.#inner.state.writeEnded) { throw new ERR_INVALID_STATE('Writer is closed'); } // If a drain is already pending, another operation is waiting @@ -2066,14 +2040,14 @@ class QuicStream { } function writevSync(chunks) { - if (closed || errored || stream.#state.writeEnded || drainWakeup != null) { + if (closed || errored || stream.#inner.state.writeEnded || drainWakeup != null) { return false; } chunks = convertChunks(chunks); let len = 0; for (const c of chunks) len += TypedArrayPrototypeGetByteLength(c); if (len === 0) return true; - if (stream.#state.writeDesiredSize === 0) return false; + if (stream.#inner.state.writeDesiredSize === 0) return false; const result = handle.write(chunks); if (result === undefined) return false; totalBytesWritten += len; @@ -2089,7 +2063,7 @@ class QuicStream { } if (errored) throw error; - if (closed || stream.#state.writeEnded) { + if (closed || stream.#inner.state.writeEnded) { throw new ERR_INVALID_STATE('Writer is closed'); } @@ -2182,7 +2156,7 @@ class QuicStream { // `INTERNAL_ERROR` (0x1). const code = error instanceof QuicError ? error.errorCode : - getQuicSessionState(stream.#session).internalErrorCode; + getQuicSessionState(stream.#inner.session).internalErrorCode; handle.resetStream(code); if (drainWakeup != null) { drainWakeup.reject(error); @@ -2193,8 +2167,8 @@ class QuicStream { const writer = { __proto__: null, get desiredSize() { - if (closed || errored || stream.#state.writeEnded) return null; - return stream.#state.writeDesiredSize; + if (closed || errored || stream.#inner.state.writeEnded) return null; + return stream.#inner.state.writeDesiredSize; }, writeSync, write, @@ -2207,7 +2181,7 @@ class QuicStream { if (closed || errored) return null; // If a drain is already pending, return the existing promise. if (drainWakeup != null) return drainWakeup.promise; - if (stream.#state.writeDesiredSize > 0) return null; + if (stream.#inner.state.writeDesiredSize > 0) return null; drainWakeup = PromiseWithResolvers(); return drainWakeup.promise; }, @@ -2221,21 +2195,23 @@ class QuicStream { }; // Non-writable stream - return a pre-closed writer. - // A readable unidirectional stream is a remote uni (read-only). - if (!handle || this.destroyed || this.#state.writeEnded || - (this.#direction === kStreamDirectionUnidirectional && - this.#reader !== undefined)) { + // A remote unidirectional stream is read-only and has no writable + // side. isLocal distinguishes locally-initiated (writable) from + // remotely-initiated (read-only) uni streams. + if (!handle || this.destroyed || this.#inner.state.writeEnded || + (this.#inner.direction === kStreamDirectionUnidirectional && + !this.#inner.isLocal)) { closed = true; - this.#writer = writer; - return this.#writer; + this.#inner.writer = writer; + return this.#inner.writer; } // Initialize the outbound DataQueue for streaming writes handle.initStreamingSource(); initStreamingBackpressure(this); - this.#writer = writer; - return this.#writer; + this.#inner.writer = writer; + return this.#inner.writer; } /** @@ -2249,17 +2225,17 @@ class QuicStream { if (this.destroyed) { throw new ERR_INVALID_STATE('Stream is destroyed'); } - if (this.#outboundSet) { + if (this.#inner.outboundSet) { throw new ERR_INVALID_STATE('Stream outbound already configured'); } - if (this.#writer !== undefined) { + if (this.#inner.writer !== undefined) { throw new ERR_INVALID_STATE('Stream writer already accessed'); } - this.#outboundSet = true; + this.#inner.outboundSet = true; // If the body is a FileHandle, store it so it is closed // automatically when the stream finishes. if (body instanceof FileHandle) { - this.#fileHandle = body; + this.#inner.fileHandle = body; } configureOutbound(this.#handle, this, body); } @@ -2271,7 +2247,7 @@ class QuicStream { * @param {FileHandle} fh */ [kAttachFileHandle](fh) { - this.#fileHandle = fh; + this.#inner.fileHandle = fh; } /** @@ -2309,7 +2285,7 @@ class QuicStream { get priority() { QuicStream.#assertIsQuicStream(this); if (this.destroyed || - !getQuicSessionState(this.#session).isPrioritySupported) return null; + !getQuicSessionState(this.#inner.session).isPrioritySupported) return null; const packed = this.#handle.getPriority(); const urgency = packed >> 1; const incremental = !!(packed & 1); @@ -2327,7 +2303,7 @@ class QuicStream { setPriority(options = kEmptyObject) { QuicStream.#assertIsQuicStream(this); if (this.destroyed) return; - if (!getQuicSessionState(this.#session).isPrioritySupported) { + if (!getQuicSessionState(this.#inner.session).isPrioritySupported) { throw new ERR_INVALID_STATE( 'The session does not support stream priority'); } @@ -2357,7 +2333,7 @@ class QuicStream { [kSendHeaders](headers, kind = kHeadersKindInitial, flags = kHeadersFlagsTerminal) { validateObject(headers, 'headers'); - if (getQuicSessionState(this.#session).headersSupported === 2) { + if (getQuicSessionState(this.#inner.session).headersSupported === 2) { throw new ERR_INVALID_STATE( 'The negotiated QUIC application protocol does not support headers'); } @@ -2375,27 +2351,21 @@ class QuicStream { } [kFinishClose](error) { - if (this.destroyed) return this.#pendingClose.promise; - if (error !== undefined) { - if (this.pending) { - debug(`destroying pending stream with error: ${error}`); - } else { - debug(`destroying stream ${this.id} with error: ${error}`); - } - this.#pendingClose.reject(error); - } else { - if (this.pending) { - debug('destroying pending stream with no error'); - } else { - debug(`destroying stream ${this.id} with no error`); - } - this.#pendingClose.resolve(); + this.#inner.pendingClose ??= PromiseWithResolvers(); + if (this.destroyed) { + return this.#inner.pendingClose.promise; } + if (error !== undefined) { + this.#inner.pendingClose.reject(error); + } else { + this.#inner.pendingClose.resolve(); + } + debug('stream closed'); if (onStreamClosedChannel.hasSubscribers) { onStreamClosedChannel.publish({ __proto__: null, stream: this, - session: this.#session, + session: this.#inner.session, error, stats: this.stats, }); @@ -2408,46 +2378,44 @@ class QuicStream { }, }); } - this.#stats[kFinishClose](); - this.#state[kFinishClose](); - this.#session[kRemoveStream](this); - if (this.#writer !== undefined) { - this.#writer.fail(error); - } - this.#session = undefined; - this.#pendingClose.reject = undefined; - this.#pendingClose.resolve = undefined; - this.#onblocked = undefined; - this.#onreset = undefined; - this.#onheaders = undefined; - this.#onerror = undefined; - this.#ontrailers = undefined; - this.#oninfo = undefined; - this.#onwanttrailers = undefined; - this.#headers = undefined; - this.#pendingTrailers = undefined; + this.#inner.stats?.[kFinishClose](); + this.#inner.state?.[kFinishClose](); + this.#inner.session[kRemoveStream](this); + this.#inner.writer?.fail(error); + this.#inner.session = undefined; + this.#inner.pendingClose.reject = undefined; + this.#inner.pendingClose.resolve = undefined; + this.#inner.onblocked = undefined; + this.#inner.onreset = undefined; + this.#inner.onheaders = undefined; + this.#inner.onerror = undefined; + this.#inner.ontrailers = undefined; + this.#inner.oninfo = undefined; + this.#inner.onwanttrailers = undefined; + this.#inner.headers = undefined; + this.#inner.pendingTrailers = undefined; this.#handle = undefined; - if (this.#fileHandle !== undefined) { + if (this.#inner.fileHandle !== undefined) { // Close the FileHandle that was used as a body source. The close // may fail if the user already closed it -- that's expected and // harmless, so mark the promise as handled. - markPromiseAsHandled(this.#fileHandle.close()); - this.#fileHandle = undefined; + markPromiseAsHandled(this.#inner.fileHandle.close()); + this.#inner.fileHandle = undefined; } } [kBlocked]() { // The blocked event should only be called if the stream was created with // an onblocked callback. The callback should always exist here. - assert(this.#onblocked, 'Unexpected stream blocked event'); + assert(this.#inner.onblocked, 'Unexpected stream blocked event'); if (onStreamBlockedChannel.hasSubscribers) { onStreamBlockedChannel.publish({ __proto__: null, stream: this, - session: this.#session, + session: this.#inner.session, }); } - safeCallbackInvoke(this.#onblocked, this); + safeCallbackInvoke(this.#inner.onblocked, this); } [kDrain]() { @@ -2458,16 +2426,16 @@ class QuicStream { [kReset](error) { // The reset event should only be called if the stream was created with // an onreset callback. The callback should always exist here. - assert(this.#onreset, 'Unexpected stream reset event'); + assert(this.#inner.onreset, 'Unexpected stream reset event'); if (onStreamResetChannel.hasSubscribers) { onStreamResetChannel.publish({ __proto__: null, stream: this, - session: this.#session, + session: this.#inner.session, error, }); } - safeCallbackInvoke(this.#onreset, this, error); + safeCallbackInvoke(this.#inner.onreset, this, error); } [kHeaders](headers, kind) { @@ -2476,41 +2444,41 @@ class QuicStream { switch (kindName) { case 'initial': - assert(this.#onheaders, 'Unexpected stream headers event'); - if (this.#headers === undefined) this.#headers = block; + assert(this.#inner.onheaders, 'Unexpected stream headers event'); + this.#inner.headers ??= block; if (onStreamHeadersChannel.hasSubscribers) { onStreamHeadersChannel.publish({ __proto__: null, stream: this, - session: this.#session, + session: this.#inner.session, headers: block, }); } - safeCallbackInvoke(this.#onheaders, this, block); + safeCallbackInvoke(this.#inner.onheaders, this, block); break; case 'trailing': if (onStreamTrailersChannel.hasSubscribers) { onStreamTrailersChannel.publish({ __proto__: null, stream: this, - session: this.#session, + session: this.#inner.session, trailers: block, }); } - if (this.#ontrailers) - safeCallbackInvoke(this.#ontrailers, this, block); + if (this.#inner.ontrailers) + safeCallbackInvoke(this.#inner.ontrailers, this, block); break; case 'hints': if (onStreamInfoChannel.hasSubscribers) { onStreamInfoChannel.publish({ __proto__: null, stream: this, - session: this.#session, + session: this.#inner.session, headers: block, }); } - if (this.#oninfo) - safeCallbackInvoke(this.#oninfo, this, block); + if (this.#inner.oninfo) + safeCallbackInvoke(this.#inner.oninfo, this, block); break; } } @@ -2520,11 +2488,11 @@ class QuicStream { // nghttp3 is asking us to provide trailers to send. // Check for pre-set pendingTrailers first, then the callback. - if (this.#pendingTrailers) { - this.sendTrailers(this.#pendingTrailers); - this.#pendingTrailers = undefined; - } else if (this.#onwanttrailers) { - safeCallbackInvoke(this.#onwanttrailers, this); + if (this.#inner.pendingTrailers) { + this.sendTrailers(this.#inner.pendingTrailers); + this.#inner.pendingTrailers = undefined; + } else if (this.#inner.onwanttrailers) { + safeCallbackInvoke(this.#inner.onwanttrailers, this); } } @@ -2544,7 +2512,7 @@ class QuicStream { direction: this.direction, pending: this.pending, stats: this.stats, - state: this.#state, + state: this.#inner.state, session: this.session, }, opts)}`; } @@ -3071,7 +3039,8 @@ class QuicSession { handle.setPriority((urgency << 1) | (incremental ? 1 : 0)); } - const stream = new QuicStream(kPrivateConstructor, handle, this, direction); + const stream = new QuicStream( + kPrivateConstructor, handle, this, direction, true /* isLocal */); this.#streams.add(stream); if (typeof this.#onerror === 'function') { markPromiseAsHandled(stream.closed);