From 378dbf00e996ea421c2aede581d213f1d79faf1c Mon Sep 17 00:00:00 2001 From: James M Snell Date: Thu, 14 May 2026 12:47:09 -0700 Subject: [PATCH] quic: improve the quic js structure * Adds invalid this protections in the stats classes * Collects internal private fields into a single private symbol to reduce the number of private field accesses * Adds and corrects isQuic* class checks * Preserve stream id and direction after destroy * Improve stats close snapshotting * Fixes a handful of other bugs and doc issues Signed-off-by: James M Snell Assisted-by: Opencode:Opus 4.6 PR-URL: https://github.com/nodejs/node/pull/63267 Reviewed-By: Matteo Collina --- lib/internal/fs/promises.js | 6 + lib/internal/quic/quic.js | 1433 +++++++++-------- lib/internal/quic/state.js | 633 +++++--- lib/internal/quic/stats.js | 531 ++++-- lib/internal/quic/symbols.js | 4 - src/quic/session.cc | 2 + src/quic/streams.cc | 2 + .../parallel/test-quic-h3-headers-support.mjs | 43 +- ...est-quic-internal-endpoint-stats-state.mjs | 2 +- .../test-quic-session-stream-lifecycle.mjs | 7 +- 10 files changed, 1549 insertions(+), 1114 deletions(-) diff --git a/lib/internal/fs/promises.js b/lib/internal/fs/promises.js index 720bd1319b3..0aa01d9b39d 100644 --- a/lib/internal/fs/promises.js +++ b/lib/internal/fs/promises.js @@ -178,6 +178,12 @@ function handleErrorFromBinding(error) { } class FileHandle extends EventEmitter { + #brandCheck = undefined; + + static isFileHandle(value) { + return (value != null && typeof value === 'object' && #brandCheck in value); + } + /** * @param {InternalFSBinding.FileHandle | undefined} filehandle */ diff --git a/lib/internal/quic/quic.js b/lib/internal/quic/quic.js index 6082226edf4..0ae04441ea1 100644 --- a/lib/internal/quic/quic.js +++ b/lib/internal/quic/quic.js @@ -203,14 +203,13 @@ const { kTrailers, kVersionNegotiation, kInspect, - kWantsHeaders, - kWantsTrailers, } = require('internal/quic/symbols'); const { QuicEndpointStats, QuicStreamStats, QuicSessionStats, + kCreateDisconnected, } = require('internal/quic/stats'); const { @@ -464,6 +463,51 @@ const endpointRegistry = new SafeSet(); * @property {string} [validationErrorCode] The error code for the validation failure (if any) */ +/** + * @typedef {object} QuicStreamDestroyOptions + * @property {bigint|number} [code] An explicit application + * error code to send on the resulting `RESET_STREAM` / + * `STOP_SENDING` frames. Numbers are coerced to `BigInt`. When + * omitted, the code is derived from `error` per the precedence + * above. + * @property {string} [reason] Optional human-readable reason. + * Accepted for symmetry with `session.close()` / + * `session.destroy()`; QUIC `RESET_STREAM` and `STOP_SENDING` + * frames do not themselves carry a reason field over the wire. + */ + +/** + * @typedef {object} SendHeadersOptions + * @property {boolean} [terminal] When true, indicates that no body data will be + * sent after these headers. + */ + +/** + * @typedef {object} StreamPriority + * @property {'default' | 'low' | 'high'} level The priority level of the stream. + * @property {boolean} incremental Whether to interleave data with same-priority streams. + */ + +/** + * @typedef {object} QuicSessionPath + * @property {SocketAddress} local The local address for this path + * @property {SocketAddress} remote The remote address for this path + */ + +/** + * @typedef {object} SNIContextOptions + * @property {boolean} [replace] When `true`, the provided SNI context will replace + * the default context for the session. When `false` (default), the provided + * context will be merged with the default context, with precedence given to + * the provided context on any overlapping options. + */ + +/** + * @typedef {object} ProcessSessionOptions + * @property {boolean} forServer true if processing options for a server session + * @property {string} addressFamily the address family to use for validating + */ + /** * Called when the Endpoint receives a new server-side Session. * @callback OnSessionCallback @@ -658,7 +702,7 @@ setCallbacks({ }, /** * Called when the QuicEndpoint C++ handle receives a new server-side session - * @param {*} session The QuicSession C++ handle + * @param {object} session The QuicSession C++ handle */ onSessionNew(session) { debug('new server session callback', this[kOwner], session); @@ -792,9 +836,9 @@ setCallbacks({ /** * Called when the session receives a session version negotiation request - * @param {*} version - * @param {*} requestedVersions - * @param {*} supportedVersions + * @param {number} version + * @param {number[]} requestedVersions + * @param {number[]} supportedVersions */ onSessionVersionNegotiation(version, requestedVersions, @@ -885,6 +929,12 @@ setCallbacks({ }, }); +function assertPrivateSymbol(privateSymbol) { + if (privateSymbol !== kPrivateConstructor) { + throw new ERR_ILLEGAL_CONSTRUCTOR(); + } +} + // QUIC error codes are 62-bit varints (RFC 9000 section 16). The // maximum representable code is 2**62 - 1. const kMaxQuicErrorCode = (1n << 62n) - 1n; @@ -911,6 +961,10 @@ class QuicError extends Error { /** @type {'transport' | 'application'} */ #type; + static isQuicError(val) { + return val != null && typeof val === 'object' && #errorCode in val; + } + /** * @param {string} message * @param {object} options @@ -1089,7 +1143,7 @@ function validateBody(body) { // FileHandle -- lock it and pass the C++ handle to GetDataQueueFromSource // which creates an fd-backed DataQueue entry from the file path. - if (body instanceof FileHandle) { + if (FileHandle.isFileHandle(body)) { if (body[kFileLocked]) { throw new ERR_INVALID_STATE('FileHandle is locked'); } @@ -1166,7 +1220,7 @@ function applyCallbacks(session, cbs) { * type and calls the appropriate C++ method. * @param {object} handle The C++ stream handle * @param {QuicStream} stream The JS stream object - * @param {*} body The body source + * @param {any} body The body source */ const kDefaultHighWaterMark = 65536; const kDefaultMaxPendingDatagrams = 128; @@ -1208,7 +1262,7 @@ function configureOutbound(handle, stream, body) { // DataQueue entry from the file path. The FileHandle is locked to // prevent concurrent use and closed automatically when the stream // finishes. - if (body instanceof FileHandle) { + if (FileHandle.isFileHandle(body)) { if (body[kFileLocked]) { throw new ERR_INVALID_STATE('FileHandle is locked'); } @@ -1363,8 +1417,14 @@ let getQuicStreamState; let getQuicSessionState; let getQuicEndpointState; let assertIsQuicEndpoint; +let assertIsQuicStream; +let assertIsQuicSession; +let assertHeadersSupported; let assertEndpointNotClosedOrClosing; let assertEndpointIsNotBusy; +let isQuicStream; +let isQuicSession; +let isQuicEndpoint; function maybeGetCloseError(context, status, pendingError) { switch (context) { @@ -1391,73 +1451,74 @@ 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; - #inner; + #inner = { + __proto__: null, + session: undefined, + direction: undefined, + isLocal: false, + state: undefined, + stats: undefined, + pendingClose: undefined, + reader: undefined, + destroying: false, + iteratorLocked: false, + outboundSet: false, + writer: undefined, + fileHandle: undefined, + headers: undefined, + pendingTrailers: undefined, + onerror: undefined, + onblocked: undefined, + onreset: undefined, + onheaders: undefined, + ontrailers: undefined, + oninfo: undefined, + onwanttrailers: undefined, + }; static { + isQuicStream = function(val) { + return val != null && typeof val === 'object' && #handle in val; + }; + + assertIsQuicStream = function(val) { + if (!isQuicStream(val)) { + throw new ERR_INVALID_THIS('QuicStream'); + } + }; + + assertHeadersSupported = function(session) { + if (getQuicSessionState(session).headersSupported === 2) { + throw new ERR_INVALID_STATE( + 'The negotiated QUIC application protocol does not support headers'); + } + }; + getQuicStreamState = function(stream) { - QuicStream.#assertIsQuicStream(stream); + assertIsQuicStream(stream); return stream.#inner.state; }; } - static #assertIsQuicStream(val) { - if (val == null || !(#handle in val)) { - throw new ERR_INVALID_THIS('QuicStream'); - } - } - - #assertHeadersSupported() { - if (getQuicSessionState(this.#inner.session).headersSupported === 2) { - throw new ERR_INVALID_STATE( - 'The negotiated QUIC application protocol does not support headers'); - } - } - /** * @param {symbol} privateSymbol * @param {object} handle * @param {QuicSession} session * @param {number} direction - * @param {boolean} [isLocal] True for locally-initiated streams + * @param {boolean} [isLocal] */ - constructor(privateSymbol, handle, session, direction, isLocal = false) { - if (privateSymbol !== kPrivateConstructor) { - throw new ERR_ILLEGAL_CONSTRUCTOR(); - } + constructor(privateSymbol, handle, session, direction, isLocal) { + assertPrivateSymbol(privateSymbol); this.#handle = handle; 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, - }; + const inner = this.#inner; + inner.session = session; + inner.direction = direction; + inner.isLocal = isLocal; + inner.state = new QuicStreamState( + kPrivateConstructor, handle.state, handle.stateByteOffset); if (hasObserver('quic')) { startPerf(this, kPerfEntry, { type: 'quic', name: 'QuicStream' }); @@ -1475,17 +1536,18 @@ class QuicStream { * @yields {Uint8Array[]} */ async *[SymbolAsyncIterator]() { - QuicStream.#assertIsQuicStream(this); - if (this.#inner.iteratorLocked) { + assertIsQuicStream(this); + const inner = this.#inner; + if (inner.iteratorLocked) { throw new ERR_INVALID_STATE('Stream is already being read'); } - this.#inner.iteratorLocked = true; + inner.iteratorLocked = true; - this.#inner.reader ??= this.#handle?.getReader(); + inner.reader ??= this.#handle?.getReader(); // Non-readable stream (outbound-only unidirectional, or closed) - if (!this.#inner.reader) return; + if (!inner.reader) return; - yield* createBlobReaderIterable(this.#inner.reader, { + yield* createBlobReaderIterable(inner.reader, { getReadError: () => { // The read side ends for one of three reasons: // * Clean FIN received from the peer (state.finReceived @@ -1499,8 +1561,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.#inner.state.readEnded && !this.#inner.state.finReceived) { - const peerResetCode = this.#inner.state.resetCode; + if (inner.state.readEnded && !inner.state.finReceived) { + const peerResetCode = inner.state.resetCode; if (peerResetCode !== undefined && peerResetCode > 0n) { return new ERR_QUIC_STREAM_RESET(Number(peerResetCode)); } @@ -1518,7 +1580,7 @@ class QuicStream { * @type {boolean} */ get pending() { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); return this.#inner.state.pending; } @@ -1529,7 +1591,7 @@ class QuicStream { * @type {boolean} */ get early() { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); return this.#inner.state.early; } @@ -1540,145 +1602,153 @@ class QuicStream { * @type {number} */ get highWaterMark() { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); return this.#inner.state.highWaterMark; } set highWaterMark(val) { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); validateInteger(val, 'highWaterMark', 0, 0xFFFFFFFF); - this.#inner.state.highWaterMark = val; + const inner = this.#inner; + 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.#inner.state.writeDesiredSize === 0 && val > 0) { - this.#inner.state.writeDesiredSize = val; + if (inner.state.writeDesiredSize === 0 && val > 0) { + inner.state.writeDesiredSize = val; } } /** @type {Function|undefined} */ get onerror() { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); return this.#inner.onerror; } set onerror(fn) { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); + const inner = this.#inner; if (fn === undefined) { - this.#inner.onerror = undefined; + inner.onerror = undefined; } else { validateFunction(fn, 'onerror'); - this.#inner.onerror = FunctionPrototypeBind(fn, 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); + inner.pendingClose ??= PromiseWithResolvers(); + markPromiseAsHandled(inner.pendingClose.promise); } } /** @type {OnBlockedCallback} */ get onblocked() { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); return this.#inner.onblocked; } set onblocked(fn) { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); + const inner = this.#inner; if (fn === undefined) { - this.#inner.onblocked = undefined; - this.#inner.state.wantsBlock = false; + inner.onblocked = undefined; + inner.state.wantsBlock = false; } else { validateFunction(fn, 'onblocked'); - this.#inner.onblocked = FunctionPrototypeBind(fn, this); - this.#inner.state.wantsBlock = true; + inner.onblocked = FunctionPrototypeBind(fn, this); + inner.state.wantsBlock = true; } } /** @type {OnStreamErrorCallback} */ get onreset() { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); return this.#inner.onreset; } set onreset(fn) { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); + const inner = this.#inner; if (fn === undefined) { - this.#inner.onreset = undefined; - this.#inner.state.wantsReset = false; + inner.onreset = undefined; + inner.state.wantsReset = false; } else { validateFunction(fn, 'onreset'); - this.#inner.onreset = FunctionPrototypeBind(fn, this); - this.#inner.state.wantsReset = true; + inner.onreset = FunctionPrototypeBind(fn, this); + inner.state.wantsReset = true; } } /** @type {OnHeadersCallback} */ get onheaders() { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); return this.#inner.onheaders; } set onheaders(fn) { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); + const inner = this.#inner; if (fn === undefined) { - this.#inner.onheaders = undefined; - this.#inner.state[kWantsHeaders] = false; + inner.onheaders = undefined; + inner.state.wantsHeaders = false; } else { - this.#assertHeadersSupported(); validateFunction(fn, 'onheaders'); - this.#inner.onheaders = FunctionPrototypeBind(fn, this); - this.#inner.state[kWantsHeaders] = true; + assertHeadersSupported(inner.session); + inner.onheaders = FunctionPrototypeBind(fn, this); + inner.state.wantsHeaders = true; } } /** @type {Function|undefined} */ get oninfo() { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); return this.#inner.oninfo; } set oninfo(fn) { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); + const inner = this.#inner; if (fn === undefined) { - this.#inner.oninfo = undefined; + inner.oninfo = undefined; } else { - this.#assertHeadersSupported(); validateFunction(fn, 'oninfo'); - this.#inner.oninfo = FunctionPrototypeBind(fn, this); + assertHeadersSupported(inner.session); + inner.oninfo = FunctionPrototypeBind(fn, this); } } /** @type {Function|undefined} */ get ontrailers() { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); return this.#inner.ontrailers; } set ontrailers(fn) { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); + const inner = this.#inner; if (fn === undefined) { - this.#inner.ontrailers = undefined; + inner.ontrailers = undefined; } else { - this.#assertHeadersSupported(); validateFunction(fn, 'ontrailers'); - this.#inner.ontrailers = FunctionPrototypeBind(fn, this); + assertHeadersSupported(inner.session); + inner.ontrailers = FunctionPrototypeBind(fn, this); } } /** @type {Function|undefined} */ get onwanttrailers() { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); return this.#inner.onwanttrailers; } set onwanttrailers(fn) { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); + const inner = this.#inner; if (fn === undefined) { - this.#inner.onwanttrailers = undefined; - this.#inner.state[kWantsTrailers] = false; + inner.onwanttrailers = undefined; + inner.state.wantsTrailers = false; } else { - this.#assertHeadersSupported(); validateFunction(fn, 'onwanttrailers'); - this.#inner.onwanttrailers = FunctionPrototypeBind(fn, this); - this.#inner.state[kWantsTrailers] = true; + assertHeadersSupported(inner.session); + inner.onwanttrailers = FunctionPrototypeBind(fn, this); + inner.state.wantsTrailers = true; } } @@ -1689,7 +1759,7 @@ class QuicStream { * @type {object|undefined} */ get headers() { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); return this.#inner.headers; } @@ -1698,22 +1768,20 @@ class QuicStream { * @type {object|undefined} */ get pendingTrailers() { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); return this.#inner.pendingTrailers; } set pendingTrailers(headers) { - QuicStream.#assertIsQuicStream(this); + const inner = this.#inner; + assertIsQuicStream(this); + assertHeadersSupported(inner.session); if (headers === undefined) { - this.#inner.pendingTrailers = undefined; + inner.pendingTrailers = undefined; return; } - 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.#inner.pendingTrailers = headers; + inner.pendingTrailers = headers; } /** @@ -1721,12 +1789,12 @@ class QuicStream { * @type {QuicStreamStats} */ get stats() { - QuicStream.#assertIsQuicStream(this); - if (this.#inner.stats === undefined) { - this.#inner.stats = new QuicStreamStats( - kPrivateConstructor, this.#handle.stats, this.#handle.statsByteOffset); - } - return this.#inner.stats; + assertIsQuicStream(this); + const inner = this.#inner; + const handle = this.#handle; + return inner.stats ??= (handle == null) ? + QuicStreamStats[kCreateDisconnected]() : + new QuicStreamStats(kPrivateConstructor, handle.stats, handle.statsByteOffset); } /** @@ -1735,30 +1803,27 @@ class QuicStream { * @type {QuicSession | null} */ get session() { - QuicStream.#assertIsQuicStream(this); - if (this.destroyed) return null; + assertIsQuicStream(this); return this.#inner.session; } /** - * Returns the id for this stream. If the stream is destroyed or still pending, + * Returns the id for this stream. If the stream is still pending, * `null` will be returned. * @type {bigint | null} */ get id() { - QuicStream.#assertIsQuicStream(this); - if (this.destroyed || this.pending) return null; + assertIsQuicStream(this); + if (this.pending) return null; return this.#inner.state.id; } /** - * Returns the directionality of this stream. If the stream is destroyed - * or still pending, `null` will be returned. - * @type {'bidi'|'uni'|null} + * Returns the directionality of this stream. + * @type {'bidi'|'uni'} */ get direction() { - QuicStream.#assertIsQuicStream(this); - if (this.destroyed || this.pending) return null; + assertIsQuicStream(this); return this.#inner.direction === kStreamDirectionBidirectional ? 'bidi' : 'uni'; } @@ -1767,7 +1832,7 @@ class QuicStream { * @type {boolean} */ get destroyed() { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); return this.#handle === undefined; } @@ -1776,10 +1841,8 @@ class QuicStream { * @type {Promise} */ get closed() { - QuicStream.#assertIsQuicStream(this); - if (this.#inner.pendingClose === undefined) { - this.#inner.pendingClose = PromiseWithResolvers(); - } + assertIsQuicStream(this); + this.#inner.pendingClose ??= PromiseWithResolvers(); return this.#inner.pendingClose.promise; } @@ -1794,19 +1857,11 @@ class QuicStream { * `QuicError`) -> the negotiated application's "internal error" * code from `QuicSessionState.internalErrorCode`. * @param {any} error - * @param {object} [options] - * @param {bigint|number} [options.code] An explicit application - * error code to send on the resulting `RESET_STREAM` / - * `STOP_SENDING` frames. Numbers are coerced to `BigInt`. When - * omitted, the code is derived from `error` per the precedence - * above. - * @param {string} [options.reason] Optional human-readable reason. - * Accepted for symmetry with `session.close()` / - * `session.destroy()`; QUIC `RESET_STREAM` and `STOP_SENDING` - * frames do not themselves carry a reason field over the wire. + * @param {QuicStreamDestroyOptions} [options] */ destroy(error, options = kEmptyObject) { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); + const inner = this.#inner; // Two distinct guards: // * `#destroying` flips synchronously here so any re-entrant call // from inside this method's user callbacks hits the guard and @@ -1816,7 +1871,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.#inner.destroying || this.destroyed) return; + if (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 @@ -1832,16 +1887,16 @@ class QuicStream { if (reason !== undefined) { validateString(reason, 'options.reason'); } - this.#inner.destroying = true; + inner.destroying = true; // Resolve the wire error code for any RESET_STREAM / STOP_SENDING // frames emitted below. let abortCode; if (optionCode !== undefined) { abortCode = BigInt(optionCode); } else if (error !== undefined) { - abortCode = error instanceof QuicError ? + abortCode = QuicError.isQuicError(error) ? error.errorCode : - getQuicSessionState(this.#inner.session).internalErrorCode; + getQuicSessionState(inner.session).internalErrorCode; } // When destroying with an error, ensure the peer stops sending // data we are about to discard by emitting STOP_SENDING. The @@ -1850,7 +1905,7 @@ class QuicStream { // authoritative -- it is set for locally-initiated uni streams // (which have no readable side) and when reading completes. if (abortCode !== undefined && - !this.#inner.state.readEnded) { + !inner.state.readEnded) { this.#handle.stopSending(abortCode); } // When destroying with an error, ensure the peer learns about @@ -1861,12 +1916,12 @@ class QuicStream { // RESET_STREAM here so the write side does not dangle on the // wire. The C++ state.writeEnded flag is authoritative. if (abortCode !== undefined && - this.#inner.writer === undefined && - !this.#inner.state.writeEnded) { + inner.writer === undefined && + !inner.state.writeEnded) { this.#handle.resetStream(abortCode); } - if (error !== undefined && typeof this.#inner.onerror === 'function') { - invokeOnerror(this.#inner.onerror, error); + if (error !== undefined && typeof inner.onerror === 'function') { + invokeOnerror(inner.onerror, error); } const handle = this.#handle; this[kFinishClose](error); @@ -1882,7 +1937,7 @@ class QuicStream { * @param {ArrayBuffer|SharedArrayBuffer|ArrayBufferView|Blob} outbound */ setOutbound(outbound) { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); if (this.destroyed) { throw new ERR_INVALID_STATE('Stream is destroyed'); } @@ -1893,14 +1948,12 @@ class QuicStream { } /** - * Send initial or response headers on this stream. Throws if the - * application does not support headers. * @param {object} headers - * @param {{ terminal?: boolean }} [options] + * @param {SendHeadersOptions} [options] * @returns {boolean} */ sendHeaders(headers, options = kEmptyObject) { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); if (this.destroyed) return false; if (getQuicSessionState(this.#inner.session).headersSupported === 2) { throw new ERR_INVALID_STATE( @@ -1909,7 +1962,7 @@ class QuicStream { validateObject(headers, 'headers'); const { terminal = false } = options; const headerString = buildNgHeaderString( - headers, assertValidPseudoHeader, true); + headers, assertValidPseudoHeader, true /* strictSingleValueFields */); const flags = terminal ? kHeadersFlagsTerminal : kHeadersFlagsNone; return this.#handle.sendHeaders(kHeadersKindInitial, headerString, flags); } @@ -1921,7 +1974,7 @@ class QuicStream { * @returns {boolean} */ sendInformationalHeaders(headers) { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); if (this.destroyed) return false; if (getQuicSessionState(this.#inner.session).headersSupported === 2) { throw new ERR_INVALID_STATE( @@ -1942,7 +1995,7 @@ class QuicStream { * @returns {boolean} */ sendTrailers(headers) { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); if (this.destroyed) return false; if (getQuicSessionState(this.#inner.session).headersSupported === 2) { throw new ERR_INVALID_STATE( @@ -1961,9 +2014,10 @@ class QuicStream { * @type {object} */ get writer() { - QuicStream.#assertIsQuicStream(this); - if (this.#inner.writer !== undefined) return this.#inner.writer; - if (this.#inner.outboundSet) { + assertIsQuicStream(this); + const inner = this.#inner; + if (inner.writer !== undefined) return inner.writer; + if (inner.outboundSet) { throw new ERR_INVALID_STATE( 'Stream outbound already configured with a body source'); } @@ -2154,7 +2208,7 @@ class QuicStream { // `H3_INTERNAL_ERROR` (0x102); for raw QUIC applications // it falls back to the QUIC transport-layer // `INTERNAL_ERROR` (0x1). - const code = error instanceof QuicError ? + const code = QuicError.isQuicError(error) ? error.errorCode : getQuicSessionState(stream.#inner.session).internalErrorCode; handle.resetStream(code); @@ -2198,44 +2252,43 @@ class QuicStream { // 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)) { + if (!handle || this.destroyed || inner.state.writeEnded || + (inner.direction === kStreamDirectionUnidirectional && + !inner.isLocal)) { closed = true; - this.#inner.writer = writer; - return this.#inner.writer; + return inner.writer = writer; } // Initialize the outbound DataQueue for streaming writes handle.initStreamingSource(); initStreamingBackpressure(this); - this.#inner.writer = writer; - return this.#inner.writer; + return inner.writer = writer; } /** * Sets the outbound body source for this stream. Accepts all body * source types (string, TypedArray, Blob, AsyncIterable, Promise, null). * Can only be called once. Mutually exclusive with stream.writer. - * @param {*} body + * @param {any} body */ setBody(body) { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); if (this.destroyed) { throw new ERR_INVALID_STATE('Stream is destroyed'); } - if (this.#inner.outboundSet) { + const inner = this.#inner; + if (inner.outboundSet) { throw new ERR_INVALID_STATE('Stream outbound already configured'); } - if (this.#inner.writer !== undefined) { + if (inner.writer !== undefined) { throw new ERR_INVALID_STATE('Stream writer already accessed'); } - this.#inner.outboundSet = true; + 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.#inner.fileHandle = body; + if (FileHandle.isFileHandle(body)) { + inner.fileHandle = body; } configureOutbound(this.#handle, this, body); } @@ -2258,7 +2311,7 @@ class QuicStream { * @param {number|bigint} code */ stopSending(code = 0n) { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); if (this.destroyed) return; this.#handle.stopSending(BigInt(code)); } @@ -2271,7 +2324,7 @@ class QuicStream { * @param {number|bigint} code */ resetStream(code = 0n) { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); if (this.destroyed) return; this.#handle.resetStream(BigInt(code)); } @@ -2280,10 +2333,10 @@ class QuicStream { * The priority of the stream. If the stream is destroyed or if * the session does not support priority, `null` will be * returned. - * @type {{ level: 'default' | 'low' | 'high', incremental: boolean } | null} + * @type {StreamPriority | null} */ get priority() { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); if (this.destroyed || !getQuicSessionState(this.#inner.session).isPrioritySupported) return null; const packed = this.#handle.getPriority(); @@ -2295,13 +2348,10 @@ class QuicStream { /** * Sets the priority of the stream. - * @param {{ - * level?: 'default' | 'low' | 'high', - * incremental?: boolean, - * }} options + * @param {StreamPriority} [options] */ setPriority(options = kEmptyObject) { - QuicStream.#assertIsQuicStream(this); + assertIsQuicStream(this); if (this.destroyed) return; if (!getQuicSessionState(this.#inner.session).isPrioritySupported) { throw new ERR_INVALID_STATE( @@ -2351,21 +2401,22 @@ class QuicStream { } [kFinishClose](error) { - this.#inner.pendingClose ??= PromiseWithResolvers(); + const inner = this.#inner; + inner.pendingClose ??= PromiseWithResolvers(); if (this.destroyed) { - return this.#inner.pendingClose.promise; + return inner.pendingClose.promise; } if (error !== undefined) { - this.#inner.pendingClose.reject(error); + inner.pendingClose.reject(error); } else { - this.#inner.pendingClose.resolve(); + inner.pendingClose.resolve(); } debug('stream closed'); if (onStreamClosedChannel.hasSubscribers) { onStreamClosedChannel.publish({ __proto__: null, stream: this, - session: this.#inner.session, + session: inner.session, error, stats: this.stats, }); @@ -2378,44 +2429,45 @@ class QuicStream { }, }); } - 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; + inner.stats?.[kFinishClose](); + inner.state?.[kFinishClose](); + inner.session[kRemoveStream](this); + inner.writer?.fail(error); + inner.session = undefined; + inner.pendingClose.reject = undefined; + inner.pendingClose.resolve = undefined; + inner.onblocked = undefined; + inner.onreset = undefined; + inner.onheaders = undefined; + inner.onerror = undefined; + inner.ontrailers = undefined; + inner.oninfo = undefined; + inner.onwanttrailers = undefined; + inner.headers = undefined; + inner.pendingTrailers = undefined; this.#handle = undefined; - if (this.#inner.fileHandle !== undefined) { + if (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.#inner.fileHandle.close()); - this.#inner.fileHandle = undefined; + inner.fileHandle = undefined; } } [kBlocked]() { + const inner = this.#inner; // The blocked event should only be called if the stream was created with // an onblocked callback. The callback should always exist here. - assert(this.#inner.onblocked, 'Unexpected stream blocked event'); + assert(inner.onblocked, 'Unexpected stream blocked event'); if (onStreamBlockedChannel.hasSubscribers) { onStreamBlockedChannel.publish({ __proto__: null, stream: this, - session: this.#inner.session, + session: inner.session, }); } - safeCallbackInvoke(this.#inner.onblocked, this); + safeCallbackInvoke(inner.onblocked, this); } [kDrain]() { @@ -2424,81 +2476,85 @@ class QuicStream { } [kReset](error) { + const inner = this.#inner; // The reset event should only be called if the stream was created with // an onreset callback. The callback should always exist here. - assert(this.#inner.onreset, 'Unexpected stream reset event'); + assert(inner.onreset, 'Unexpected stream reset event'); if (onStreamResetChannel.hasSubscribers) { onStreamResetChannel.publish({ __proto__: null, stream: this, - session: this.#inner.session, + session: inner.session, error, }); } - safeCallbackInvoke(this.#inner.onreset, this, error); + safeCallbackInvoke(inner.onreset, this, error); } [kHeaders](headers, kind) { const block = parseHeaderPairs(headers); const kindName = kHeadersKindName[kind] ?? kind; + const inner = this.#inner; switch (kindName) { case 'initial': - assert(this.#inner.onheaders, 'Unexpected stream headers event'); - this.#inner.headers ??= block; + assert(inner.onheaders, 'Unexpected stream headers event'); + inner.headers ??= block; if (onStreamHeadersChannel.hasSubscribers) { onStreamHeadersChannel.publish({ __proto__: null, stream: this, - session: this.#inner.session, + session: inner.session, headers: block, }); } - safeCallbackInvoke(this.#inner.onheaders, this, block); + safeCallbackInvoke(inner.onheaders, this, block); break; case 'trailing': if (onStreamTrailersChannel.hasSubscribers) { onStreamTrailersChannel.publish({ __proto__: null, stream: this, - session: this.#inner.session, + session: inner.session, trailers: block, }); } - if (this.#inner.ontrailers) - safeCallbackInvoke(this.#inner.ontrailers, this, block); + if (inner.ontrailers) + safeCallbackInvoke(inner.ontrailers, this, block); break; case 'hints': if (onStreamInfoChannel.hasSubscribers) { onStreamInfoChannel.publish({ __proto__: null, stream: this, - session: this.#inner.session, + session: inner.session, headers: block, }); } - if (this.#inner.oninfo) - safeCallbackInvoke(this.#inner.oninfo, this, block); + if (typeof inner.oninfo === 'function') + safeCallbackInvoke(inner.oninfo, this, block); break; } } [kTrailers]() { if (this.destroyed) return; + const inner = this.#inner; // nghttp3 is asking us to provide trailers to send. // Check for pre-set pendingTrailers first, then the callback. - if (this.#inner.pendingTrailers) { - this.sendTrailers(this.#inner.pendingTrailers); - this.#inner.pendingTrailers = undefined; - } else if (this.#inner.onwanttrailers) { - safeCallbackInvoke(this.#inner.onwanttrailers, this); + if (inner.pendingTrailers) { + this.sendTrailers(inner.pendingTrailers); + inner.pendingTrailers = undefined; + } else if (typeof inner.onwanttrailers === 'function') { + safeCallbackInvoke(inner.onwanttrailers, this); } } [kInspect](depth, options) { - if (depth < 0) - return this; + if (depth < 0) { + return 'QuicStream { }'; + } const opts = { __proto__: null, @@ -2506,105 +2562,83 @@ class QuicStream { depth: options.depth == null ? null : options.depth - 1, }; + const { + id, + direction, + pending, + stats, + session, + } = this; + return `QuicStream ${inspect({ __proto__: null, - id: this.id, - direction: this.direction, - pending: this.pending, - stats: this.stats, + id, + direction, + pending, + stats, state: this.#inner.state, - session: this.session, + session, }, opts)}`; } } class QuicSession { - /** @type {QuicEndpoint} */ - #endpoint = undefined; - /** @type {boolean} */ - #isPendingClose = false; - /** @type {boolean} */ - #selfInitiatedClose = false; - /** - * Flag set at the top of `destroy()` to make the method safely - * re-entrant. Distinct from `#handle === undefined` so callbacks - * that fire from C++ during teardown (e.g. `onSessionClose` -> - * `[kFinishClose]`) still see a live `#handle` and can complete - * their work. - * @type {boolean} - */ - #destroying = false; - /** - * Set to `true` once the TLS handshake has completed successfully - * (i.e. `[kHandshake]` has fired). Used to gate operations that only - * make sense for a fully-opened session - notably, attempting to - * send a `CONNECTION_CLOSE` from `endpoint.destroy(error)` cascade. - * The C++ side cannot create a valid `CONNECTION_CLOSE` packet - * before handshake completion and falls back to a path that - * re-enters JS `destroy()` and trips our `#destroying` guard, - * leaving the C++ side asserting an inconsistent state. - * @type {boolean} - */ - #handshakeCompleted = false; /** @type {object|undefined} */ #handle; - /** @type {PromiseWithResolvers} */ - #pendingClose = PromiseWithResolvers(); - /** @type {PromiseWithResolvers} */ - #pendingOpen = PromiseWithResolvers(); - /** @type {QuicSessionState} */ - #state; - /** @type {QuicSessionStats} */ - #stats; - /** @type {Set} */ - #streams = new SafeSet(); - /** @type {Function|undefined} */ - #onerror = undefined; - /** @type {OnStreamCallback} */ - #onstream = undefined; - /** @type {OnDatagramCallback|undefined} */ - #ondatagram = undefined; - /** @type {OnDatagramStatusCallback|undefined} */ - #ondatagramstatus = undefined; - /** @type {Function|undefined} */ - #onpathvalidation = undefined; - /** @type {Function|undefined} */ - #onsessionticket = undefined; - /** @type {Function|undefined} */ - #onversionnegotiation = undefined; - /** @type {Function|undefined} */ - #onhandshake = undefined; - /** @type {Function|undefined} */ - #onnewtoken = undefined; - /** @type {Function|undefined} */ - #onearlyrejected = undefined; - /** @type {Function|undefined} */ - #onorigin = undefined; - /** @type {Function|undefined} */ - #ongoaway = undefined; - /** @type {Function|undefined} */ - #onkeylog = undefined; - /** @type {Function|undefined} */ - #onqlog = undefined; - #pendingQlog = undefined; - #handshakeInfo = undefined; - /** @type {{ local: SocketAddress, remote: SocketAddress }|undefined} */ - #path = undefined; - #certificate = undefined; - #peerCertificate = undefined; - #ephemeralKeyInfo = undefined; + + #inner = { + __proto__: null, + /** @type {QuicEndpoint} */ + endpoint: undefined, + isPendingClose: false, + selfInitiatedClose: false, + destroying: false, + handshakeCompleted: false, + pendingClose: PromiseWithResolvers(), + pendingOpen: PromiseWithResolvers(), + /** @type {QuicSessionState} */ + state: undefined, + /** @type {QuicSessionStats} */ + stats: undefined, + streams: new SafeSet(), + onerror: undefined, + onstream: undefined, + ondatagram: undefined, + ondatagramstatus: undefined, + onpathvalidation: undefined, + onsessionticket: undefined, + onversionnegotiation: undefined, + onhandshake: undefined, + onnewtoken: undefined, + onearlyrejected: undefined, + onorigin: undefined, + ongoaway: undefined, + onkeylog: undefined, + onqlog: undefined, + pendingQlog: undefined, + handshakeInfo: undefined, + /** @type {QuicSessionPath|undefined} */ + path: undefined, + certificate: undefined, + peerCertificate: undefined, + ephemeralKeyInfo: undefined, + }; static { - getQuicSessionState = function(session) { - QuicSession.#assertIsQuicSession(session); - return session.#state; + isQuicSession = function(val) { + return val != null && typeof val === 'object' && #handle in val; }; - } - static #assertIsQuicSession(val) { - if (val == null || !(#handle in val)) { - throw new ERR_INVALID_THIS('QuicSession'); - } + assertIsQuicSession = function(val) { + if (!isQuicSession(val)) { + throw new ERR_INVALID_THIS('QuicSession'); + } + }; + + getQuicSessionState = function(session) { + assertIsQuicSession(session); + return session.#inner.state; + }; } /** @@ -2614,21 +2648,21 @@ class QuicSession { */ constructor(privateSymbol, handle, endpoint) { // Instances of QuicSession can only be created internally. - if (privateSymbol !== kPrivateConstructor) { - throw new ERR_ILLEGAL_CONSTRUCTOR(); - } + assertPrivateSymbol(privateSymbol); - this.#endpoint = endpoint; this.#handle = handle; this.#handle[kOwner] = this; + + const inner = this.#inner; + inner.endpoint = endpoint; // Move any qlog entries that arrived before the wrapper existed. if (handle._pendingQlog !== undefined) { - this.#pendingQlog = handle._pendingQlog; + inner.pendingQlog = handle._pendingQlog; handle._pendingQlog = undefined; } - this.#stats = new QuicSessionStats( + inner.stats = new QuicSessionStats( kPrivateConstructor, handle.stats, handle.statsByteOffset); - this.#state = new QuicSessionState( + inner.state = new QuicSessionState( kPrivateConstructor, handle.state, handle.stateByteOffset); if (hasObserver('quic')) { @@ -2640,32 +2674,33 @@ class QuicSession { /** @type {boolean} */ get #isClosedOrClosing() { - return this.#handle === undefined || this.#isPendingClose; + return this.#handle === undefined || this.#inner.isPendingClose; } /** @type {Function|undefined} */ get onerror() { - QuicSession.#assertIsQuicSession(this); - return this.#onerror; + assertIsQuicSession(this); + return this.#inner.onerror; } set onerror(fn) { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); + const inner = this.#inner; if (fn === undefined) { - this.#onerror = undefined; + inner.onerror = undefined; } else { validateFunction(fn, 'onerror'); - this.#onerror = FunctionPrototypeBind(fn, this); + inner.onerror = FunctionPrototypeBind(fn, this); // When an onerror handler is provided, mark the pending promises // as handled so that rejections from destroy(error) don't surface // as unhandled rejections. The onerror callback is the // application's error handler for this session. - markPromiseAsHandled(this.#pendingClose.promise); - markPromiseAsHandled(this.#pendingOpen.promise); + markPromiseAsHandled(inner.pendingClose.promise); + markPromiseAsHandled(inner.pendingOpen.promise); // Also mark existing streams' closed promises. Stream rejections // during session destruction are expected collateral when the // session has an error handler. - for (const stream of this.#streams) { + for (const stream of inner.streams) { markPromiseAsHandled(stream.closed); } } @@ -2673,35 +2708,37 @@ class QuicSession { /** @type {OnStreamCallback} */ get onstream() { - QuicSession.#assertIsQuicSession(this); - return this.#onstream; + assertIsQuicSession(this); + return this.#inner.onstream; } set onstream(fn) { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); + const inner = this.#inner; if (fn === undefined) { - this.#onstream = undefined; + inner.onstream = undefined; } else { validateFunction(fn, 'onstream'); - this.#onstream = FunctionPrototypeBind(fn, this); + inner.onstream = FunctionPrototypeBind(fn, this); } } /** @type {OnDatagramCallback} */ get ondatagram() { - QuicSession.#assertIsQuicSession(this); - return this.#ondatagram; + assertIsQuicSession(this); + return this.#inner.ondatagram; } set ondatagram(fn) { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); + const inner = this.#inner; if (fn === undefined) { - this.#ondatagram = undefined; - this.#state.hasDatagramListener = false; + inner.ondatagram = undefined; + inner.state.hasDatagramListener = false; } else { validateFunction(fn, 'ondatagram'); - this.#ondatagram = FunctionPrototypeBind(fn, this); - this.#state.hasDatagramListener = true; + inner.ondatagram = FunctionPrototypeBind(fn, this); + inner.state.hasDatagramListener = true; } } @@ -2711,71 +2748,75 @@ class QuicSession { * @type {OnDatagramStatusCallback} */ get ondatagramstatus() { - QuicSession.#assertIsQuicSession(this); - return this.#ondatagramstatus; + assertIsQuicSession(this); + return this.#inner.ondatagramstatus; } set ondatagramstatus(fn) { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); + const inner = this.#inner; if (fn === undefined) { - this.#ondatagramstatus = undefined; - this.#state.hasDatagramStatusListener = false; + inner.ondatagramstatus = undefined; + inner.state.hasDatagramStatusListener = false; } else { validateFunction(fn, 'ondatagramstatus'); - this.#ondatagramstatus = FunctionPrototypeBind(fn, this); - this.#state.hasDatagramStatusListener = true; + inner.ondatagramstatus = FunctionPrototypeBind(fn, this); + inner.state.hasDatagramStatusListener = true; } } /** @type {Function|undefined} */ get onpathvalidation() { - QuicSession.#assertIsQuicSession(this); - return this.#onpathvalidation; + assertIsQuicSession(this); + return this.#inner.onpathvalidation; } set onpathvalidation(fn) { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); + const inner = this.#inner; if (fn === undefined) { - this.#onpathvalidation = undefined; - this.#state.hasPathValidationListener = false; + inner.onpathvalidation = undefined; + inner.state.hasPathValidationListener = false; } else { validateFunction(fn, 'onpathvalidation'); - this.#onpathvalidation = FunctionPrototypeBind(fn, this); - this.#state.hasPathValidationListener = true; + inner.onpathvalidation = FunctionPrototypeBind(fn, this); + inner.state.hasPathValidationListener = true; } } get onkeylog() { - QuicSession.#assertIsQuicSession(this); - return this.#onkeylog; + assertIsQuicSession(this); + return this.#inner.onkeylog; } set onkeylog(fn) { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); + const inner = this.#inner; if (fn === undefined) { - this.#onkeylog = undefined; + inner.onkeylog = undefined; } else { validateFunction(fn, 'onkeylog'); - this.#onkeylog = FunctionPrototypeBind(fn, this); + inner.onkeylog = FunctionPrototypeBind(fn, this); } } get onqlog() { - QuicSession.#assertIsQuicSession(this); - return this.#onqlog; + assertIsQuicSession(this); + return this.#inner.onqlog; } set onqlog(fn) { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); + const inner = this.#inner; if (fn === undefined) { - this.#onqlog = undefined; + inner.onqlog = undefined; } else { validateFunction(fn, 'onqlog'); - this.#onqlog = FunctionPrototypeBind(fn, this); + inner.onqlog = FunctionPrototypeBind(fn, this); // Flush any qlog entries that were cached before the callback was set. - if (this.#pendingQlog !== undefined) { - const pending = this.#pendingQlog; - this.#pendingQlog = undefined; + if (inner.pendingQlog !== undefined) { + const pending = inner.pendingQlog; + inner.pendingQlog = undefined; for (let i = 0; i < pending.length; i += 2) { this[kQlog](pending[i], pending[i + 1]); } @@ -2785,119 +2826,126 @@ class QuicSession { /** @type {Function|undefined} */ get onsessionticket() { - QuicSession.#assertIsQuicSession(this); - return this.#onsessionticket; + assertIsQuicSession(this); + return this.#inner.onsessionticket; } set onsessionticket(fn) { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); + const inner = this.#inner; if (fn === undefined) { - this.#onsessionticket = undefined; - this.#state.hasSessionTicketListener = false; + inner.onsessionticket = undefined; + inner.state.hasSessionTicketListener = false; } else { validateFunction(fn, 'onsessionticket'); - this.#onsessionticket = FunctionPrototypeBind(fn, this); - this.#state.hasSessionTicketListener = true; + inner.onsessionticket = FunctionPrototypeBind(fn, this); + inner.state.hasSessionTicketListener = true; } } /** @type {Function|undefined} */ get onversionnegotiation() { - QuicSession.#assertIsQuicSession(this); - return this.#onversionnegotiation; + assertIsQuicSession(this); + return this.#inner.onversionnegotiation; } set onversionnegotiation(fn) { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); + const inner = this.#inner; if (fn === undefined) { - this.#onversionnegotiation = undefined; + inner.onversionnegotiation = undefined; } else { validateFunction(fn, 'onversionnegotiation'); - this.#onversionnegotiation = FunctionPrototypeBind(fn, this); + inner.onversionnegotiation = FunctionPrototypeBind(fn, this); } } /** @type {Function|undefined} */ get onhandshake() { - QuicSession.#assertIsQuicSession(this); - return this.#onhandshake; + assertIsQuicSession(this); + return this.#inner.onhandshake; } set onhandshake(fn) { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); + const inner = this.#inner; if (fn === undefined) { - this.#onhandshake = undefined; + inner.onhandshake = undefined; } else { validateFunction(fn, 'onhandshake'); - this.#onhandshake = FunctionPrototypeBind(fn, this); + inner.onhandshake = FunctionPrototypeBind(fn, this); } } /** @type {Function|undefined} */ get onnewtoken() { - QuicSession.#assertIsQuicSession(this); - return this.#onnewtoken; + assertIsQuicSession(this); + return this.#inner.onnewtoken; } set onnewtoken(fn) { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); + const inner = this.#inner; if (fn === undefined) { - this.#onnewtoken = undefined; - this.#state.hasNewTokenListener = false; + inner.onnewtoken = undefined; + inner.state.hasNewTokenListener = false; } else { validateFunction(fn, 'onnewtoken'); - this.#onnewtoken = FunctionPrototypeBind(fn, this); - this.#state.hasNewTokenListener = true; + inner.onnewtoken = FunctionPrototypeBind(fn, this); + inner.state.hasNewTokenListener = true; } } /** @type {Function|undefined} */ get onearlyrejected() { - QuicSession.#assertIsQuicSession(this); - return this.#onearlyrejected; + assertIsQuicSession(this); + return this.#inner.onearlyrejected; } set onearlyrejected(fn) { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); + const inner = this.#inner; if (fn === undefined) { - this.#onearlyrejected = undefined; + inner.onearlyrejected = undefined; } else { validateFunction(fn, 'onearlyrejected'); - this.#onearlyrejected = FunctionPrototypeBind(fn, this); + inner.onearlyrejected = FunctionPrototypeBind(fn, this); } } /** @type {Function|undefined} */ get onorigin() { - QuicSession.#assertIsQuicSession(this); - return this.#onorigin; + assertIsQuicSession(this); + return this.#inner.onorigin; } set onorigin(fn) { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); + const inner = this.#inner; if (fn === undefined) { - this.#onorigin = undefined; - this.#state.hasOriginListener = false; + inner.onorigin = undefined; + inner.state.hasOriginListener = false; } else { validateFunction(fn, 'onorigin'); - this.#onorigin = FunctionPrototypeBind(fn, this); - this.#state.hasOriginListener = true; + inner.onorigin = FunctionPrototypeBind(fn, this); + inner.state.hasOriginListener = true; } } /** @type {Function|undefined} */ get ongoaway() { - QuicSession.#assertIsQuicSession(this); - return this.#ongoaway; + assertIsQuicSession(this); + return this.#inner.ongoaway; } set ongoaway(fn) { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); + const inner = this.#inner; if (fn === undefined) { - this.#ongoaway = undefined; + inner.ongoaway = undefined; } else { validateFunction(fn, 'ongoaway'); - this.#ongoaway = FunctionPrototypeBind(fn, this); + inner.ongoaway = FunctionPrototypeBind(fn, this); } } @@ -2907,8 +2955,8 @@ class QuicSession { * @type {bigint} */ get maxDatagramSize() { - QuicSession.#assertIsQuicSession(this); - return this.#state.maxDatagramSize; + assertIsQuicSession(this); + return this.#inner.state.maxDatagramSize; } /** @@ -2918,14 +2966,14 @@ class QuicSession { * @type {number} */ get maxPendingDatagrams() { - QuicSession.#assertIsQuicSession(this); - return this.#state.maxPendingDatagrams; + assertIsQuicSession(this); + return this.#inner.state.maxPendingDatagrams; } set maxPendingDatagrams(val) { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); validateInteger(val, 'maxPendingDatagrams', 0, 0xFFFF); - this.#state.maxPendingDatagrams = val; + this.#inner.state.maxPendingDatagrams = val; } /** @@ -2933,8 +2981,8 @@ class QuicSession { * @type {QuicSessionStats} */ get stats() { - QuicSession.#assertIsQuicSession(this); - return this.#stats; + assertIsQuicSession(this); + return this.#inner.stats; } /** @@ -2943,19 +2991,19 @@ class QuicSession { * @type {QuicEndpoint|null} */ get endpoint() { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); if (this.destroyed) return null; - return this.#endpoint; + return this.#inner.endpoint; } /** * The local and remote socket addresses associated with the session. - * @type {{ local: SocketAddress, remote: SocketAddress } | undefined} + * @type {QuicSessionPath | undefined} */ get path() { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); if (this.destroyed) return undefined; - return this.#path ??= { + return this.#inner.path ??= { __proto__: null, local: new InternalSocketAddress(this.#handle.getLocalAddress()), remote: new InternalSocketAddress(this.#handle.getRemoteAddress()), @@ -2967,9 +3015,9 @@ class QuicSession { * @type {object|undefined} */ get certificate() { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); if (this.destroyed) return undefined; - return this.#certificate ??= this.#handle.getCertificate(); + return this.#inner.certificate ??= this.#handle.getCertificate(); } /** @@ -2978,9 +3026,9 @@ class QuicSession { * @type {object|undefined} */ get peerCertificate() { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); if (this.destroyed) return undefined; - return this.#peerCertificate ??= this.#handle.getPeerCertificate(); + return this.#inner.peerCertificate ??= this.#handle.getPeerCertificate(); } /** @@ -2990,9 +3038,9 @@ class QuicSession { * @type {object|undefined} */ get ephemeralKeyInfo() { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); if (this.destroyed) return undefined; - return this.#ephemeralKeyInfo ??= this.#handle.getEphemeralKey(); + return this.#inner.ephemeralKeyInfo ??= this.#handle.getEphemeralKey(); } /** @@ -3001,11 +3049,12 @@ class QuicSession { * @returns {QuicStream} */ async #createStream(direction, options = kEmptyObject) { + const inner = this.#inner; if (this.#isClosedOrClosing) { throw new ERR_INVALID_STATE('Session is closed. New streams cannot be opened.'); } const dir = direction === kStreamDirectionBidirectional ? 'bidi' : 'uni'; - if (this.#state.isStreamOpenAllowed) { + if (inner.state.isStreamOpenAllowed) { debug(`opening new pending ${dir} stream`); } else { debug(`opening new ${dir} stream`); @@ -3034,21 +3083,21 @@ class QuicSession { throw new ERR_QUIC_OPEN_STREAM_FAILED(); } - if (this.#state.isPrioritySupported) { + if (inner.state.isPrioritySupported) { const urgency = priority === 'high' ? 0 : priority === 'low' ? 7 : 3; handle.setPriority((urgency << 1) | (incremental ? 1 : 0)); } const stream = new QuicStream( kPrivateConstructor, handle, this, direction, true /* isLocal */); - this.#streams.add(stream); - if (typeof this.#onerror === 'function') { + inner.streams.add(stream); + if (typeof this.#inner.onerror === 'function') { markPromiseAsHandled(stream.closed); } // If the body was a FileHandle, store it on the stream so it is // closed automatically when the stream finishes. - if (body instanceof FileHandle) { + if (FileHandle.isFileHandle(body)) { stream[kAttachFileHandle](body); } @@ -3083,7 +3132,7 @@ class QuicSession { * @returns {Promise} */ async createBidirectionalStream(options = kEmptyObject) { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); return await this.#createStream(kStreamDirectionBidirectional, options); } @@ -3094,7 +3143,7 @@ class QuicSession { * @returns {Promise} */ async createUnidirectionalStream(options = kEmptyObject) { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); return await this.#createStream(kStreamDirectionUnidirectional, options); } @@ -3119,12 +3168,12 @@ class QuicSession { * @returns {Promise} The datagram ID */ async sendDatagram(datagram, encoding = 'utf8') { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); if (this.#isClosedOrClosing) { throw new ERR_INVALID_STATE('Session is closed'); } - const maxDatagramSize = this.#state.maxDatagramSize; + const maxDatagramSize = this.#inner.state.maxDatagramSize; // The peer max datagram size is either unknown or they have explicitly // indicated that they do not support datagrams by setting it to 0. In @@ -3177,7 +3226,7 @@ class QuicSession { * Initiate a key update. */ updateKey() { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); if (this.#isClosedOrClosing) { throw new ERR_INVALID_STATE('Session is closed'); } @@ -3211,12 +3260,13 @@ class QuicSession { * @returns {Promise} */ close(options = kEmptyObject) { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); options = validateCloseOptions(options); + const inner = this.#inner; if (!this.#isClosedOrClosing) { - this.#isPendingClose = true; + inner.isPendingClose = true; if (options?.code !== undefined) { - this.#selfInitiatedClose = true; + inner.selfInitiatedClose = true; } debug('gracefully closing the session'); @@ -3234,13 +3284,13 @@ class QuicSession { /** @type {boolean} */ get closing() { - return this.#isPendingClose; + return this.#inner.isPendingClose; } /** @type {Promise} */ get opened() { - QuicSession.#assertIsQuicSession(this); - return this.#pendingOpen.promise; + assertIsQuicSession(this); + return this.#inner.pendingOpen.promise; } /** @@ -3249,13 +3299,13 @@ class QuicSession { * @type {Promise} */ get closed() { - QuicSession.#assertIsQuicSession(this); - return this.#pendingClose.promise; + assertIsQuicSession(this); + return this.#inner.pendingClose.promise; } /** @type {boolean} */ get destroyed() { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); return this.#handle === undefined; } @@ -3275,7 +3325,8 @@ class QuicSession { * string included in the CONNECTION_CLOSE frame (diagnostic only). */ destroy(error, options) { - QuicSession.#assertIsQuicSession(this); + assertIsQuicSession(this); + const inner = this.#inner; // Two distinct guards (see also `QuicStream.destroy`): // * `#destroying` flips synchronously here so any re-entrant call // (e.g. from a user `onerror` callback or from a cascading @@ -3286,10 +3337,10 @@ class QuicSession { // "fully torn down". Defense-in-depth for paths that may have // finished teardown without setting `#destroying` and for // repeat invocations after this method has fully run. - if (this.#destroying || this.destroyed) return; + if (inner.destroying || this.destroyed) return; if (options !== undefined) options = validateCloseOptions(options); - this.#destroying = true; + inner.destroying = true; debug('destroying the session'); @@ -3301,31 +3352,31 @@ class QuicSession { error, }); } - if (typeof this.#onerror === 'function') { - invokeOnerror(this.#onerror, error); + if (typeof inner.onerror === 'function') { + invokeOnerror(inner.onerror, error); } } // First, forcefully and immediately destroy all open streams, if any. - for (const stream of this.#streams) { + for (const stream of inner.streams) { stream.destroy(error); } // The streams should remove themselves when they are destroyed but let's // be doubly sure. - if (this.#streams.size) { + if (inner.streams.size) { process.emitWarning( - `The session is destroyed with ${this.#streams.size} active streams. ` + + `The session is destroyed with ${inner.streams.size} active streams. ` + 'This should not happen and indicates a bug in Node.js. Please open an ' + 'issue in the Node.js GitHub repository at https://github.com/nodejs/node ' + 'to report the problem.', ); } - this.#streams.clear(); + inner.streams.clear(); // Remove this session immediately from the endpoint - this.#endpoint[kRemoveSession](this); - this.#endpoint = undefined; - this.#isPendingClose = false; + inner.endpoint[kRemoveSession](this); + inner.endpoint = undefined; + inner.isPendingClose = false; // If the handshake never completed, reject the opened promise. The // session is being destroyed, so the handshake will never complete @@ -3341,54 +3392,54 @@ class QuicSession { // rejection warning - common for server-side sessions delivered via // `onsession`, which often do not await opened. The rejection is // still observable via `await session.opened`. - if (this.#pendingOpen.reject) { - markPromiseAsHandled(this.#pendingOpen.promise); - this.#pendingOpen.reject(error ?? new ERR_INVALID_STATE( + if (inner.pendingOpen.reject) { + markPromiseAsHandled(inner.pendingOpen.promise); + inner.pendingOpen.reject(error ?? new ERR_INVALID_STATE( 'Session was destroyed before it opened')); } if (error) { // If the session is still waiting to be closed, and error // is specified, reject the closed promise. - this.#pendingClose.reject?.(error); + inner.pendingClose.reject?.(error); } else { - this.#pendingClose.resolve?.(); + inner.pendingClose.resolve?.(); } - this.#pendingClose.reject = undefined; - this.#pendingClose.resolve = undefined; - this.#pendingOpen.reject = undefined; - this.#pendingOpen.resolve = undefined; + inner.pendingClose.reject = undefined; + inner.pendingClose.resolve = undefined; + inner.pendingOpen.reject = undefined; + inner.pendingOpen.resolve = undefined; - this.#state[kFinishClose](); - this.#stats[kFinishClose](); + inner.state[kFinishClose](); + inner.stats[kFinishClose](); if (this[kPerfEntry] && hasObserver('quic')) { stopPerf(this, kPerfEntry, { detail: { - stats: this.stats, - handshake: this.#handshakeInfo, - path: this.#path, + stats: inner.stats, + handshake: inner.handshakeInfo, + path: inner.path, }, }); } - this.#onerror = undefined; - this.#onstream = undefined; - this.#ondatagram = undefined; - this.#ondatagramstatus = undefined; - this.#onpathvalidation = undefined; - this.#onsessionticket = undefined; - this.#onkeylog = undefined; - this.#onversionnegotiation = undefined; - this.#onhandshake = undefined; - this.#onnewtoken = undefined; - this.#onorigin = undefined; - this.#ongoaway = undefined; - this.#path = undefined; - this.#certificate = undefined; - this.#peerCertificate = undefined; - this.#ephemeralKeyInfo = undefined; + inner.onerror = undefined; + inner.onstream = undefined; + inner.ondatagram = undefined; + inner.ondatagramstatus = undefined; + inner.onpathvalidation = undefined; + inner.onsessionticket = undefined; + inner.onkeylog = undefined; + inner.onversionnegotiation = undefined; + inner.onhandshake = undefined; + inner.onnewtoken = undefined; + inner.onorigin = undefined; + inner.ongoaway = undefined; + inner.path = undefined; + inner.certificate = undefined; + inner.peerCertificate = undefined; + inner.ephemeralKeyInfo = undefined; // Destroy the underlying C++ handle. Pass close error options if // provided so the CONNECTION_CLOSE frame carries the correct code. @@ -3404,7 +3455,7 @@ class QuicSession { __proto__: null, session: this, error, - stats: this.stats, + stats: inner.stats, }); } } @@ -3416,7 +3467,8 @@ class QuicSession { * @param {bigint} lastStreamId */ [kGoaway](lastStreamId) { - this.#isPendingClose = true; + const inner = this.#inner; + inner.isPendingClose = true; if (onSessionClosingChannel.hasSubscribers) { onSessionClosingChannel.publish({ __proto__: null, session: this }); } @@ -3427,8 +3479,8 @@ class QuicSession { lastStreamId, }); } - if (this.#ongoaway) { - safeCallbackInvoke(this.#ongoaway, this, lastStreamId); + if (typeof inner.ongoaway === 'function') { + safeCallbackInvoke(inner.ongoaway, this, lastStreamId); } } @@ -3451,7 +3503,7 @@ class QuicSession { // If the local side initiated this close with an error code (via // close({ code })), this is an intentional shutdown; not an error. // The closed promise should resolve, not reject. - if (this.#selfInitiatedClose) { + if (this.#inner.selfInitiatedClose) { this.destroy(); return; } @@ -3491,13 +3543,15 @@ class QuicSession { } [kKeylog](line) { - if (this.destroyed || this.onkeylog === undefined) return; - safeCallbackInvoke(this.#onkeylog, this, line); + const inner = this.#inner; + if (this.destroyed || inner.onkeylog === undefined) return; + safeCallbackInvoke(inner.onkeylog, this, line); } [kQlog](data, fin) { - if (this.onqlog === undefined) return; - safeCallbackInvoke(this.#onqlog, this, data, fin); + const inner = this.#inner; + if (inner.onqlog === undefined) return; + safeCallbackInvoke(inner.onqlog, this, data, fin); } /** @@ -3507,7 +3561,8 @@ class QuicSession { [kDatagram](u8, early) { // The datagram event should only be called if the session has // an ondatagram callback. The callback should always exist here. - assert(typeof this.#ondatagram === 'function', 'Unexpected datagram event'); + const inner = this.#inner; + assert(typeof inner.ondatagram === 'function', 'Unexpected datagram event'); if (this.destroyed) return; const length = TypedArrayPrototypeGetByteLength(u8); if (onSessionReceiveDatagramChannel.hasSubscribers) { @@ -3518,7 +3573,7 @@ class QuicSession { session: this, }); } - safeCallbackInvoke(this.#ondatagram, this, u8, early); + safeCallbackInvoke(inner.ondatagram, this, u8, early); } /** @@ -3526,9 +3581,10 @@ class QuicSession { * @param {'lost'|'acknowledged'} status */ [kDatagramStatus](id, status) { + const inner = this.#inner; // The datagram status event should only be called if the session has // an ondatagramstatus callback. The callback should always exist here. - assert(typeof this.#ondatagramstatus === 'function', 'Unexpected datagram status event'); + assert(typeof inner.ondatagramstatus === 'function', 'Unexpected datagram status event'); if (this.destroyed) return; if (onSessionReceiveDatagramStatusChannel.hasSubscribers) { onSessionReceiveDatagramStatusChannel.publish({ @@ -3538,7 +3594,7 @@ class QuicSession { session: this, }); } - safeCallbackInvoke(this.#ondatagramstatus, this, id, status); + safeCallbackInvoke(inner.ondatagramstatus, this, id, status); } /** @@ -3551,7 +3607,8 @@ class QuicSession { */ [kPathValidation](result, newLocalAddress, newRemoteAddress, oldLocalAddress, oldRemoteAddress, preferredAddress) { - assert(typeof this.#onpathvalidation === 'function', + const inner = this.#inner; + assert(typeof inner.onpathvalidation === 'function', 'Unexpected path validation event'); if (this.destroyed) return; const newLocal = new InternalSocketAddress(newLocalAddress); @@ -3572,7 +3629,7 @@ class QuicSession { session: this, }); } - safeCallbackInvoke(this.#onpathvalidation, this, result, newLocal, newRemote, + safeCallbackInvoke(inner.onpathvalidation, this, result, newLocal, newRemote, oldLocal, oldRemote, preferredAddress); } @@ -3580,7 +3637,8 @@ class QuicSession { * @param {object} ticket */ [kSessionTicket](ticket) { - assert(typeof this.#onsessionticket === 'function', + const inner = this.#inner; + assert(typeof inner.onsessionticket === 'function', 'Unexpected session ticket event'); if (this.destroyed) return; if (onSessionTicketChannel.hasSubscribers) { @@ -3590,7 +3648,7 @@ class QuicSession { session: this, }); } - safeCallbackInvoke(this.#onsessionticket, this, ticket); + safeCallbackInvoke(inner.onsessionticket, this, ticket); } /** @@ -3598,7 +3656,8 @@ class QuicSession { * @param {SocketAddress} address */ [kNewToken](token, address) { - assert(typeof this.#onnewtoken === 'function', + const inner = this.#inner; + assert(typeof inner.onnewtoken === 'function', 'Unexpected new token event'); if (this.destroyed) return; const addr = new InternalSocketAddress(address); @@ -3610,7 +3669,7 @@ class QuicSession { session: this, }); } - safeCallbackInvoke(this.#onnewtoken, this, token, addr); + safeCallbackInvoke(inner.onnewtoken, this, token, addr); } [kEarlyDataRejected]() { @@ -3621,8 +3680,9 @@ class QuicSession { session: this, }); } - if (typeof this.#onearlyrejected === 'function') { - safeCallbackInvoke(this.#onearlyrejected, this); + const inner = this.#inner; + if (typeof inner.onearlyrejected === 'function') { + safeCallbackInvoke(inner.onearlyrejected, this); } } @@ -3642,8 +3702,9 @@ class QuicSession { session: this, }); } - if (this.#onversionnegotiation) { - safeCallbackInvoke(this.#onversionnegotiation, this, + const inner = this.#inner; + if (typeof inner.onversionnegotiation === 'function') { + safeCallbackInvoke(inner.onversionnegotiation, this, version, requestedVersions, supportedVersions); } // Version negotiation is always a fatal event - the session must be @@ -3656,9 +3717,9 @@ class QuicSession { * @param {string[]} origins */ [kOrigin](origins) { - assert(typeof this.#onorigin === 'function', - 'Unexpected origin event'); if (this.destroyed) return; + const inner = this.#inner; + assert(typeof inner.onorigin === 'function', 'Unexpected origin event'); if (onSessionOriginChannel.hasSubscribers) { onSessionOriginChannel.publish({ __proto__: null, @@ -3666,7 +3727,7 @@ class QuicSession { session: this, }); } - safeCallbackInvoke(this.#onorigin, this, origins); + safeCallbackInvoke(inner.onorigin, this, origins); } /** @@ -3679,13 +3740,15 @@ class QuicSession { */ [kHandshake](servername, protocol, cipher, cipherVersion, validationErrorReason, validationErrorCode, earlyDataAttempted, earlyDataAccepted) { - if (this.destroyed || !this.#pendingOpen.resolve) return; + const inner = this.#inner; + if (this.destroyed || !inner.pendingOpen.resolve) return; + const addr = this.#handle.getRemoteAddress(); const info = { __proto__: null, - local: this.#endpoint.address, + local: inner.endpoint.address, remote: addr !== undefined ? new InternalSocketAddress(addr) : undefined, @@ -3700,7 +3763,7 @@ class QuicSession { }; // Stash timing-relevant handshake info for the perf entry detail. - this.#handshakeInfo = { + inner.handshakeInfo = { __proto__: null, servername, protocol, @@ -3716,19 +3779,19 @@ class QuicSession { }); } - if (this.#onhandshake) { - safeCallbackInvoke(this.#onhandshake, this, info); + if (typeof inner.onhandshake === 'function') { + safeCallbackInvoke(inner.onhandshake, this, info); } - this.#pendingOpen.resolve?.(info); - this.#pendingOpen.resolve = undefined; - this.#pendingOpen.reject = undefined; - this.#handshakeCompleted = true; + inner.pendingOpen.resolve?.(info); + inner.pendingOpen.resolve = undefined; + inner.pendingOpen.reject = undefined; + inner.handshakeCompleted = true; } /** @type {boolean} */ get [kHandshakeCompleted]() { - return this.#handshakeCompleted; + return this.#inner.handshakeCompleted; } /** @@ -3736,22 +3799,25 @@ class QuicSession { * @param {number} direction */ [kNewStream](handle, direction) { - const stream = new QuicStream(kPrivateConstructor, handle, this, direction); + const inner = this.#inner; + const stream = new QuicStream(kPrivateConstructor, handle, this, direction, + false /* isLocal */); // Set the default high water mark for received streams. stream.highWaterMark = kDefaultHighWaterMark; // A new stream was received. If we don't have an onstream callback, then // there's nothing we can do about it. Destroy the stream in this case. - if (typeof this.#onstream !== 'function') { + if (typeof inner.onstream !== 'function') { process.emitWarning('A new stream was received but no onstream callback was provided'); stream.destroy(); return; } - this.#streams.add(stream); + + inner.streams.add(stream); // If the session has an onerror handler, mark the stream's closed // promise as handled. See the onerror setter for explanation. - if (typeof this.#onerror === 'function') { + if (typeof inner.onerror === 'function') { markPromiseAsHandled(stream.closed); } @@ -3774,16 +3840,17 @@ class QuicSession { }); } - safeCallbackInvoke(this.#onstream, this, stream); + safeCallbackInvoke(inner.onstream, this, stream); } [kRemoveStream](stream) { - this.#streams.delete(stream); + this.#inner.streams.delete(stream); } [kInspect](depth, options) { - if (depth < 0) - return this; + if (depth < 0) { + return 'QuicSession { }'; + } const opts = { __proto__: null, @@ -3791,100 +3858,54 @@ class QuicSession { depth: options.depth == null ? null : options.depth - 1, }; + const { + isPendingClose: closing, + endpoint, + path, + state, + stats, + streams, + } = this.#inner; + return `QuicSession ${inspect({ closed: this.closed, - closing: this.#isPendingClose, + closing, destroyed: this.destroyed, - endpoint: this.endpoint, - path: this.path, - state: this.#state, - stats: this.stats, - streams: this.#streams, + endpoint, + path, + state, + stats, + streams, }, opts)}`; } async [SymbolAsyncDispose]() { await this.close(); } } -let isQuicEndpoint; - // The QuicEndpoint represents a local UDP port binding. It can act as both a // server for receiving peer sessions, or a client for initiating them. The // local UDP port will be lazily bound only when connect() or listen() are // called. class QuicEndpoint { - /** - * The local socket address on which the endpoint is listening (lazily created) - * @type {SocketAddress|undefined} - */ - #address = undefined; - /** - * When true, the endpoint has been marked busy and is temporarily not accepting - * new sessions (only used when the Endpoint is acting as a server) - * @type {boolean} - */ - #busy = false; - /** - * The underlying C++ handle for the endpoint. When undefined the endpoint is - * considered to be closed. - * @type {object} - */ #handle; - /** - * True if endpoint.close() has been called and the [kFinishClose] method has - * not yet been called. - * @type {boolean} - */ - #isPendingClose = false; - /** - * True if the endpoint is acting as a server and actively listening for connections. - * @type {boolean} - */ - #listening = false; - /** - * A promise that is resolved when the endpoint has been closed (or rejected if - * the endpoint closes abruptly due to an error). - * @type {PromiseWithResolvers} - */ - #pendingClose = PromiseWithResolvers(); - /** - * If destroy() is called with an error, the error is stored here and used to reject - * the pendingClose promise when [kFinishClose] is called. - * @type {any} - */ - #pendingError = undefined; - /** - * The collection of active sessions. - * @type {Set} - */ - #sessions = new SafeSet(); - /** - * The internal state of the endpoint. Used to efficiently track and update the - * state of the underlying c++ endpoint handle. - * @type {QuicEndpointState} - */ - #state; - /** - * The collected statistics for the endpoint. - * @type {QuicEndpointStats} - */ - #stats; - /** - * The user provided callback that is invoked when a new session is received. - * (used only when the endpoint is acting as a server) - * @type {OnSessionCallback} - */ - #onsession = undefined; - #sessionCallbacks = undefined; + #inner = { + __proto__: null, + address: undefined, + busy: false, + isPendingClose: false, + listening: false, + pendingClose: PromiseWithResolvers(), + pendingError: undefined, + sessions: new SafeSet(), + stat: undefined, + stats: undefined, + onsession: undefined, + sessionCallbacks: undefined, + }; static { - getQuicEndpointState = function(endpoint) { - assertIsQuicEndpoint(endpoint); - return endpoint.#state; - }; - isQuicEndpoint = function(val) { - return val != null && #handle in val; + return val != null && typeof val === 'object' && #handle in val; }; assertIsQuicEndpoint = function(val) { @@ -3893,6 +3914,11 @@ class QuicEndpoint { } }; + getQuicEndpointState = function(endpoint) { + assertIsQuicEndpoint(endpoint); + return endpoint.#inner.state; + }; + assertEndpointNotClosedOrClosing = function(endpoint) { if (endpoint.#isClosedOrClosing) { throw new ERR_INVALID_STATE('Endpoint is closed'); @@ -3900,7 +3926,7 @@ class QuicEndpoint { }; assertEndpointIsNotBusy = function(endpoint) { - if (endpoint.#state.isBusy) { + if (endpoint.#inner.state.isBusy) { throw new ERR_INVALID_STATE('Endpoint is busy'); } }; @@ -3974,7 +4000,7 @@ class QuicEndpoint { #newSession(handle) { const session = new QuicSession(kPrivateConstructor, handle, this); - this.#sessions.add(session); + this.#inner.sessions.add(session); // Set default pending datagram queue size. session.maxPendingDatagrams = kDefaultMaxPendingDatagrams; return session; @@ -3987,8 +4013,9 @@ class QuicEndpoint { const options = this.#processEndpointOptions(config); this.#handle = new Endpoint_(options); this.#handle[kOwner] = this; - this.#stats = new QuicEndpointStats(kPrivateConstructor, this.#handle.stats); - this.#state = new QuicEndpointState(kPrivateConstructor, this.#handle.state); + const inner = this.#inner; + inner.stats = new QuicEndpointStats(kPrivateConstructor, this.#handle.stats); + inner.state = new QuicEndpointState(kPrivateConstructor, this.#handle.state); // Connection limits are stored in the shared state buffer so they // can be read by C++ and mutated from JS after construction. @@ -4023,11 +4050,11 @@ class QuicEndpoint { */ get stats() { assertIsQuicEndpoint(this); - return this.#stats; + return this.#inner.stats; } get #isClosedOrClosing() { - return this.destroyed || this.#isPendingClose; + return this.destroyed || this.#inner.isPendingClose; } /** @@ -4037,7 +4064,7 @@ class QuicEndpoint { */ get busy() { assertIsQuicEndpoint(this); - return this.#busy; + return this.#inner.busy; } /** @@ -4048,15 +4075,16 @@ class QuicEndpoint { assertEndpointNotClosedOrClosing(this); // The val is allowed to be any truthy value // Non-op if there is no change - if (!!val !== this.#busy) { - debug('toggling endpoint busy status to ', !this.#busy); - this.#busy = !this.#busy; - this.#handle.markBusy(this.#busy); + const inner = this.#inner; + if (!!val !== inner.busy) { + debug('toggling endpoint busy status to ', !inner.busy); + inner.busy = !inner.busy; + this.#handle.markBusy(inner.busy); if (onEndpointBusyChangeChannel.hasSubscribers) { onEndpointBusyChangeChannel.publish({ __proto__: null, endpoint: this, - busy: this.#busy, + busy: inner.busy, }); } } @@ -4069,13 +4097,13 @@ class QuicEndpoint { */ get maxConnectionsPerHost() { assertIsQuicEndpoint(this); - return this.#state.maxConnectionsPerHost; + return this.#inner.state.maxConnectionsPerHost; } set maxConnectionsPerHost(val) { assertIsQuicEndpoint(this); validateInteger(val, 'maxConnectionsPerHost', 0, 0xFFFF); - this.#state.maxConnectionsPerHost = val; + this.#inner.state.maxConnectionsPerHost = val; } /** @@ -4085,13 +4113,13 @@ class QuicEndpoint { */ get maxConnectionsTotal() { assertIsQuicEndpoint(this); - return this.#state.maxConnectionsTotal; + return this.#inner.state.maxConnectionsTotal; } set maxConnectionsTotal(val) { assertIsQuicEndpoint(this); validateInteger(val, 'maxConnectionsTotal', 0, 0xFFFF); - this.#state.maxConnectionsTotal = val; + this.#inner.state.maxConnectionsTotal = val; } /** @@ -4101,11 +4129,11 @@ class QuicEndpoint { get address() { assertIsQuicEndpoint(this); if (this.#isClosedOrClosing) return undefined; - if (this.#address === undefined) { + if (this.#inner.address === undefined) { const addr = this.#handle.address(); - if (addr !== undefined) this.#address = new InternalSocketAddress(addr); + if (addr !== undefined) this.#inner.address = new InternalSocketAddress(addr); } - return this.#address; + return this.#inner.address; } /** @@ -4116,11 +4144,13 @@ class QuicEndpoint { [kListen](onsession, options) { assertEndpointNotClosedOrClosing(this); assertEndpointIsNotBusy(this); - if (this.#listening) { + const inner = this.#inner; + if (inner.listening) { throw new ERR_INVALID_STATE('Endpoint is already listening'); } validateObject(options, 'options'); - this.#onsession = FunctionPrototypeBind(onsession, this); + validateFunction(onsession, 'onsession'); + this.#inner.onsession = FunctionPrototypeBind(onsession, this); const { onerror, @@ -4146,7 +4176,7 @@ class QuicEndpoint { } = options; // Store session and stream callbacks to apply to each new incoming session. - this.#sessionCallbacks = { + inner.sessionCallbacks = { __proto__: null, onerror, onstream, @@ -4168,9 +4198,9 @@ class QuicEndpoint { onwanttrailers, }; - debug('endpoint listening as a server'); this.#handle.listen(rest); - this.#listening = true; + inner.listening = true; + debug('endpoint listening as a server'); } /** @@ -4212,15 +4242,16 @@ class QuicEndpoint { assertIsQuicEndpoint(this); if (!this.#isClosedOrClosing) { debug('gracefully closing the endpoint'); + const inner = this.#inner; + inner.isPendingClose = true; + this.#handle.closeGracefully(); if (onEndpointClosingChannel.hasSubscribers) { onEndpointClosingChannel.publish({ __proto__: null, endpoint: this, - hasPendingError: this.#pendingError !== undefined, + hasPendingError: inner.pendingError !== undefined, }); } - this.#isPendingClose = true; - this.#handle.closeGracefully(); } return this.closed; } @@ -4233,7 +4264,7 @@ class QuicEndpoint { */ get closed() { assertIsQuicEndpoint(this); - return this.#pendingClose.promise; + return this.#inner.pendingClose.promise; } /** @@ -4242,13 +4273,13 @@ class QuicEndpoint { */ get closing() { assertIsQuicEndpoint(this); - return this.#isPendingClose; + return this.#inner.isPendingClose; } /** @type {boolean} */ get listening() { assertIsQuicEndpoint(this); - return this.#listening; + return this.#inner.listening; } /** @type {boolean} */ @@ -4268,6 +4299,7 @@ class QuicEndpoint { destroy(error) { assertIsQuicEndpoint(this); debug('destroying the endpoint'); + const inner = this.#inner; // Record the error before deciding whether to initiate a close. If // `close()` was already called (e.g. the user kicked off a graceful // shutdown and then a fatal error was reported afterwards via @@ -4276,7 +4308,7 @@ class QuicEndpoint { // last in-flight session finishes draining. Only the *first* error // is recorded, matching how other Node subsystems handle a // double-error race. - if (error !== undefined) this.#pendingError ??= error; + if (error !== undefined) inner.pendingError ??= error; // Force all sessions to be abruptly closed *before* signalling the // endpoint to close gracefully. The order matters: each session's // `destroy(error, options)` asks the C++ side to emit a @@ -4293,7 +4325,7 @@ class QuicEndpoint { // `destroy()`, which trips the `#destroying` guard and leaves the // C++ side asserting an inconsistent destroyed state. const closeOptions = errorToCloseOptions(error); - for (const session of this.#sessions) { + for (const session of inner.sessions) { // Mark each cascaded session's `closed` as handled before // destroying it. This prevents unhandled-rejection warnings when // the session is collateral damage from an endpoint-level destroy @@ -4321,7 +4353,7 @@ class QuicEndpoint { * replace is true, the entire SNI map is replaced. Otherwise, the * provided entries are merged into the existing map. * @param {object} entries - * @param {{replace?: boolean}} [options] + * @param {SNIContextOptions} [options] */ setSNIContexts(entries, options = kEmptyObject) { assertIsQuicEndpoint(this); @@ -4356,38 +4388,39 @@ class QuicEndpoint { debug('endpoint is finishing close', context, status); endpointRegistry.delete(this); this.#handle = undefined; - this.#stats[kFinishClose](); - this.#state[kFinishClose](); + const inner = this.#inner; + inner.stats[kFinishClose](); + inner.state[kFinishClose](); if (this[kPerfEntry] && hasObserver('quic')) { stopPerf(this, kPerfEntry, { detail: { stats: this.stats }, }); } - this.#address = undefined; - this.#busy = false; - this.#listening = false; - this.#isPendingClose = false; + inner.address = undefined; + inner.busy = false; + inner.listening = false; + inner.isPendingClose = false; // As QuicSessions are closed they are expected to remove themselves // from the sessions collection. Just in case they don't, let's force // it by resetting the set so we don't leak memory. Let's emit a warning, // tho, if the set is not empty at this point as that would indicate a // bug in Node.js that should be fixed. - if (this.#sessions.size > 0) { + if (inner.sessions.size > 0) { process.emitWarning( - `The endpoint is closed with ${this.#sessions.size} active sessions. ` + + `The endpoint is closed with ${inner.sessions.size} active sessions. ` + 'This should not happen and indicates a bug in Node.js. Please open an ' + 'issue in the Node.js GitHub repository at https://github.com/nodejs/node ' + 'to report the problem.', ); } - this.#sessions.clear(); + inner.sessions.clear(); // If destroy was called with an error, then the this.#pendingError will be // set. Or, if context indicates an error condition that caused the endpoint // to be closed, the status will indicate the error code. In either case, // we will reject the pending close promise at this point. - const maybeCloseError = maybeGetCloseError(context, status, this.#pendingError); + const maybeCloseError = maybeGetCloseError(context, status, inner.pendingError); if (maybeCloseError !== undefined) { if (onEndpointErrorChannel.hasSubscribers) { onEndpointErrorChannel.publish({ @@ -4396,33 +4429,36 @@ class QuicEndpoint { error: maybeCloseError, }); } - this.#pendingClose.reject(maybeCloseError); + inner.pendingClose.reject(maybeCloseError); } else { // Otherwise we are good to resolve the pending close promise! - this.#pendingClose.resolve(); + inner.pendingClose.resolve(); } if (onEndpointClosedChannel.hasSubscribers) { onEndpointClosedChannel.publish({ __proto__: null, endpoint: this, - stats: this.stats, + stats: inner.stats, }); } // Note that we are intentionally not clearing the // this.#pendingClose.promise here. - this.#pendingClose.resolve = undefined; - this.#pendingClose.reject = undefined; - this.#pendingError = undefined; + inner.pendingClose.resolve = undefined; + inner.pendingClose.reject = undefined; + inner.pendingError = undefined; } [kNewSession](handle) { + const inner = this.#inner; + assert(typeof inner.onsession === 'function', + 'onsession callback not specified'); const session = this.#newSession(handle); // Apply session callbacks stored at listen time before notifying // the onsession callback, to avoid missing events that fire // during or immediately after the handshake. - if (this.#sessionCallbacks) { - applyCallbacks(session, this.#sessionCallbacks); + if (inner.sessionCallbacks) { + applyCallbacks(session, inner.sessionCallbacks); } if (onEndpointServerSessionChannel.hasSubscribers) { onEndpointServerSessionChannel.publish({ @@ -4432,25 +4468,24 @@ class QuicEndpoint { address: session.path?.remote, }); } - assert(typeof this.#onsession === 'function', - 'onsession callback not specified'); // Route through safeCallbackInvoke so that a synchronous throw or a // rejected promise from the user's onsession callback destroys this // endpoint with the error rather than surfacing as an unhandled // exception or unhandled rejection coming out of the C++ -> JS // boundary. - safeCallbackInvoke(this.#onsession, this, session); + safeCallbackInvoke(inner.onsession, this, session); } // Called by the QuicSession when it closes to remove itself from // the active sessions tracked by the QuicEndpoint. [kRemoveSession](session) { - this.#sessions.delete(session); + this.#inner.sessions.delete(session); } [kInspect](depth, options) { - if (depth < 0) - return this; + if (depth < 0) { + return 'QuicEndpoint { }'; + } const opts = { __proto__: null, @@ -4458,16 +4493,26 @@ class QuicEndpoint { depth: options.depth == null ? null : options.depth - 1, }; + const { + address, + busy, + isPendingClose: closing, + listening, + sessions, + stats, + state, + } = this.#inner; + return `QuicEndpoint ${inspect({ - address: this.address, - busy: this.busy, + address, + busy, closed: this.closed, - closing: this.#isPendingClose, + closing, destroyed: this.destroyed, - listening: this.#listening, - sessions: this.#sessions, - stats: this.stats, - state: this.#state, + listening, + sessions, + stats, + state, }, opts)}`; } @@ -4809,10 +4854,10 @@ function getPreferredAddressPolicy(policy = 'default') { /** * @param {SessionOptions} options - * @param {{forServer: boolean, addressFamily: string}} [config] + * @param {ProcessSessionOptions} [config] * @returns {SessionOptions} */ -function processSessionOptions(options, config = { __proto__: null }) { +function processSessionOptions(options, config = kEmptyObject) { validateObject(options, 'options'); const { endpoint, diff --git a/lib/internal/quic/state.js b/lib/internal/quic/state.js index d32bbcce5c5..82277b115d6 100644 --- a/lib/internal/quic/state.js +++ b/lib/internal/quic/state.js @@ -5,7 +5,6 @@ /* c8 ignore start */ const { - ArrayBuffer, DataView, DataViewPrototypeGetBigInt64, DataViewPrototypeGetBigUint64, @@ -16,21 +15,15 @@ const { DataViewPrototypeSetUint16, DataViewPrototypeSetUint32, DataViewPrototypeSetUint8, - Float32Array, JSONStringify, - Uint8Array, + Number, } = primordials; -// Determine native byte order. The shared state buffer is written by -// C++ in native byte order, so DataView reads must match. -const kIsLittleEndian = (() => { - // -1 as float32 is 0xBF800000. On little-endian, the bytes are - // [0x00, 0x00, 0x80, 0xBF], so byte[3] is 0xBF (non-zero). - // On big-endian, the bytes are [0xBF, 0x80, 0x00, 0x00], so byte[3] is 0. - const buf = new Float32Array(1); - buf[0] = -1; - return new Uint8Array(buf.buffer)[3] !== 0; -})(); +const { + isBigEndian, +} = internalBinding('os'); + +const kIsLittleEndian = !isBigEndian; const { getOptionValue, @@ -58,8 +51,6 @@ const { kFinishClose, kInspect, kPrivateConstructor, - kWantsHeaders, - kWantsTrailers, } = require('internal/quic/symbols'); // This file defines the helper objects for accessing state for @@ -155,6 +146,11 @@ assert(IDX_STATE_STREAM_WANTS_TRAILERS !== undefined); assert(IDX_STATE_STREAM_WRITE_DESIRED_SIZE !== undefined); assert(IDX_STATE_STREAM_RESET_CODE !== undefined); +const kEmptyObject = { __proto__: null }; + +// The internal state objects for endpoints, sessions, and streams. +// These are not exposed directly to users. + class QuicEndpointState { /** @type {DataView} */ #handle; @@ -175,58 +171,67 @@ class QuicEndpointState { /** @type {boolean} */ get isBound() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, IDX_STATE_ENDPOINT_BOUND); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, IDX_STATE_ENDPOINT_BOUND) !== 0; } /** @type {boolean} */ get isReceiving() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, IDX_STATE_ENDPOINT_RECEIVING); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, IDX_STATE_ENDPOINT_RECEIVING) !== 0; } /** @type {boolean} */ get isListening() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, IDX_STATE_ENDPOINT_LISTENING); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, IDX_STATE_ENDPOINT_LISTENING) !== 0; } /** @type {boolean} */ get isClosing() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, IDX_STATE_ENDPOINT_CLOSING); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, IDX_STATE_ENDPOINT_CLOSING) !== 0; } /** @type {boolean} */ get isBusy() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, IDX_STATE_ENDPOINT_BUSY); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, IDX_STATE_ENDPOINT_BUSY) !== 0; } /** @type {number} */ get maxConnectionsPerHost() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; + const handle = this.#handle; + if (handle === undefined) return undefined; return DataViewPrototypeGetUint16( - this.#handle, IDX_STATE_ENDPOINT_MAX_CONNECTIONS_PER_HOST, kIsLittleEndian); + handle, IDX_STATE_ENDPOINT_MAX_CONNECTIONS_PER_HOST, kIsLittleEndian); } set maxConnectionsPerHost(val) { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return; + const handle = this.#handle; + if (handle === undefined) return; DataViewPrototypeSetUint16( - this.#handle, IDX_STATE_ENDPOINT_MAX_CONNECTIONS_PER_HOST, val, kIsLittleEndian); + handle, IDX_STATE_ENDPOINT_MAX_CONNECTIONS_PER_HOST, val, kIsLittleEndian); } /** @type {number} */ get maxConnectionsTotal() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; + const handle = this.#handle; + if (handle === undefined) return undefined; return DataViewPrototypeGetUint16( - this.#handle, IDX_STATE_ENDPOINT_MAX_CONNECTIONS_TOTAL, kIsLittleEndian); + handle, IDX_STATE_ENDPOINT_MAX_CONNECTIONS_TOTAL, kIsLittleEndian); } set maxConnectionsTotal(val) { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return; + const handle = this.#handle; + if (handle === undefined) return; DataViewPrototypeSetUint16( - this.#handle, IDX_STATE_ENDPOINT_MAX_CONNECTIONS_TOTAL, val, kIsLittleEndian); + handle, IDX_STATE_ENDPOINT_MAX_CONNECTIONS_TOTAL, val, kIsLittleEndian); } /** @@ -236,8 +241,9 @@ class QuicEndpointState { * @type {bigint} */ get pendingCallbacks() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return DataViewPrototypeGetBigUint64(this.#handle, IDX_STATE_ENDPOINT_PENDING_CALLBACKS, kIsLittleEndian); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetBigUint64(handle, IDX_STATE_ENDPOINT_PENDING_CALLBACKS, kIsLittleEndian); } toString() { @@ -245,49 +251,70 @@ class QuicEndpointState { } toJSON() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return {}; + if (this.#handle === undefined) return kEmptyObject; + const { + isBound, + isReceiving, + isListening, + isClosing, + isBusy, + maxConnectionsPerHost, + maxConnectionsTotal, + pendingCallbacks, + } = this; return { __proto__: null, - isBound: this.isBound, - isReceiving: this.isReceiving, - isListening: this.isListening, - isClosing: this.isClosing, - isBusy: this.isBusy, - maxConnectionsPerHost: this.maxConnectionsPerHost, - maxConnectionsTotal: this.maxConnectionsTotal, - pendingCallbacks: `${this.pendingCallbacks}`, + isBound, + isReceiving, + isListening, + isClosing, + isBusy, + maxConnectionsPerHost, + maxConnectionsTotal, + pendingCallbacks: Number(pendingCallbacks), }; } [kInspect](depth, options) { - if (depth < 0) - return this; - - if (DataViewPrototypeGetByteLength(this.#handle) === 0) { + if (this.#handle === undefined) { return 'QuicEndpointState { }'; } + if (depth < 0) { + return 'QuicEndpointState { }'; + } + const opts = { __proto__: null, ...options, depth: options.depth == null ? null : options.depth - 1, }; + const { + isBound, + isReceiving, + isListening, + isClosing, + isBusy, + maxConnectionsPerHost, + maxConnectionsTotal, + pendingCallbacks, + } = this; + return `QuicEndpointState ${inspect({ - isBound: this.isBound, - isReceiving: this.isReceiving, - isListening: this.isListening, - isClosing: this.isClosing, - isBusy: this.isBusy, - pendingCallbacks: this.pendingCallbacks, + isBound, + isReceiving, + isListening, + isClosing, + isBusy, + maxConnectionsPerHost, + maxConnectionsTotal, + pendingCallbacks, }, opts)}`; } [kFinishClose]() { - // Snapshot the state into a new DataView since the underlying - // buffer will be destroyed. - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return; - this.#handle = new DataView(new ArrayBuffer(0)); + this.#handle = undefined; } } @@ -324,17 +351,19 @@ class QuicSessionState { static #LISTENER_ORIGIN = 1 << 5; #getListenerFlag(flag) { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!(DataViewPrototypeGetUint32( - this.#handle, this.#offset + IDX_STATE_SESSION_LISTENER_FLAGS, kIsLittleEndian) & flag); + const handle = this.#handle; + if (handle === undefined) return undefined; + return (DataViewPrototypeGetUint32( + handle, this.#offset + IDX_STATE_SESSION_LISTENER_FLAGS, kIsLittleEndian) & flag) !== 0; } #setListenerFlag(flag, val) { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return; + const handle = this.#handle; + if (handle === undefined) return; const current = DataViewPrototypeGetUint32( - this.#handle, this.#offset + IDX_STATE_SESSION_LISTENER_FLAGS, kIsLittleEndian); + handle, this.#offset + IDX_STATE_SESSION_LISTENER_FLAGS, kIsLittleEndian); DataViewPrototypeSetUint32( - this.#handle, this.#offset + IDX_STATE_SESSION_LISTENER_FLAGS, + handle, this.#offset + IDX_STATE_SESSION_LISTENER_FLAGS, val ? (current | flag) : (current & ~flag), kIsLittleEndian); } @@ -388,50 +417,58 @@ class QuicSessionState { /** @type {boolean} */ get isClosing() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_SESSION_CLOSING); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_SESSION_CLOSING) !== 0; } /** @type {boolean} */ get isGracefulClose() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_SESSION_GRACEFUL_CLOSE); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_SESSION_GRACEFUL_CLOSE) !== 0; } /** @type {boolean} */ get isSilentClose() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_SESSION_SILENT_CLOSE); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_SESSION_SILENT_CLOSE) !== 0; } /** @type {boolean} */ get isStatelessReset() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_SESSION_STATELESS_RESET); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_SESSION_STATELESS_RESET) !== 0; } /** @type {boolean} */ get isHandshakeCompleted() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_SESSION_HANDSHAKE_COMPLETED); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_SESSION_HANDSHAKE_COMPLETED) !== 0; } /** @type {boolean} */ get isHandshakeConfirmed() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_SESSION_HANDSHAKE_CONFIRMED); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_SESSION_HANDSHAKE_CONFIRMED) !== 0; } /** @type {boolean} */ get isStreamOpenAllowed() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_SESSION_STREAM_OPEN_ALLOWED); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_SESSION_STREAM_OPEN_ALLOWED) !== 0; } /** @type {boolean} */ get isPrioritySupported() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_SESSION_PRIORITY_SUPPORTED); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_SESSION_PRIORITY_SUPPORTED) !== 0; } /** @@ -440,20 +477,23 @@ class QuicSessionState { * @type {number} */ get headersSupported() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_SESSION_HEADERS_SUPPORTED); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_SESSION_HEADERS_SUPPORTED); } /** @type {boolean} */ get isWrapped() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_SESSION_WRAPPED); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_SESSION_WRAPPED) !== 0; } /** @type {number} */ get applicationType() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_SESSION_APPLICATION_TYPE); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_SESSION_APPLICATION_TYPE); } /** @@ -464,9 +504,10 @@ class QuicSessionState { * @type {bigint} */ get noErrorCode() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; + const handle = this.#handle; + if (handle === undefined) return undefined; return DataViewPrototypeGetBigUint64( - this.#handle, this.#offset + IDX_STATE_SESSION_NO_ERROR_CODE, kIsLittleEndian); + handle, this.#offset + IDX_STATE_SESSION_NO_ERROR_CODE, kIsLittleEndian); } /** @@ -479,38 +520,43 @@ class QuicSessionState { * @type {bigint} */ get internalErrorCode() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; + const handle = this.#handle; + if (handle === undefined) return undefined; return DataViewPrototypeGetBigUint64( - this.#handle, this.#offset + IDX_STATE_SESSION_INTERNAL_ERROR_CODE, kIsLittleEndian); + handle, this.#offset + IDX_STATE_SESSION_INTERNAL_ERROR_CODE, kIsLittleEndian); } /** @type {number} */ get maxDatagramSize() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; + const handle = this.#handle; + if (handle === undefined) return undefined; return DataViewPrototypeGetUint16( - this.#handle, this.#offset + IDX_STATE_SESSION_MAX_DATAGRAM_SIZE, + handle, this.#offset + IDX_STATE_SESSION_MAX_DATAGRAM_SIZE, kIsLittleEndian); } /** @type {bigint} */ get lastDatagramId() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; + const handle = this.#handle; + if (handle === undefined) return undefined; return DataViewPrototypeGetBigUint64( - this.#handle, this.#offset + IDX_STATE_SESSION_LAST_DATAGRAM_ID, + handle, this.#offset + IDX_STATE_SESSION_LAST_DATAGRAM_ID, kIsLittleEndian); } /** @type {number} */ get maxPendingDatagrams() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; + const handle = this.#handle; + if (handle === undefined) return undefined; return DataViewPrototypeGetUint16( - this.#handle, this.#offset + IDX_STATE_SESSION_MAX_PENDING_DATAGRAMS, kIsLittleEndian); + handle, this.#offset + IDX_STATE_SESSION_MAX_PENDING_DATAGRAMS, kIsLittleEndian); } set maxPendingDatagrams(val) { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return; + const handle = this.#handle; + if (handle === undefined) return; DataViewPrototypeSetUint16( - this.#handle, this.#offset + IDX_STATE_SESSION_MAX_PENDING_DATAGRAMS, val, kIsLittleEndian); + handle, this.#offset + IDX_STATE_SESSION_MAX_PENDING_DATAGRAMS, val, kIsLittleEndian); } toString() { @@ -518,78 +564,126 @@ class QuicSessionState { } toJSON() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return {}; + if (this.#handle === undefined) return kEmptyObject; + const { + hasPathValidationListener, + hasDatagramListener, + hasDatagramStatusListener, + hasSessionTicketListener, + hasNewTokenListener, + hasOriginListener, + isClosing, + isGracefulClose, + isSilentClose, + isStatelessReset, + isHandshakeCompleted, + isHandshakeConfirmed, + isStreamOpenAllowed, + isPrioritySupported, + headersSupported, + isWrapped, + applicationType, + noErrorCode, + internalErrorCode, + maxDatagramSize, + lastDatagramId, + maxPendingDatagrams, + } = this; return { __proto__: null, - hasPathValidationListener: this.hasPathValidationListener, - hasDatagramListener: this.hasDatagramListener, - hasDatagramStatusListener: this.hasDatagramStatusListener, - hasSessionTicketListener: this.hasSessionTicketListener, - hasNewTokenListener: this.hasNewTokenListener, - hasOriginListener: this.hasOriginListener, - isClosing: this.isClosing, - isGracefulClose: this.isGracefulClose, - isSilentClose: this.isSilentClose, - isStatelessReset: this.isStatelessReset, - isHandshakeCompleted: this.isHandshakeCompleted, - isHandshakeConfirmed: this.isHandshakeConfirmed, - isStreamOpenAllowed: this.isStreamOpenAllowed, - isPrioritySupported: this.isPrioritySupported, - headersSupported: this.headersSupported, - isWrapped: this.isWrapped, - applicationType: this.applicationType, - noErrorCode: `${this.noErrorCode}`, - internalErrorCode: `${this.internalErrorCode}`, - maxDatagramSize: `${this.maxDatagramSize}`, - lastDatagramId: `${this.lastDatagramId}`, - maxPendingDatagrams: this.maxPendingDatagrams, + hasPathValidationListener, + hasDatagramListener, + hasDatagramStatusListener, + hasSessionTicketListener, + hasNewTokenListener, + hasOriginListener, + isClosing, + isGracefulClose, + isSilentClose, + isStatelessReset, + isHandshakeCompleted, + isHandshakeConfirmed, + isStreamOpenAllowed, + isPrioritySupported, + headersSupported, + isWrapped, + applicationType, + noErrorCode: `${noErrorCode}`, + internalErrorCode: `${internalErrorCode}`, + maxDatagramSize: `${maxDatagramSize}`, + lastDatagramId: `${lastDatagramId}`, + maxPendingDatagrams, }; } [kInspect](depth, options) { - if (depth < 0) - return this; - - if (DataViewPrototypeGetByteLength(this.#handle) === 0) { + if (this.#handle === undefined) { return 'QuicSessionState { }'; } + if (depth < 0) { + return 'QuicSessionState { }'; + } + const opts = { __proto__: null, ...options, depth: options.depth == null ? null : options.depth - 1, }; + const { + hasPathValidationListener, + hasDatagramListener, + hasDatagramStatusListener, + hasSessionTicketListener, + hasNewTokenListener, + hasOriginListener, + isClosing, + isGracefulClose, + isSilentClose, + isStatelessReset, + isHandshakeCompleted, + isHandshakeConfirmed, + isStreamOpenAllowed, + isPrioritySupported, + headersSupported, + isWrapped, + applicationType, + noErrorCode, + internalErrorCode, + maxDatagramSize, + lastDatagramId, + maxPendingDatagrams, + } = this; + return `QuicSessionState ${inspect({ - hasPathValidationListener: this.hasPathValidationListener, - hasDatagramListener: this.hasDatagramListener, - hasDatagramStatusListener: this.hasDatagramStatusListener, - hasSessionTicketListener: this.hasSessionTicketListener, - hasNewTokenListener: this.hasNewTokenListener, - hasOriginListener: this.hasOriginListener, - isClosing: this.isClosing, - isGracefulClose: this.isGracefulClose, - isSilentClose: this.isSilentClose, - isStatelessReset: this.isStatelessReset, - isHandshakeCompleted: this.isHandshakeCompleted, - isHandshakeConfirmed: this.isHandshakeConfirmed, - isStreamOpenAllowed: this.isStreamOpenAllowed, - isPrioritySupported: this.isPrioritySupported, - headersSupported: this.headersSupported, - isWrapped: this.isWrapped, - applicationType: this.applicationType, - noErrorCode: this.noErrorCode, - internalErrorCode: this.internalErrorCode, - maxDatagramSize: this.maxDatagramSize, - lastDatagramId: this.lastDatagramId, + hasPathValidationListener, + hasDatagramListener, + hasDatagramStatusListener, + hasSessionTicketListener, + hasNewTokenListener, + hasOriginListener, + isClosing, + isGracefulClose, + isSilentClose, + isStatelessReset, + isHandshakeCompleted, + isHandshakeConfirmed, + isStreamOpenAllowed, + isPrioritySupported, + headersSupported, + isWrapped, + applicationType, + noErrorCode, + internalErrorCode, + maxDatagramSize, + lastDatagramId, + maxPendingDatagrams, }, opts)}`; } [kFinishClose]() { - // Snapshot the state into a new DataView since the underlying - // buffer will be destroyed. - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return; - this.#handle = new DataView(new ArrayBuffer(0)); + this.#handle = undefined; } } @@ -598,6 +692,8 @@ class QuicStreamState { #handle; /** @type {number} */ #offset = 0; + /** @type {bigint|undefined} */ + #id = undefined; /** * @param {symbol} privateSymbol @@ -618,144 +714,166 @@ class QuicStreamState { /** @type {bigint} */ get id() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return DataViewPrototypeGetBigInt64(this.#handle, this.#offset + IDX_STATE_STREAM_ID, kIsLittleEndian); + const handle = this.#handle; + if (handle === undefined) return this.#id; + return DataViewPrototypeGetBigInt64(handle, this.#offset + IDX_STATE_STREAM_ID, kIsLittleEndian); } /** @type {boolean} */ get pending() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_STREAM_PENDING); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_STREAM_PENDING) !== 0; } /** @type {boolean} */ get finSent() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_STREAM_FIN_SENT); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_STREAM_FIN_SENT) !== 0; } /** @type {boolean} */ get finReceived() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_STREAM_FIN_RECEIVED); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_STREAM_FIN_RECEIVED) !== 0; } /** @type {boolean} */ get readEnded() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_STREAM_READ_ENDED); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_STREAM_READ_ENDED) !== 0; } /** @type {boolean} */ get writeEnded() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_STREAM_WRITE_ENDED); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_STREAM_WRITE_ENDED) !== 0; } - /** @type {boolean} */ get reset() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_STREAM_RESET); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_STREAM_RESET) !== 0; } /** @type {boolean} */ get hasOutbound() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_STREAM_HAS_OUTBOUND); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_STREAM_HAS_OUTBOUND) !== 0; } /** @type {boolean} */ get hasReader() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_STREAM_HAS_READER); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_STREAM_HAS_READER) !== 0; } /** @type {boolean} */ get wantsBlock() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_STREAM_WANTS_BLOCK); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_STREAM_WANTS_BLOCK) !== 0; } /** @type {boolean} */ set wantsBlock(val) { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return; - DataViewPrototypeSetUint8(this.#handle, this.#offset + IDX_STATE_STREAM_WANTS_BLOCK, val ? 1 : 0); + const handle = this.#handle; + if (handle === undefined) return; + DataViewPrototypeSetUint8(handle, this.#offset + IDX_STATE_STREAM_WANTS_BLOCK, val ? 1 : 0); } /** @type {boolean} */ - get [kWantsHeaders]() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_STREAM_WANTS_HEADERS); + get wantsHeaders() { + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_STREAM_WANTS_HEADERS) !== 0; } /** @type {boolean} */ - set [kWantsHeaders](val) { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return; - DataViewPrototypeSetUint8(this.#handle, this.#offset + IDX_STATE_STREAM_WANTS_HEADERS, val ? 1 : 0); + set wantsHeaders(val) { + const handle = this.#handle; + if (handle === undefined) return; + DataViewPrototypeSetUint8(handle, this.#offset + IDX_STATE_STREAM_WANTS_HEADERS, val ? 1 : 0); } /** @type {boolean} */ get wantsReset() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_STREAM_WANTS_RESET); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_STREAM_WANTS_RESET) !== 0; } /** @type {boolean} */ set wantsReset(val) { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return; - DataViewPrototypeSetUint8(this.#handle, this.#offset + IDX_STATE_STREAM_WANTS_RESET, val ? 1 : 0); + const handle = this.#handle; + if (handle === undefined) return; + DataViewPrototypeSetUint8(handle, this.#offset + IDX_STATE_STREAM_WANTS_RESET, val ? 1 : 0); } /** @type {boolean} */ - get [kWantsTrailers]() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_STREAM_WANTS_TRAILERS); + get wantsTrailers() { + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_STREAM_WANTS_TRAILERS) !== 0; } /** @type {boolean} */ - set [kWantsTrailers](val) { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return; - DataViewPrototypeSetUint8(this.#handle, this.#offset + IDX_STATE_STREAM_WANTS_TRAILERS, val ? 1 : 0); + set wantsTrailers(val) { + const handle = this.#handle; + if (handle === undefined) return; + DataViewPrototypeSetUint8(handle, this.#offset + IDX_STATE_STREAM_WANTS_TRAILERS, val ? 1 : 0); } /** @type {boolean} */ get early() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; - return !!DataViewPrototypeGetUint8(this.#handle, this.#offset + IDX_STATE_STREAM_RECEIVED_EARLY_DATA); + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8(handle, this.#offset + IDX_STATE_STREAM_RECEIVED_EARLY_DATA) !== 0; } /** @type {bigint} */ get resetCode() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; + const handle = this.#handle; + if (handle === undefined) return undefined; return DataViewPrototypeGetBigUint64( - this.#handle, this.#offset + IDX_STATE_STREAM_RESET_CODE, kIsLittleEndian); + handle, this.#offset + IDX_STATE_STREAM_RESET_CODE, kIsLittleEndian); } /** @type {bigint} */ get writeDesiredSize() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; + const handle = this.#handle; + if (handle === undefined) return undefined; return DataViewPrototypeGetUint32( - this.#handle, this.#offset + IDX_STATE_STREAM_WRITE_DESIRED_SIZE, kIsLittleEndian); + handle, this.#offset + IDX_STATE_STREAM_WRITE_DESIRED_SIZE, kIsLittleEndian); } set writeDesiredSize(val) { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return; + const handle = this.#handle; + if (handle === undefined) return; DataViewPrototypeSetUint32( - this.#handle, this.#offset + IDX_STATE_STREAM_WRITE_DESIRED_SIZE, val, kIsLittleEndian); + handle, this.#offset + IDX_STATE_STREAM_WRITE_DESIRED_SIZE, val, kIsLittleEndian); } /** @type {number} */ get highWaterMark() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return undefined; + const handle = this.#handle; + if (handle === undefined) return undefined; return DataViewPrototypeGetUint32( - this.#handle, this.#offset + IDX_STATE_STREAM_HIGH_WATER_MARK, kIsLittleEndian); + handle, this.#offset + IDX_STATE_STREAM_HIGH_WATER_MARK, kIsLittleEndian); } set highWaterMark(val) { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return; + const handle = this.#handle; + if (handle === undefined) return; DataViewPrototypeSetUint32( - this.#handle, this.#offset + IDX_STATE_STREAM_HIGH_WATER_MARK, val, kIsLittleEndian); + handle, this.#offset + IDX_STATE_STREAM_HIGH_WATER_MARK, val, kIsLittleEndian); } toString() { @@ -763,59 +881,108 @@ class QuicStreamState { } toJSON() { - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return {}; + if (this.#handle === undefined) return kEmptyObject; + const { + id, + pending, + finSent, + finReceived, + readEnded, + writeEnded, + reset, + hasOutbound, + hasReader, + wantsBlock, + wantsReset, + wantsHeaders, + wantsTrailers, + early, + resetCode, + writeDesiredSize, + highWaterMark, + } = this; return { __proto__: null, - id: `${this.id}`, - pending: this.pending, - finSent: this.finSent, - finReceived: this.finReceived, - readEnded: this.readEnded, - writeEnded: this.writeEnded, - reset: this.reset, - hasOutbound: this.hasOutbound, - hasReader: this.hasReader, - wantsBlock: this.wantsBlock, - wantsReset: this.wantsReset, - early: this.early, + id: `${id}`, + pending, + finSent, + finReceived, + readEnded, + writeEnded, + reset, + hasOutbound, + hasReader, + wantsBlock, + wantsReset, + wantsHeaders, + wantsTrailers, + early, + resetCode, + writeDesiredSize, + highWaterMark, }; } [kInspect](depth, options) { - if (depth < 0) - return this; - if (DataViewPrototypeGetByteLength(this.#handle) === 0) { return 'QuicStreamState { }'; } + if (depth < 0) { + return 'QuicStreamState { }'; + } + const opts = { __proto__: null, ...options, depth: options.depth == null ? null : options.depth - 1, }; + const { + id, + pending, + finSent, + finReceived, + readEnded, + writeEnded, + reset, + hasOutbound, + hasReader, + wantsBlock, + wantsReset, + wantsHeaders, + wantsTrailers, + early, + resetCode, + writeDesiredSize, + highWaterMark, + } = this; + return `QuicStreamState ${inspect({ - id: this.id, - pending: this.pending, - finSent: this.finSent, - finReceived: this.finReceived, - readEnded: this.readEnded, - writeEnded: this.writeEnded, - reset: this.reset, - hasOutbound: this.hasOutbound, - hasReader: this.hasReader, - wantsBlock: this.wantsBlock, - wantsReset: this.wantsReset, - early: this.early, + id, + pending, + finSent, + finReceived, + readEnded, + writeEnded, + reset, + hasOutbound, + hasReader, + wantsBlock, + wantsReset, + wantsHeaders, + wantsTrailers, + early, + resetCode, + writeDesiredSize, + highWaterMark, }, opts)}`; } [kFinishClose]() { - // Snapshot the state into a new DataView since the underlying - // buffer will be destroyed. - if (DataViewPrototypeGetByteLength(this.#handle) === 0) return; - this.#handle = new DataView(new ArrayBuffer(0)); + // Cache the stream ID since the buffer will be zeroed out and the ID will be lost. + this.#id = this.id; + this.#handle = undefined; } } diff --git a/lib/internal/quic/stats.js b/lib/internal/quic/stats.js index 27a986f4d05..9ffbff8df20 100644 --- a/lib/internal/quic/stats.js +++ b/lib/internal/quic/stats.js @@ -7,6 +7,8 @@ const { BigUint64Array, JSONStringify, + Symbol, + TypedArrayPrototypeSubarray, } = primordials; const { @@ -25,6 +27,7 @@ const { codes: { ERR_ILLEGAL_CONSTRUCTOR, ERR_INVALID_ARG_TYPE, + ERR_INVALID_THIS, }, } = require('internal/errors'); @@ -88,11 +91,11 @@ const { IDX_STATS_SESSION_BYTES_LOST, IDX_STATS_SESSION_PING_RECV, IDX_STATS_SESSION_PKT_DISCARDED, - IDX_STATS_SESSION_DATAGRAMS_RECEIVED, IDX_STATS_SESSION_DATAGRAMS_SENT, IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED, IDX_STATS_SESSION_DATAGRAMS_LOST, + IDX_STATS_SESSION_COUNT, IDX_STATS_STREAM_CREATED_AT, IDX_STATS_STREAM_OPENED_AT, @@ -105,6 +108,7 @@ const { IDX_STATS_STREAM_MAX_OFFSET_ACK, IDX_STATS_STREAM_MAX_OFFSET_RECV, IDX_STATS_STREAM_FINAL_SIZE, + IDX_STATS_STREAM_COUNT, } = internalBinding('quic'); assert(IDX_STATS_ENDPOINT_CREATED_AT !== undefined); @@ -162,6 +166,23 @@ assert(IDX_STATS_STREAM_MAX_OFFSET !== undefined); assert(IDX_STATS_STREAM_MAX_OFFSET_ACK !== undefined); assert(IDX_STATS_STREAM_MAX_OFFSET_RECV !== undefined); assert(IDX_STATS_STREAM_FINAL_SIZE !== undefined); +assert(IDX_STATS_STREAM_COUNT !== undefined); +assert(IDX_STATS_SESSION_COUNT !== undefined); + +const kCreateDisconnected = Symbol('kCreateDisconnected'); + +let assertIsQuicEndpointStats; +let assertIsQuicSessionStats; +let assertIsQuicStreamStats; +let isQuicEndpointStats; +let isQuicSessionStats; +let isQuicStreamStats; + +function assertIsPrivateConstructor(privateSymbol) { + if (privateSymbol !== kPrivateConstructor) { + throw new ERR_ILLEGAL_CONSTRUCTOR(); + } +} class QuicEndpointStats { /** @type {BigUint64Array} */ @@ -169,6 +190,18 @@ class QuicEndpointStats { /** @type {boolean} */ #disconnected = false; + static { + isQuicEndpointStats = function(val) { + return val != null && typeof val === 'object' && #handle in val; + }; + + assertIsQuicEndpointStats = function(val) { + if (!isQuicEndpointStats(val)) { + throw new ERR_INVALID_THIS('QuicEndpointStats'); + } + }; + } + /** * @param {symbol} privateSymbol * @param {ArrayBuffer} buffer @@ -176,9 +209,7 @@ class QuicEndpointStats { constructor(privateSymbol, buffer) { // We use the kPrivateConstructor symbol to restrict the ability to // create new instances of QuicEndpointStats to internal code. - if (privateSymbol !== kPrivateConstructor) { - throw new ERR_ILLEGAL_CONSTRUCTOR(); - } + assertIsPrivateConstructor(privateSymbol); if (!isArrayBuffer(buffer)) { throw new ERR_INVALID_ARG_TYPE('buffer', ['ArrayBuffer'], buffer); } @@ -187,66 +218,79 @@ class QuicEndpointStats { /** @type {bigint} */ get createdAt() { + assertIsQuicEndpointStats(this); return this.#handle[IDX_STATS_ENDPOINT_CREATED_AT]; } /** @type {bigint} */ get destroyedAt() { + assertIsQuicEndpointStats(this); return this.#handle[IDX_STATS_ENDPOINT_DESTROYED_AT]; } /** @type {bigint} */ get bytesReceived() { + assertIsQuicEndpointStats(this); return this.#handle[IDX_STATS_ENDPOINT_BYTES_RECEIVED]; } /** @type {bigint} */ get bytesSent() { + assertIsQuicEndpointStats(this); return this.#handle[IDX_STATS_ENDPOINT_BYTES_SENT]; } /** @type {bigint} */ get packetsReceived() { + assertIsQuicEndpointStats(this); return this.#handle[IDX_STATS_ENDPOINT_PACKETS_RECEIVED]; } /** @type {bigint} */ get packetsSent() { + assertIsQuicEndpointStats(this); return this.#handle[IDX_STATS_ENDPOINT_PACKETS_SENT]; } /** @type {bigint} */ get serverSessions() { + assertIsQuicEndpointStats(this); return this.#handle[IDX_STATS_ENDPOINT_SERVER_SESSIONS]; } /** @type {bigint} */ get clientSessions() { + assertIsQuicEndpointStats(this); return this.#handle[IDX_STATS_ENDPOINT_CLIENT_SESSIONS]; } /** @type {bigint} */ get serverBusyCount() { + assertIsQuicEndpointStats(this); return this.#handle[IDX_STATS_ENDPOINT_SERVER_BUSY_COUNT]; } /** @type {bigint} */ get retryCount() { + assertIsQuicEndpointStats(this); return this.#handle[IDX_STATS_ENDPOINT_RETRY_COUNT]; } /** @type {bigint} */ get versionNegotiationCount() { + assertIsQuicEndpointStats(this); return this.#handle[IDX_STATS_ENDPOINT_VERSION_NEGOTIATION_COUNT]; } /** @type {bigint} */ get statelessResetCount() { + assertIsQuicEndpointStats(this); return this.#handle[IDX_STATS_ENDPOINT_STATELESS_RESET_COUNT]; } /** @type {bigint} */ get immediateCloseCount() { + assertIsQuicEndpointStats(this); return this.#handle[IDX_STATS_ENDPOINT_IMMEDIATE_CLOSE_COUNT]; } @@ -255,30 +299,48 @@ class QuicEndpointStats { } toJSON() { + assertIsQuicEndpointStats(this); + const { + createdAt, + destroyedAt, + bytesReceived, + bytesSent, + packetsReceived, + packetsSent, + serverSessions, + clientSessions, + serverBusyCount, + retryCount, + versionNegotiationCount, + statelessResetCount, + immediateCloseCount, + } = this; return { __proto__: null, connected: this.isConnected, // We need to convert the values to strings because JSON does not // support BigInts. - createdAt: `${this.createdAt}`, - destroyedAt: `${this.destroyedAt}`, - bytesReceived: `${this.bytesReceived}`, - bytesSent: `${this.bytesSent}`, - packetsReceived: `${this.packetsReceived}`, - packetsSent: `${this.packetsSent}`, - serverSessions: `${this.serverSessions}`, - clientSessions: `${this.clientSessions}`, - serverBusyCount: `${this.serverBusyCount}`, - retryCount: `${this.retryCount}`, - versionNegotiationCount: `${this.versionNegotiationCount}`, - statelessResetCount: `${this.statelessResetCount}`, - immediateCloseCount: `${this.immediateCloseCount}`, + createdAt: `${createdAt}`, + destroyedAt: `${destroyedAt}`, + bytesReceived: `${bytesReceived}`, + bytesSent: `${bytesSent}`, + packetsReceived: `${packetsReceived}`, + packetsSent: `${packetsSent}`, + serverSessions: `${serverSessions}`, + clientSessions: `${clientSessions}`, + serverBusyCount: `${serverBusyCount}`, + retryCount: `${retryCount}`, + versionNegotiationCount: `${versionNegotiationCount}`, + statelessResetCount: `${statelessResetCount}`, + immediateCloseCount: `${immediateCloseCount}`, }; } [kInspect](depth, options) { - if (depth < 0) - return this; + assertIsQuicEndpointStats(this); + if (depth < 0) { + return 'QuicEndpointStats { }'; + } const opts = { __proto__: null, @@ -286,21 +348,37 @@ class QuicEndpointStats { depth: options.depth == null ? null : options.depth - 1, }; + const { + createdAt, + destroyedAt, + bytesReceived, + bytesSent, + packetsReceived, + packetsSent, + serverSessions, + clientSessions, + serverBusyCount, + retryCount, + versionNegotiationCount, + statelessResetCount, + immediateCloseCount, + } = this; + return `QuicEndpointStats ${inspect({ connected: this.isConnected, - createdAt: this.createdAt, - destroyedAt: this.destroyedAt, - bytesReceived: this.bytesReceived, - bytesSent: this.bytesSent, - packetsReceived: this.packetsReceived, - packetsSent: this.packetsSent, - serverSessions: this.serverSessions, - clientSessions: this.clientSessions, - serverBusyCount: this.serverBusyCount, - retryCount: this.retryCount, - versionNegotiationCount: this.versionNegotiationCount, - statelessResetCount: this.statelessResetCount, - immediateCloseCount: this.immediateCloseCount, + createdAt, + destroyedAt, + bytesReceived, + bytesSent, + packetsReceived, + packetsSent, + serverSessions, + clientSessions, + serverBusyCount, + retryCount, + versionNegotiationCount, + statelessResetCount, + immediateCloseCount, }, opts)}`; } @@ -311,12 +389,11 @@ class QuicEndpointStats { * @type {boolean} */ get isConnected() { + assertIsQuicEndpointStats(this); return !this.#disconnected; } [kFinishClose]() { - // Snapshot the stats into a new BigUint64Array since the underlying - // buffer will be destroyed. this.#handle = new BigUint64Array(this.#handle); this.#disconnected = true; } @@ -325,22 +402,31 @@ class QuicEndpointStats { class QuicSessionStats { /** @type {BigUint64Array} */ #handle; - /** @type {boolean} */ #disconnected = false; + #offset = 0; + + static { + isQuicSessionStats = function(val) { + return val != null && typeof val === 'object' && #handle in val; + }; + + assertIsQuicSessionStats = function(val) { + if (!isQuicSessionStats(val)) { + throw new ERR_INVALID_THIS('QuicSessionStats'); + } + }; + } + /** * @param {symbol} privateSymbol - * @param {ArrayBuffer} buffer + * @param {ArrayBuffer} view + * @param {number} [byteOffset] */ - /** @type {number} */ - #offset = 0; - constructor(privateSymbol, view, byteOffset = 0) { // We use the kPrivateConstructor symbol to restrict the ability to // create new instances of QuicSessionStats to internal code. - if (privateSymbol !== kPrivateConstructor) { - throw new ERR_ILLEGAL_CONSTRUCTOR(); - } + assertIsPrivateConstructor(privateSymbol); if (isArrayBuffer(view)) { this.#handle = new BigUint64Array(view); } else { @@ -351,148 +437,179 @@ class QuicSessionStats { /** @type {bigint} */ get createdAt() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_CREATED_AT]; } /** @type {bigint} */ get destroyedAt() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_DESTROYED_AT]; } /** @type {bigint} */ get closingAt() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_CLOSING_AT]; } /** @type {bigint} */ get handshakeCompletedAt() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_HANDSHAKE_COMPLETED_AT]; } /** @type {bigint} */ get handshakeConfirmedAt() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_HANDSHAKE_CONFIRMED_AT]; } /** @type {bigint} */ get bytesReceived() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_BYTES_RECEIVED]; } /** @type {bigint} */ get bidiInStreamCount() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_BIDI_IN_STREAM_COUNT]; } /** @type {bigint} */ get bidiOutStreamCount() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_BIDI_OUT_STREAM_COUNT]; } /** @type {bigint} */ get uniInStreamCount() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_UNI_IN_STREAM_COUNT]; } /** @type {bigint} */ get uniOutStreamCount() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_UNI_OUT_STREAM_COUNT]; } /** @type {bigint} */ get maxBytesInFlight() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_MAX_BYTES_IN_FLIGHT]; } /** @type {bigint} */ get bytesInFlight() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_BYTES_IN_FLIGHT]; } /** @type {bigint} */ get blockCount() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_BLOCK_COUNT]; } /** @type {bigint} */ get cwnd() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_CWND]; } /** @type {bigint} */ get latestRtt() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_LATEST_RTT]; } /** @type {bigint} */ get minRtt() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_MIN_RTT]; } /** @type {bigint} */ get rttVar() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_RTTVAR]; } /** @type {bigint} */ get smoothedRtt() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_SMOOTHED_RTT]; } /** @type {bigint} */ get ssthresh() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_SSTHRESH]; } get pktSent() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_PKT_SENT]; } get bytesSent() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_BYTES_SENT]; } get pktRecv() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_PKT_RECV]; } get bytesRecv() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_BYTES_RECV]; } get pktLost() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_PKT_LOST]; } get bytesLost() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_BYTES_LOST]; } get pingRecv() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_PING_RECV]; } get pktDiscarded() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_PKT_DISCARDED]; } /** @type {bigint} */ get datagramsReceived() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_DATAGRAMS_RECEIVED]; } /** @type {bigint} */ get datagramsSent() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_DATAGRAMS_SENT]; } /** @type {bigint} */ get datagramsAcknowledged() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_DATAGRAMS_ACKNOWLEDGED]; } /** @type {bigint} */ get datagramsLost() { + assertIsQuicSessionStats(this); return this.#handle[this.#offset + IDX_STATS_SESSION_DATAGRAMS_LOST]; } @@ -501,47 +618,81 @@ class QuicSessionStats { } toJSON() { + assertIsQuicSessionStats(this); + const { + createdAt, + closingAt, + handshakeCompletedAt, + handshakeConfirmedAt, + bytesReceived, + bidiInStreamCount, + bidiOutStreamCount, + uniInStreamCount, + uniOutStreamCount, + maxBytesInFlight, + bytesInFlight, + blockCount, + cwnd, + latestRtt, + minRtt, + rttVar, + smoothedRtt, + ssthresh, + pktSent, + bytesSent, + pktRecv, + bytesRecv, + pktLost, + bytesLost, + pingRecv, + pktDiscarded, + datagramsReceived, + datagramsSent, + datagramsAcknowledged, + datagramsLost, + } = this; return { __proto__: null, connected: this.isConnected, // We need to convert the values to strings because JSON does not // support BigInts. - createdAt: `${this.createdAt}`, - closingAt: `${this.closingAt}`, - handshakeCompletedAt: `${this.handshakeCompletedAt}`, - handshakeConfirmedAt: `${this.handshakeConfirmedAt}`, - bytesReceived: `${this.bytesReceived}`, - bidiInStreamCount: `${this.bidiInStreamCount}`, - bidiOutStreamCount: `${this.bidiOutStreamCount}`, - uniInStreamCount: `${this.uniInStreamCount}`, - uniOutStreamCount: `${this.uniOutStreamCount}`, - maxBytesInFlight: `${this.maxBytesInFlight}`, - bytesInFlight: `${this.bytesInFlight}`, - blockCount: `${this.blockCount}`, - cwnd: `${this.cwnd}`, - latestRtt: `${this.latestRtt}`, - minRtt: `${this.minRtt}`, - rttVar: `${this.rttVar}`, - smoothedRtt: `${this.smoothedRtt}`, - ssthresh: `${this.ssthresh}`, - pktSent: `${this.pktSent}`, - bytesSent: `${this.bytesSent}`, - pktRecv: `${this.pktRecv}`, - bytesRecv: `${this.bytesRecv}`, - pktLost: `${this.pktLost}`, - bytesLost: `${this.bytesLost}`, - pingRecv: `${this.pingRecv}`, - pktDiscarded: `${this.pktDiscarded}`, - datagramsReceived: `${this.datagramsReceived}`, - datagramsSent: `${this.datagramsSent}`, - datagramsAcknowledged: `${this.datagramsAcknowledged}`, - datagramsLost: `${this.datagramsLost}`, + createdAt: `${createdAt}`, + closingAt: `${closingAt}`, + handshakeCompletedAt: `${handshakeCompletedAt}`, + handshakeConfirmedAt: `${handshakeConfirmedAt}`, + bytesReceived: `${bytesReceived}`, + bidiInStreamCount: `${bidiInStreamCount}`, + bidiOutStreamCount: `${bidiOutStreamCount}`, + uniInStreamCount: `${uniInStreamCount}`, + uniOutStreamCount: `${uniOutStreamCount}`, + maxBytesInFlight: `${maxBytesInFlight}`, + bytesInFlight: `${bytesInFlight}`, + blockCount: `${blockCount}`, + cwnd: `${cwnd}`, + latestRtt: `${latestRtt}`, + minRtt: `${minRtt}`, + rttVar: `${rttVar}`, + smoothedRtt: `${smoothedRtt}`, + ssthresh: `${ssthresh}`, + pktSent: `${pktSent}`, + bytesSent: `${bytesSent}`, + pktRecv: `${pktRecv}`, + bytesRecv: `${bytesRecv}`, + pktLost: `${pktLost}`, + bytesLost: `${bytesLost}`, + pingRecv: `${pingRecv}`, + pktDiscarded: `${pktDiscarded}`, + datagramsReceived: `${datagramsReceived}`, + datagramsSent: `${datagramsSent}`, + datagramsAcknowledged: `${datagramsAcknowledged}`, + datagramsLost: `${datagramsLost}`, }; } [kInspect](depth, options) { - if (depth < 0) - return this; + if (depth < 0) { + return 'QuicSessionStats { }'; + } const opts = { __proto__: null, @@ -549,38 +700,71 @@ class QuicSessionStats { depth: options.depth == null ? null : options.depth - 1, }; + const { + createdAt, + closingAt, + handshakeCompletedAt, + handshakeConfirmedAt, + bytesReceived, + bidiInStreamCount, + bidiOutStreamCount, + uniInStreamCount, + uniOutStreamCount, + maxBytesInFlight, + bytesInFlight, + blockCount, + cwnd, + latestRtt, + minRtt, + rttVar, + smoothedRtt, + ssthresh, + pktSent, + bytesSent, + pktRecv, + bytesRecv, + pktLost, + bytesLost, + pingRecv, + pktDiscarded, + datagramsReceived, + datagramsSent, + datagramsAcknowledged, + datagramsLost, + } = this; + return `QuicSessionStats ${inspect({ connected: this.isConnected, - createdAt: this.createdAt, - closingAt: this.closingAt, - handshakeCompletedAt: this.handshakeCompletedAt, - handshakeConfirmedAt: this.handshakeConfirmedAt, - bytesReceived: this.bytesReceived, - bidiInStreamCount: this.bidiInStreamCount, - bidiOutStreamCount: this.bidiOutStreamCount, - uniInStreamCount: this.uniInStreamCount, - uniOutStreamCount: this.uniOutStreamCount, - maxBytesInFlight: this.maxBytesInFlight, - bytesInFlight: this.bytesInFlight, - blockCount: this.blockCount, - cwnd: this.cwnd, - latestRtt: this.latestRtt, - minRtt: this.minRtt, - rttVar: this.rttVar, - smoothedRtt: this.smoothedRtt, - ssthresh: this.ssthresh, - pktSent: this.pktSent, - bytesSent: this.bytesSent, - pktRecv: this.pktRecv, - bytesRecv: this.bytesRecv, - pktLost: this.pktLost, - bytesLost: this.bytesLost, - pingRecv: this.pingRecv, - pktDiscarded: this.pktDiscarded, - datagramsReceived: this.datagramsReceived, - datagramsSent: this.datagramsSent, - datagramsAcknowledged: this.datagramsAcknowledged, - datagramsLost: this.datagramsLost, + createdAt, + closingAt, + handshakeCompletedAt, + handshakeConfirmedAt, + bytesReceived, + bidiInStreamCount, + bidiOutStreamCount, + uniInStreamCount, + uniOutStreamCount, + maxBytesInFlight, + bytesInFlight, + blockCount, + cwnd, + latestRtt, + minRtt, + rttVar, + smoothedRtt, + ssthresh, + pktSent, + bytesSent, + pktRecv, + bytesRecv, + pktLost, + bytesLost, + pingRecv, + pktDiscarded, + datagramsReceived, + datagramsSent, + datagramsAcknowledged, + datagramsLost, }, opts)}`; } @@ -595,13 +779,10 @@ class QuicSessionStats { } [kFinishClose]() { - // Snapshot this session's stats slice into a standalone BigUint64Array. - const count = IDX_STATS_SESSION_DATAGRAMS_LOST + 1; - const snapshot = new BigUint64Array(count); - for (let i = 0; i < count; i++) { - snapshot[i] = this.#handle[this.#offset + i]; - } - this.#handle = snapshot; + const view = TypedArrayPrototypeSubarray(this.#handle, + this.#offset, + this.#offset + IDX_STATS_STREAM_COUNT); + this.#handle = new BigUint64Array(view); this.#offset = 0; this.#disconnected = true; } @@ -610,11 +791,21 @@ class QuicSessionStats { class QuicStreamStats { /** @type {BigUint64Array} */ #handle; - /** @type {number} */ #offset = 0; - /** type {boolean} */ #disconnected = false; + static { + isQuicStreamStats = function(val) { + return val != null && typeof val === 'object' && #handle in val; + }; + + assertIsQuicStreamStats = function(val) { + if (!isQuicStreamStats(val)) { + throw new ERR_INVALID_THIS('QuicStreamStats'); + } + }; + } + /** * @param {symbol} privateSymbol * @param {BigUint64Array|ArrayBuffer} view @@ -623,70 +814,78 @@ class QuicStreamStats { constructor(privateSymbol, view, byteOffset = 0) { // We use the kPrivateConstructor symbol to restrict the ability to // create new instances of QuicStreamStats to internal code. - if (privateSymbol !== kPrivateConstructor) { - throw new ERR_ILLEGAL_CONSTRUCTOR(); - } + assertIsPrivateConstructor(privateSymbol); if (isArrayBuffer(view)) { this.#handle = new BigUint64Array(view); } else { this.#handle = view; } - // Convert byte offset to element offset (8 bytes per uint64). this.#offset = byteOffset / 8; } /** @type {bigint} */ get createdAt() { + assertIsQuicStreamStats(this); return this.#handle[this.#offset + IDX_STATS_STREAM_CREATED_AT]; } /** @type {bigint} */ get openedAt() { + assertIsQuicStreamStats(this); return this.#handle[this.#offset + IDX_STATS_STREAM_OPENED_AT]; } /** @type {bigint} */ get receivedAt() { + assertIsQuicStreamStats(this); return this.#handle[this.#offset + IDX_STATS_STREAM_RECEIVED_AT]; } /** @type {bigint} */ get ackedAt() { + assertIsQuicStreamStats(this); return this.#handle[this.#offset + IDX_STATS_STREAM_ACKED_AT]; } /** @type {bigint} */ get destroyedAt() { + assertIsQuicStreamStats(this); return this.#handle[this.#offset + IDX_STATS_STREAM_DESTROYED_AT]; } /** @type {bigint} */ get bytesReceived() { + assertIsQuicStreamStats(this); return this.#handle[this.#offset + IDX_STATS_STREAM_BYTES_RECEIVED]; } /** @type {bigint} */ get bytesSent() { + assertIsQuicStreamStats(this); return this.#handle[this.#offset + IDX_STATS_STREAM_BYTES_SENT]; } /** @type {bigint} */ get maxOffset() { + assertIsQuicStreamStats(this); return this.#handle[this.#offset + IDX_STATS_STREAM_MAX_OFFSET]; } /** @type {bigint} */ get maxOffsetAcknowledged() { + assertIsQuicStreamStats(this); return this.#handle[this.#offset + IDX_STATS_STREAM_MAX_OFFSET_ACK]; } /** @type {bigint} */ get maxOffsetReceived() { + assertIsQuicStreamStats(this); return this.#handle[this.#offset + IDX_STATS_STREAM_MAX_OFFSET_RECV]; } /** @type {bigint} */ get finalSize() { + assertIsQuicStreamStats(this); return this.#handle[this.#offset + IDX_STATS_STREAM_FINAL_SIZE]; } @@ -695,28 +894,43 @@ class QuicStreamStats { } toJSON() { + assertIsQuicStreamStats(this); + const { + createdAt, + openedAt, + receivedAt, + ackedAt, + destroyedAt, + bytesReceived, + bytesSent, + maxOffset, + maxOffsetAcknowledged, + maxOffsetReceived, + finalSize, + } = this; return { __proto__: null, connected: this.isConnected, // We need to convert the values to strings because JSON does not // support BigInts. - createdAt: `${this.createdAt}`, - openedAt: `${this.openedAt}`, - receivedAt: `${this.receivedAt}`, - ackedAt: `${this.ackedAt}`, - destroyedAt: `${this.destroyedAt}`, - bytesReceived: `${this.bytesReceived}`, - bytesSent: `${this.bytesSent}`, - maxOffset: `${this.maxOffset}`, - maxOffsetAcknowledged: `${this.maxOffsetAcknowledged}`, - maxOffsetReceived: `${this.maxOffsetReceived}`, - finalSize: `${this.finalSize}`, + createdAt: `${createdAt}`, + openedAt: `${openedAt}`, + receivedAt: `${receivedAt}`, + ackedAt: `${ackedAt}`, + destroyedAt: `${destroyedAt}`, + bytesReceived: `${bytesReceived}`, + bytesSent: `${bytesSent}`, + maxOffset: `${maxOffset}`, + maxOffsetAcknowledged: `${maxOffsetAcknowledged}`, + maxOffsetReceived: `${maxOffsetReceived}`, + finalSize: `${finalSize}`, }; } [kInspect](depth, options) { - if (depth < 0) - return this; + if (depth < 0) { + return 'QuicStreamStats { }'; + } const opts = { __proto__: null, @@ -724,19 +938,33 @@ class QuicStreamStats { depth: options.depth == null ? null : options.depth - 1, }; + const { + createdAt, + openedAt, + receivedAt, + ackedAt, + destroyedAt, + bytesReceived, + bytesSent, + maxOffset, + maxOffsetAcknowledged, + maxOffsetReceived, + finalSize, + } = this; + return `QuicStreamStats ${inspect({ connected: this.isConnected, - createdAt: this.createdAt, - openedAt: this.openedAt, - receivedAt: this.receivedAt, - ackedAt: this.ackedAt, - destroyedAt: this.destroyedAt, - bytesReceived: this.bytesReceived, - bytesSent: this.bytesSent, - maxOffset: this.maxOffset, - maxOffsetAcknowledged: this.maxOffsetAcknowledged, - maxOffsetReceived: this.maxOffsetReceived, - finalSize: this.finalSize, + createdAt, + openedAt, + receivedAt, + ackedAt, + destroyedAt, + bytesReceived, + bytesSent, + maxOffset, + maxOffsetAcknowledged, + maxOffsetReceived, + finalSize, }, opts)}`; } @@ -751,22 +979,29 @@ class QuicStreamStats { } [kFinishClose]() { - // Snapshot this stream's stats slice into a standalone BigUint64Array. - const count = IDX_STATS_STREAM_FINAL_SIZE + 1; - const snapshot = new BigUint64Array(count); - for (let i = 0; i < count; i++) { - snapshot[i] = this.#handle[this.#offset + i]; - } - this.#handle = snapshot; + const view = TypedArrayPrototypeSubarray(this.#handle, + this.#offset, + this.#offset + IDX_STATS_STREAM_COUNT); + this.#handle = new BigUint64Array(view); this.#offset = 0; this.#disconnected = true; } + + // Creates an immediately disconnected QuicStreamStats object. Used when + // lazily creating stats for a stream that has already been destroyed. + static [kCreateDisconnected]() { + const count = IDX_STATS_STREAM_FINAL_SIZE + 1; + const stats = new QuicStreamStats(kPrivateConstructor, new BigUint64Array(count), 0); + stats.#disconnected = true; + return stats; + } } module.exports = { QuicEndpointStats, QuicSessionStats, QuicStreamStats, + kCreateDisconnected, }; /* c8 ignore stop */ diff --git a/lib/internal/quic/symbols.js b/lib/internal/quic/symbols.js index 9a8e9155f0b..75f5b72ae22 100644 --- a/lib/internal/quic/symbols.js +++ b/lib/internal/quic/symbols.js @@ -57,8 +57,6 @@ const kSendHeaders = Symbol('kSendHeaders'); const kSessionTicket = Symbol('kSessionTicket'); const kTrailers = Symbol('kTrailers'); const kVersionNegotiation = Symbol('kVersionNegotiation'); -const kWantsHeaders = Symbol('kWantsHeaders'); -const kWantsTrailers = Symbol('kWantsTrailers'); module.exports = { kAttachFileHandle, @@ -93,8 +91,6 @@ module.exports = { kSessionTicket, kTrailers, kVersionNegotiation, - kWantsHeaders, - kWantsTrailers, }; /* c8 ignore stop */ diff --git a/src/quic/session.cc b/src/quic/session.cc index 1cc4b8b23b5..401775355f2 100644 --- a/src/quic/session.cc +++ b/src/quic/session.cc @@ -3729,6 +3729,8 @@ void Session::InitPerContext(Realm* realm, Local target) { SESSION_STATE(V) #undef V + NODE_DEFINE_CONSTANT(target, IDX_STATS_SESSION_COUNT); + #define V(name, _) NODE_DEFINE_CONSTANT(target, IDX_STATS_SESSION_##name); SESSION_STATS(V) NODE_DEFINE_CONSTANT(target, IDX_STATS_SESSION_COUNT); diff --git a/src/quic/streams.cc b/src/quic/streams.cc index abd14300487..634799fb5ae 100644 --- a/src/quic/streams.cc +++ b/src/quic/streams.cc @@ -983,6 +983,8 @@ void Stream::InitPerContext(Realm* realm, Local target) { STREAM_STATE(V) #undef V + NODE_DEFINE_CONSTANT(target, IDX_STATS_STREAM_COUNT); + constexpr int QUIC_STREAM_HEADERS_KIND_HINTS = static_cast(HeadersKind::HINTS); constexpr int QUIC_STREAM_HEADERS_KIND_INITIAL = diff --git a/test/parallel/test-quic-h3-headers-support.mjs b/test/parallel/test-quic-h3-headers-support.mjs index 159f5ba03fa..5439ff5fd3a 100644 --- a/test/parallel/test-quic-h3-headers-support.mjs +++ b/test/parallel/test-quic-h3-headers-support.mjs @@ -27,43 +27,30 @@ const serverDone = Promise.withResolvers(); const serverEndpoint = await listen(mustCall(async (serverSession) => { serverSession.onstream = mustCall(async (stream) => { // Sending headers on non-H3 stream throws. - throws(() => { - stream.sendHeaders({ ':status': '200' }); - }, { code: 'ERR_INVALID_STATE' }); + throws(() => stream.sendHeaders({ ':status': '200' }), { code: 'ERR_INVALID_STATE' }); // Setting onheaders on non-H3 stream throws. - throws(() => { - stream.onheaders = () => {}; - }, { code: 'ERR_INVALID_STATE' }); + throws(() => stream.onheaders = () => {}, { code: 'ERR_INVALID_STATE' }); // Setting ontrailers on non-H3 stream throws. - throws(() => { - stream.ontrailers = () => {}; - }, { code: 'ERR_INVALID_STATE' }); + throws(() => stream.ontrailers = () => {}, { code: 'ERR_INVALID_STATE' }); // Setting oninfo on non-H3 stream throws. - throws(() => { - stream.oninfo = () => {}; - }, { code: 'ERR_INVALID_STATE' }); + throws(() => stream.oninfo = () => {}, { code: 'ERR_INVALID_STATE' }); // Setting onwanttrailers on non-H3 stream throws. - throws(() => { - stream.onwanttrailers = () => {}; - }, { code: 'ERR_INVALID_STATE' }); + throws(() => stream.onwanttrailers = () => {}, { code: 'ERR_INVALID_STATE' }); // sendInformationalHeaders throws on non-H3. - throws(() => { - stream.sendInformationalHeaders({ ':status': '103' }); - }, { code: 'ERR_INVALID_STATE' }); + throws(() => stream.sendInformationalHeaders({ ':status': '103' }), { + code: 'ERR_INVALID_STATE', + }); // sendTrailers throws on non-H3. - throws(() => { - stream.sendTrailers({ 'x-trailer': 'value' }); - }, { code: 'ERR_INVALID_STATE' }); + throws(() => stream.sendTrailers({ 'x-trailer': 'value' }), { code: 'ERR_INVALID_STATE' }); + + stream.writer.endSync(); - try { await stream.closed; } catch { - // Stream may close with error. - } serverSession.close(); serverDone.resolve(); }); @@ -81,15 +68,9 @@ await clientSession.opened; const stream = await clientSession.createBidirectionalStream({ body: encoder.encode('ping'), }); -stream.closed.catch(() => {}); // Client side — sending headers on non-H3 stream throws. -throws(() => { - stream.sendHeaders({ ':method': 'GET' }); -}, { code: 'ERR_INVALID_STATE' }); +throws(() => stream.sendHeaders({ ':method': 'GET' }), { code: 'ERR_INVALID_STATE' }); -try { await stream.closed; } catch { - // Stream may close with error. -} await serverDone.promise; clientSession.close(); diff --git a/test/parallel/test-quic-internal-endpoint-stats-state.mjs b/test/parallel/test-quic-internal-endpoint-stats-state.mjs index 57044a773eb..c8e6cb89bea 100644 --- a/test/parallel/test-quic-internal-endpoint-stats-state.mjs +++ b/test/parallel/test-quic-internal-endpoint-stats-state.mjs @@ -45,7 +45,7 @@ const { isBusy: false, maxConnectionsPerHost: 100, maxConnectionsTotal: 10_000, - pendingCallbacks: '0', + pendingCallbacks: 0, }); endpoint.busy = true; diff --git a/test/parallel/test-quic-session-stream-lifecycle.mjs b/test/parallel/test-quic-session-stream-lifecycle.mjs index f18f82994f2..2eb35145dfe 100644 --- a/test/parallel/test-quic-session-stream-lifecycle.mjs +++ b/test/parallel/test-quic-session-stream-lifecycle.mjs @@ -90,8 +90,9 @@ strictEqual(clientSession.endpoint, null); strictEqual(clientSession.stats.isConnected, false); strictEqual(stream.destroyed, true); -strictEqual(stream.session, null); -strictEqual(stream.id, null); -strictEqual(stream.direction, null); + +// The stream id and direction should still be available after destruction +strictEqual(stream.id, 0n); +strictEqual(stream.direction, 'bidi'); await serverEndpoint.close();