import { Duration, Elapsed, Instant, type Interval, interval, MissedTickBehavior, now, timeout } from "@moq/clock"; import { Credit, StreamLimit, Window } from "./credit.ts"; import { resetCode, SessionError, StreamError, streamCode, TransportCode, TransportError, transportCode, } from "./error.ts"; import type { TransportParams, WireFormat } from "./frame.ts"; import * as Frame from "./frame.ts"; import { DEFAULT_TRANSPORT_PARAMS, usesRecords } from "./frame.ts"; import { Queue } from "./queue.ts"; import { RecvStream } from "./recv.ts"; import { RecvOpen } from "./recv-open.ts"; import { BacklogSink, DEFAULT_SEND_ORDER, SendScheduler, type SendSink, WritableStreamSink } from "./scheduler.ts"; import { SendHalf } from "./send.ts"; import * as Stream from "./stream.ts"; import { VarInt } from "./varint.ts"; import { openWebSocketStream, type WebSocketLike, WebSocketStream, type WebSocketStreamLike, } from "./web-socket-stream.ts"; /** The QMux wire-format versions a caller can advertise. @reexport */ export type Version = WireFormat; /** Options for a new outgoing stream. `@types/web` doesn't declare `waitUntilAvailable` yet. */ export type SendStreamOptions = WebTransportSendStreamOptions & { /** Wait for the peer to grant stream credit (the default) instead of rejecting at once. */ waitUntilAvailable?: boolean; }; /** Configuration for a QMux session. */ export interface Config { /** Max concurrent streams the peer can open, in each direction. */ maxStreams?: bigint; /** Connection-level receive window in bytes. */ receiveWindow?: bigint; /** Receive window in bytes for every stream. */ streamReceiveWindow?: bigint; /** Idle timeout, sent as whole milliseconds rounded up, or null to disable it; zero is refused. */ idleTimeout?: Duration | null; /** How long `ready` waits for the peer's transport parameters, or null to wait indefinitely; * zero is refused. The session closes when it passes. */ handshakeTimeout?: Duration | null; /** Maximum QMux Record size in bytes (draft-01). */ maxRecordSize?: bigint; /** Largest DATAGRAM *frame* (RFC 9221: type + length + payload) we advertise * willingness to receive; null disables datagrams. This is a frame size, not a * payload size; `Session.datagrams.maxDatagramSize` reports the usable payload * (this value less framing overhead). Keep it at or below `maxRecordSize`. * Datagrams are a record-framed-draft feature (qmux-01+); this is ignored on * qmux-00. Defaults to a full record. */ maxDatagramFrameSize?: bigint | null; } const DEFAULT_CONFIG: Required = { maxStreams: 100n, receiveWindow: 1_048_576n, streamReceiveWindow: 262_144n, idleTimeout: Duration.secs(30), handshakeTimeout: Duration.secs(10), maxRecordSize: Frame.DEFAULT_MAX_RECORD_SIZE, // Fill a full record by default; the record layer bounds the size. maxDatagramFrameSize: Frame.DEFAULT_MAX_RECORD_SIZE, }; function resolveConfig(config?: Config): Required { if (config !== undefined && (config === null || typeof config !== "object" || Array.isArray(config))) { throw new TypeError("config must be an object"); } const resolved = { ...DEFAULT_CONFIG }; for (const key of Reflect.ownKeys(config ?? {})) { if (typeof key !== "string" || !Object.hasOwn(DEFAULT_CONFIG, key)) { throw new TypeError(`Unsupported QMux config setting: ${String(key)}`); } const value = config?.[key as keyof Config]; if (value !== undefined) Object.assign(resolved, { [key]: value }); } for (const [key, value] of Object.entries(resolved)) { if (key === "idleTimeout" || key === "handshakeTimeout") { if (value !== null && (!(value instanceof Duration) || value.isZero())) { throw new TypeError(`${key} must be a positive Duration or null`); } if (value !== null && !Number.isSafeInteger(Math.ceil(value.asMillis()))) { throw new TypeError(`${key} exceeds the safe integer millisecond range`); } } else if (key !== "maxDatagramFrameSize" || value !== null) { if (typeof value !== "bigint") throw new TypeError(`${key} must be a bigint`); VarInt.from(value); } } if (resolved.maxDatagramFrameSize === 0n) throw new Error("maxDatagramFrameSize must be positive or null"); if (resolved.maxRecordSize < Frame.DEFAULT_MAX_RECORD_SIZE) { throw new Error(`maxRecordSize must be at least ${Frame.DEFAULT_MAX_RECORD_SIZE}`); } return resolved; } function configToTransportParams(config: Required): TransportParams { return { maxIdleTimeout: BigInt(config.idleTimeout === null ? 0 : Math.ceil(config.idleTimeout.asMillis())), initialMaxData: config.receiveWindow, initialMaxStreamDataBidiLocal: config.streamReceiveWindow, initialMaxStreamDataBidiRemote: config.streamReceiveWindow, initialMaxStreamDataUni: config.streamReceiveWindow, initialMaxStreamsBidi: config.maxStreams, initialMaxStreamsUni: config.maxStreams, // Clamp to maxRecordSize so we never advertise a datagram larger than our // record layer accepts. maxDatagramFrameSize: config.maxDatagramFrameSize === null ? 0n : // biome-ignore lint/complexity/useMathMinMax: bigint operands; Math.min/max throw on bigint. config.maxDatagramFrameSize < config.maxRecordSize ? config.maxDatagramFrameSize : config.maxRecordSize, maxRecordSize: config.maxRecordSize, // Version-gated in #startSession (only advertised on qmux-02). resetStreamAt: false, }; } // Only the session can construct or mutate the datagram transport. const datagramsKey = Symbol("Datagrams"); let makeDatagrams: (send: (data: Uint8Array) => void) => Datagrams; let pushDatagram: (datagrams: Datagrams, data: Uint8Array) => void; let setMaxDatagramSize: (datagrams: Datagrams, size: number) => void; let closeDatagrams: (datagrams: Datagrams, err?: Error) => void; /** WebTransport datagrams with a live inbound queue limit and no expiry. */ class Datagrams implements WebTransportDatagramDuplexStream { /** The datagrams the peer sends. */ readonly readable: ReadableStream; /** The datagrams to send to the peer. */ readonly writable: WritableStream; #incomingHighWaterMark = 1024; #incoming!: ReadableStreamDefaultController; #pending: Uint8Array[] = []; #pullResolve?: () => void; #closed = false; // Resolved from the peer's transport parameters once the handshake completes; // 0 until then (and forever if the peer doesn't accept datagrams). #maxDatagramSize = 0; private constructor(key: typeof datagramsKey, send: (data: Uint8Array) => void) { if (key !== datagramsKey) throw new TypeError("Datagrams can only be constructed by Session"); this.readable = new ReadableStream( { start: (controller) => { this.#incoming = controller; }, pull: () => { const data = this.#pending.shift(); if (data) this.#incoming.enqueue(data); if (this.#closed && this.#pending.length === 0) this.#incoming.close(); if (data || this.#closed) return; return new Promise((resolve) => { this.#pullResolve = resolve; }); }, cancel: () => { this.#closed = true; this.#pending = []; this.#resolvePull(); }, }, // Keep the backlog here so the live policy counts only unread packets. { highWaterMark: 0 }, ); this.writable = new WritableStream({ write: (chunk) => { // Oversized or unsupported datagrams are discarded, not errored: // the writable stays usable, matching unreliable-datagram semantics. if (this.#maxDatagramSize > 0 && chunk.byteLength <= this.#maxDatagramSize) send(chunk); }, }); } static { makeDatagrams = (send) => new Datagrams(datagramsKey, send); pushDatagram = (datagrams, data) => datagrams.#push(data); setMaxDatagramSize = (datagrams, size) => { datagrams.#maxDatagramSize = size; }; closeDatagrams = (datagrams, err) => datagrams.#close(err); } /** The largest payload a datagram can carry, or 0 before the peer allows any. */ get maxDatagramSize(): number { return this.#maxDatagramSize; } /** The live inbound queue limit; lowering it preserves already queued datagrams. */ get incomingHighWaterMark(): number { return this.#incomingHighWaterMark; } set incomingHighWaterMark(value: number) { if (typeof value !== "number") throw new TypeError("incomingHighWaterMark must be a number"); if (Number.isNaN(value) || value < 0) throw new RangeError("incomingHighWaterMark must be nonnegative"); this.#incomingHighWaterMark = Math.max(1, value); } /** Inbound expiry is unsupported. */ get incomingMaxAge(): number | null { return null; } set incomingMaxAge(value: number | null) { if (value !== null) throw new DOMException("Datagram expiry is unsupported", "NotSupportedError"); } /** The outbound queue limit cannot be changed. */ get outgoingHighWaterMark(): number { return 1024; } set outgoingHighWaterMark(value: number) { if (value !== 1024) throw new DOMException("Outbound queue policy is unsupported", "NotSupportedError"); } /** Outbound expiry is unsupported. */ get outgoingMaxAge(): number | null { return null; } set outgoingMaxAge(value: number | null) { if (value !== null) throw new DOMException("Datagram expiry is unsupported", "NotSupportedError"); } #push(data: Uint8Array): void { if (this.#closed) return; if (this.#pullResolve) { this.#incoming.enqueue(data); this.#resolvePull(); } else if (this.#pending.length < this.#incomingHighWaterMark) { this.#pending.push(data); } } #resolvePull(): void { const resolve = this.#pullResolve; this.#pullResolve = undefined; resolve?.(); } #close(err?: Error): void { if (this.#closed) return; this.#closed = true; if (err) { this.#pending = []; this.#incoming.error(err); } else if (this.#pending.length === 0) { this.#incoming.close(); } this.#resolvePull(); } } interface PendingIncomingStream { value: T; onAccept: () => void; onDrop: (err: Error) => void; } /** Application-facing incoming-stream acceptor with no implicit prefetch. * * A normal ReadableStream controller will happily queue past its high-water * mark; `desiredSize` is only a backpressure signal. QMux cannot stop reading * its underlying byte stream, so keep new streams in this explicit queue and * transfer ownership only in response to an application read. The peer's * MAX_STREAMS credit waits on `onAccept`, which bounds this pending queue to the * stream count we advertised. */ class IncomingStreamQueue { readonly readable: ReadableStream; #controller!: ReadableStreamDefaultController; #pending = new Queue>(); #pullResolve?: () => void; #cancelled = false; #closed = false; constructor() { this.readable = new ReadableStream( { start: (controller) => { this.#controller = controller; }, pull: () => { if (this.#deliver()) return; return new Promise((resolve) => { this.#pullResolve = resolve; }); }, cancel: () => { this.#cancelled = true; this.#dropPending(new Error("incoming stream acceptor cancelled")); this.#resolvePull(); }, }, { highWaterMark: 0 }, ); } push(value: T, onAccept: () => void, onDrop: (err: Error) => void): boolean { if (this.#cancelled || this.#closed) return false; this.#pending.push({ value, onAccept, onDrop }); if (this.#pullResolve) { this.#deliver(); this.#resolvePull(); } return true; } close(err?: Error): void { if (this.#closed || this.#cancelled) return; this.#closed = true; this.#dropPending(err ?? new Error("session closed")); try { if (err) this.#controller.error(err); else this.#controller.close(); } catch {} this.#resolvePull(); } #deliver(): boolean { const item = this.#pending.shift(); if (!item) return false; try { this.#controller.enqueue(item.value); item.onAccept(); } catch { item.onDrop(new Error("incoming stream acceptor cancelled")); } return true; } #dropPending(err: Error): void { const pending = this.#pending; this.#pending = new Queue(); for (const item of pending) item.onDrop(err); } #resolvePull(): void { const resolve = this.#pullResolve; this.#pullResolve = undefined; resolve?.(); } } /** What a send stream has sent so far, the shape of W3C WebTransport's `WebTransportSendStreamStats`. */ export interface SendStreamStats { /** The bytes written to the stream. */ bytesWritten: number; /** The bytes handed to the WebSocket. */ bytesSent: number; /** The bytes the peer has acknowledged, which are `bytesSent`: QMux acknowledges data once * it is passed to the underlying transport. */ bytesAcknowledged: number; } /** A stream's send half, with W3C `WebTransportSendStream`'s `sendOrder` and `getStats()`. */ export interface SendStream extends WritableStream { /** Its priority against the session's other streams; higher sends first. */ sendOrder: number; /** What the stream has written, sent, and had acknowledged so far. */ getStats(): Promise; } /** A bidirectional stream whose send half is a {@link SendStream}. */ export interface BidirectionalStream extends WebTransportBidirectionalStream { readonly writable: SendStream; } /** Options for opening a QMux Session over WebSocket. */ export interface SessionOptions extends WebTransportOptions { /** Application-level subprotocols to advertise via `Sec-WebSocket-Protocol`. * * Each entry is either: * - A bare ALPN (e.g. `"moq-lite-04"`). The polyfill resolves it via * {@link SessionOptions.versions} and emits the prefixed wire form * `{version}.{alpn}` (e.g. `"qmux-01.moq-lite-04"`). * - An explicit pair already prefixed with a QMux version * (e.g. `"qmux-00.moq-transport-18"`). Advertised as-is. * * Bare entries that have no matching `versions` entry throw at * construction time. */ protocols?: string[]; /** Maps each bare ALPN to the QMux wire-format version(s) it can ride on. * * Required for every bare entry in `protocols`; entries already in * `{qmux-VV}.{alpn}` pair form bypass this map. Per-entry semantics: * * - `Version`: advertise exactly `{version}.{alpn}`. * - `Version[]`: advertise one `{v}.{alpn}` per array entry in order. * Lets the server pick across multiple QMux drafts. * - `null`: advertise the ALPN under every QMux version this polyfill * knows about (currently qmux-02, qmux-01, then qmux-00). Useful when the * app doesn't care which draft and wants forward compatibility. * */ versions?: Record; /** Require the peer to negotiate one of the app protocols in `protocols`. * * When false (the default), bare QMux version ALPNs are also offered. * Set true to require a version-prefixed application protocol. */ requireProtocol?: boolean; /** QMux flow control configuration. Only used for the QMux wire formats. */ config?: Config; /** Initial send-buffer high-water mark in bytes, used for write * backpressure: past it, writes wait and datagrams are dropped. * Defaults to 64 KiB. * * For best throughput *and* prioritization, set this to roughly the * bandwidth-delay product (RTT × estimated throughput) and adjust it at * runtime with {@link Session.setSendBufferSize}. */ sendBufferSize?: number; } // At least one byte, so a lone frame can always be written; non-finite sizes are a caller bug. function sendBufferSize(bytes: number): number { if (!Number.isFinite(bytes)) throw new RangeError(`invalid sendBufferSize: ${bytes}`); return Math.max(1, Math.floor(bytes)); } /** Options for accepting a QMux Session on an already-negotiated socket. * * The handshake is done by the time [[Session.accept]] is called, so the * subprotocol options ({@link SessionOptions.protocols}, `versions`, * `requireProtocol`) don't apply - see [[selectSubprotocol]], which consumes * them during the upgrade instead. */ export interface AcceptOptions extends Pick { /** The negotiated `Sec-WebSocket-Protocol` value, for hosts that don't expose * it on the socket. * * [[Session.accept]] reads `socket.protocol` by default, which is where the * wire-format version comes from. Set this when the socket reports an empty * protocol despite one having been negotiated - otherwise the session refuses the socket. Pass the full wire value (e.g. `"qmux-02.moq-lite-04"`), not * the bare app protocol. */ protocol?: string; } /** Default send-buffer high-water mark (bytes). */ const DEFAULT_SEND_BUFFER_SIZE = 64 * 1024; /** How long a closing session waits for a backed-up socket to take its close * frame, matching Rust's `CLOSE_TIMEOUT`. A peer that stopped reading can't * hold the socket open past it. */ const CLOSE_TIMEOUT = Duration.secs(3); /** Present the caller's socket as a `WebSocketStreamLike`, whichever they passed. * * A `WebSocketStream` (native or ponyfill) already has the shape; a plain * `WebSocket` gets wrapped, which takes ownership of its event handlers. */ function toWebSocketStream(socket: WebSocketLike | WebSocketStreamLike, highWaterMark: number): WebSocketStreamLike { return "opened" in socket ? socket : WebSocketStream.adopt(socket, { highWaterMark }); } /** Get the subprotocol prefix for a QMux wire-format version. */ function versionPrefix(version: Version): string { switch (version) { case "qmux-02": return "qmux-02."; case "qmux-01": return "qmux-01."; case "qmux-00": return "qmux-00."; default: throw new Error(`Unsupported QMux version: ${JSON.stringify(version)}`); } } /** QMux versions recognized as prefixed ALPNs, newest first. */ const QMUX_VERSIONS = ["qmux-02", "qmux-01", "qmux-00"] as const satisfies readonly Version[]; /** Convert `http(s)://` to `ws(s)://`. Pass-through for `ws(s)://` URLs. */ function toWebSocketUrl(url: string | URL): string { const u = typeof url === "string" ? new URL(url) : url; let scheme: string; switch (u.protocol) { case "https:": case "wss:": scheme = "wss:"; break; case "http:": case "ws:": scheme = "ws:"; break; default: throw new Error(`Unsupported protocol: ${u.protocol}`); } return `${scheme}//${u.host}${u.pathname}${u.search}`; } /** Bare version ALPNs appended unless `requireProtocol` is set. Newest first. */ const BARE_ALPNS = ["qmux-02", "qmux-01", "qmux-00"] as const; /** Resolve a `protocols` + `versions` pair to the wire subprotocol list. * * Expansion rules per bare entry's `versions` value: single `Version` * emits one pair; an array emits one pair per element; `null` emits one * pair per [[QMUX_VERSIONS]] entry. Entries already in `{qmux-VV}.{alpn}` * pair form pass through. Unless `requireProtocol` is true, the bare version * ALPNs (`qmux-02`, `qmux-01`, `qmux-00`) are appended after the * prefixed pairs so a peer that doesn't pin an app protocol can still * negotiate a wire format. * * Throws if any bare entry has no matching `versions` mapping. */ export function resolveSubprotocols( protocols: readonly string[], versions: Readonly>, requireProtocol: boolean, ): string[] { const out: string[] = []; for (const entry of protocols) { const known = QMUX_VERSIONS.find((v) => entry.startsWith(versionPrefix(v))); if (known !== undefined) { out.push(entry); continue; } if (!(entry in versions)) { throw new Error( `Sec-WebSocket-Protocol entry ${JSON.stringify(entry)} has no qmux prefix and no versions mapping`, ); } const value = versions[entry]; const expanded: readonly Version[] = value === null ? QMUX_VERSIONS : Array.isArray(value) ? value : [value]; for (const v of expanded) { out.push(`${versionPrefix(v)}${entry}`); } } if (!requireProtocol) { out.push(...BARE_ALPNS); } return out; } /** Choose the `Sec-WebSocket-Protocol` value to accept from a client's offer. * * The server role performs the WebSocket handshake itself (`Deno.upgradeWebSocket`, * `ws`, `Bun.serve`, ...), so it - not this library - picks the subprotocol. This * is the server-side mirror of [[resolveSubprotocols]]: it expands the same * `protocols` + `versions` pair into the wire forms this session supports, in * preference order, and returns the first one the client offered. Pass the result * to the host's upgrade call, then hand the accepted socket to [[Session.accept]], * which derives the wire-format version from it. * * `offered` accepts the raw `Sec-WebSocket-Protocol` header (comma-separated) or * an already-split list. Returns `undefined` when nothing matches, which the * caller should turn into a failed upgrade rather than accepting the socket: * completing the handshake with no supported subprotocol is refused. * * Preference is ours, not the client's - the first entry in `protocols` that the * client also offered wins, matching the Rust `qmux::ws::Server`. * * @example * ```ts * const protocol = selectSubprotocol(req.headers.get("sec-websocket-protocol"), { * protocols: ["moq-transport-18"], * versions: { "moq-transport-18": null }, * }); * if (!protocol) return new Response("no supported protocol", { status: 400 }); * const { socket, response } = Deno.upgradeWebSocket(req, { protocol }); * ``` */ export function selectSubprotocol( offered: string | readonly string[] | null | undefined, options?: Pick, ): string | undefined { const wanted = typeof offered === "string" ? offered.split(",") : (offered ?? []); const client = new Set(wanted.map((p) => p.trim()).filter((p) => p !== "")); if (client.size === 0) return undefined; const ours = resolveSubprotocols( options?.protocols ?? [], options?.versions ?? {}, options?.requireProtocol ?? false, ); return ours.find((p) => client.has(p)); } /** Pick the QMux wire-format version from a negotiated subprotocol. */ function detectVersion(negotiated: string): WireFormat { for (const v of QMUX_VERSIONS) { if (negotiated === v || negotiated.startsWith(versionPrefix(v))) { return v; } } throw new Error(`Unsupported QMux subprotocol: ${JSON.stringify(negotiated)}`); } /** Strip the version prefix from a negotiated `Sec-WebSocket-Protocol` value. * * Returns the application protocol name, or `""` if only the bare version * ALPN was negotiated. Unsupported subprotocols are refused before parsing. */ function parseProtocol(raw: string, version: WireFormat): string { if (raw === version) return ""; const prefix = versionPrefix(version); return raw.startsWith(prefix) ? raw.slice(prefix.length) : ""; } /** A stream's halves, kept until each is done on the wire: the receive half once its * final size is known (FIN or RESET_STREAM received), the send half once its FIN * reached the socket or it was reset. Until then a late frame still finds the state * that accounts for it. */ interface StreamState { send?: SendHalf; /** The writable's controller, so STOP_SENDING and a closing session can error it. */ writable?: WritableStreamDefaultController; recv?: RecvStream; /** Runs once both halves are done, returning a peer stream's slot once the application has it too. */ onClose?: () => void; } /** A terminal transition, with the close frame that tells the peer, if any. A clean * end fulfills `closed` with its code and reason, and `send` puts them on the wire * as an APPLICATION_CLOSE. An abort rejects `closed` with `cause`, and `send` tells * the peer why with a CONNECTION_CLOSE. */ type End = | { clean: true; code: number; reason: string; send: boolean } | { clean: false; cause: Error; send?: { code: number; reason: string } }; /** A `WebTransport` session carried over a WebSocket, for hosts without native WebTransport. */ export class Session implements WebTransport { /** The transport label MoQ reports, telling this session apart from native WebTransport. */ readonly transport = "websocket"; // The transport: a native `WebSocketStream` when the platform has one, // otherwise the `WebSocketStream` ponyfill over a plain `WebSocket`. Either // way, one API. #wss?: WebSocketStreamLike; #scheduler?: SendScheduler; // Counts the send backlog of any transport but the ponyfill, which counts its own. #backlog?: BacklogSink; #sendBufferSize: number; // The stream-id role: false dials (client), true accepts (server). Set by // [[Session.accept]]; every id we mint and every id we allow the peer to mint // keys off it. #isServer = false; // [[AcceptOptions.protocol]]: stands in for `socket.protocol` when the host // doesn't expose the negotiated subprotocol. #protocolOverride?: string; // `SessionOptions.requireProtocol` on a dial: the server must pick one of // our application protocols, not answer with none. #requireProtocol = false; // Set once closed, and never changed after: the error later calls throw. #closed?: Error; #streams = new Map(); // Streams whose MAX_STREAM_DATA is owed, sent with the newest limit when the scheduler polls. #updates = new Set(); #nextUniStreamId = 0n; #nextBiStreamId = 0n; // Used only after the negotiated subprotocol has been validated. #version: WireFormat = "qmux-02"; #protocol = ""; /** The negotiated application-level subprotocol, or empty string if none. * * The prefix is stripped; this returns only the application protocol name. */ get protocol(): string { return this.#protocol; } /** Resolves once the peer's transport parameters arrive, as a WebTransport handshake completes: * stream limits and `datagrams.maxDatagramSize` are known from then on. */ readonly ready: Promise; #readyResolve: () => void; #readyReject: (err: Error) => void; /** Resolves with the close code and reason on a clean close, or rejects with a {@link SessionError}. */ readonly closed: Promise; #closedResolve: (info: WebTransportCloseInfo) => void; #closedReject: (err: Error) => void; /** Bidirectional streams the peer opens, in arrival order. */ readonly incomingBidirectionalStreams: ReadableStream; #incomingBidirectionalQueue: IncomingStreamQueue; /** Unidirectional streams the peer opens, in arrival order. */ readonly incomingUnidirectionalStreams: ReadableStream>; #incomingUnidirectionalQueue: IncomingStreamQueue>; readonly #datagrams = makeDatagrams((data) => this.#sendDatagram(data)); /** Unreliable datagrams sent and received as QMux DATAGRAM frames. */ get datagrams(): WebTransportDatagramDuplexStream { return this.#datagrams; } // Flow control state #config: Required; #ourParams: TransportParams; #peerParams: TransportParams = { ...DEFAULT_TRANSPORT_PARAMS }; #paramsReceived = false; // Settles once the peer's stream limits are known (or the session ends), so a // create that refuses to wait judges the peer's real limit, not the zero placeholder. #paramsSettled = Promise.withResolvers(); // Peer credit is unavailable until its transport parameters arrive. #connCredit = new Credit(0n); // The connection receive window (MAX_DATA), which every peer byte charges. #recvData: Window; #recvOpenBi = new RecvOpen(); #recvOpenUni = new RecvOpen(); // Stream counts start at zero until the peer grants credit. #bidiStreamCredit = new Credit(0n); #uniStreamCredit = new Credit(0n); // The streams the peer may open (MAX_STREAMS). #recvBiLimit: StreamLimit; #recvUniLimit: StreamLimit; // QMux01 idle-timeout tracking (engaged once we've received the peer's params). #lastRecvAt = now(); #lastSendAt = now(); // Deadline bookkeeping for #idleActivityAt: the newest receive observed, the // send last allowed to restart the deadline, and whether a send may restart it. #recvSeen = Instant.ZERO; #sendResetAt = Instant.ZERO; #sendCredit = true; #nextPingSeq = 0; // Highest sequence seen in a received QX_PING request (draft-02 requires them // to strictly increase). Undefined until the first request arrives. #lastPingRecv?: bigint; #idleTimer?: Interval; /** Open a QMux session as the **client**, dialing `url`. * * The polyfill constructs the underlying `WebSocket` itself. Pass the * application-level ALPNs in `options.protocols` plus a `versions` * map saying which QMux wire-format version each bare ALPN rides on. The * wire form `{qmux-VV}.{alpn}` is built automatically; entries already in * pair form (e.g. `"qmux-00.moq-transport-18"`) pass through unchanged. * * Once the handshake completes, the QMux wire-format version is derived * from the negotiated `Sec-WebSocket-Protocol`. `.protocol` exposes the * application protocol with the QMux prefix stripped. * * Pass an already-connected `WebSocket` (or `WebSocketStream`) instead of a * URL to run the client role over a socket you opened yourself - the * subprotocol was chosen when you created it, so `options.protocols` and * `options.versions` are ignored. See [[Session.accept]] for the server role. */ constructor(source: string | URL | WebSocketLike | WebSocketStreamLike, options?: SessionOptions) { if (options?.requireUnreliable) { throw new Error("not allowed to use WebSocket; requireUnreliable is true"); } // Pinning can't be honored over WebSocket, and connecting anyway would // silently drop the authentication the caller asked for. if (options?.serverCertificateHashes?.length) { throw new Error("not allowed to use WebSocket; serverCertificateHashes is not supported"); } const dial = typeof source === "string" || source instanceof URL; // Resolve before any other setup so a bad protocols/versions pairing throws // from the constructor rather than failing the handshake later. const subprotocols = dial ? resolveSubprotocols(options?.protocols ?? [], options?.versions ?? {}, options?.requireProtocol ?? false) : []; this.#config = resolveConfig(options?.config); this.#requireProtocol = dial && (options?.requireProtocol ?? false); this.#ourParams = configToTransportParams(this.#config); this.#sendBufferSize = sendBufferSize(options?.sendBufferSize ?? DEFAULT_SEND_BUFFER_SIZE); // Receive limits are version-independent. const notify = () => this.#scheduler?.notify(); this.#recvData = new Window(this.#ourParams.initialMaxData, notify); this.#recvBiLimit = new StreamLimit(this.#config.maxStreams, notify); this.#recvUniLimit = new StreamLimit(this.#config.maxStreams, notify); const ready = Promise.withResolvers(); this.ready = ready.promise; this.#readyResolve = ready.resolve; this.#readyReject = ready.reject; // Avoid an unhandled rejection if `ready` is rejected (early close) before // the caller attaches a handler; real awaiters still observe the rejection. this.ready.catch(() => {}); const closed = Promise.withResolvers(); this.closed = closed.promise; this.#closedResolve = closed.resolve; this.#closedReject = closed.reject; // Same guard as `ready`: an abnormal close rejects `closed`, and a consumer // that only ever calls close() never attaches a handler. Real awaiters still // observe the rejection. this.closed.catch(() => {}); this.#incomingBidirectionalQueue = new IncomingStreamQueue(); this.incomingBidirectionalStreams = this.#incomingBidirectionalQueue.readable; this.#incomingUnidirectionalQueue = new IncomingStreamQueue>(); this.incomingUnidirectionalStreams = this.#incomingUnidirectionalQueue.readable; this.#attach( dial ? // Open the transport via `WebSocketStream` - native when present, else // the ponyfill over a plain `WebSocket`. One code path for both, so the // path exercised in tests is the one Chromium runs natively. openWebSocketStream(toWebSocketUrl(source as string | URL), { protocols: subprotocols, highWaterMark: this.#sendBufferSize, }) : toWebSocketStream(source as WebSocketLike | WebSocketStreamLike, this.#sendBufferSize), ); } /** Open a QMux session as the **server**, over a socket you have already * accepted from an HTTP upgrade. * * The host performs the WebSocket handshake (`Deno.upgradeWebSocket`, `ws`, * ...), so by the time you get here the subprotocol is already negotiated: * the wire-format version and `.protocol` are read off the socket rather than * advertised. Use [[selectSubprotocol]] to pick that value during the upgrade. * * The returned session is a `WebTransport`, identical to a client session * apart from the stream-id role - so it accepts peer-initiated streams and * opens server-initiated ones. * * Cap the host's message size at one record where it allows it, as `ws`'s * `maxPayload` does: the larger of `config.maxRecordSize` and 16384, draft-00's * frame limit. The session refuses a larger message, but only once it is buffered. * * @example * ```ts * const { socket, response } = Deno.upgradeWebSocket(req, { protocol }); * const session = Session.accept(socket, { config }); * await session.ready; * ``` */ static accept(socket: WebSocketLike | WebSocketStreamLike, options?: AcceptOptions): Session { const session = new Session(socket, options); // Applied after construction, which is safe because both transports settle // `opened` asynchronously: #startSession, every stream id, and every inbound // frame are interpreted strictly later than this. session.#isServer = true; session.#protocolOverride = options?.protocol; return session; } /** Drive the session off an opened transport, whichever way we got it. */ #attach(wss: WebSocketStreamLike) { this.#wss = wss; wss.opened.then( (conn) => { // The session may have been closed before the socket finished opening. if (this.#closed) return; try { const protocol = this.#protocolOverride ?? conn.protocol; // Strict application negotiation also refuses a bare QMux version. if (this.#requireProtocol && parseProtocol(protocol, detectVersion(protocol)) === "") { this.#end({ clean: false, cause: new Error(`server negotiated no application protocol (${JSON.stringify(protocol)})`), }); return; } // Only the ponyfill's `desiredSize` measures bytes; the native API's counts // writes, so it would read as backpressured with any write in flight. let sink: SendSink; if (wss instanceof WebSocketStream) sink = new WritableStreamSink(conn.writable); else sink = this.#backlog = new BacklogSink(conn.writable, this.#sendBufferSize); this.#startSession(protocol, sink); void this.#readLoop(conn.readable.getReader()); } catch (error) { this.#end({ clean: false, cause: toError(error, "Invalid QMux subprotocol") }); } }, (err: unknown) => { this.#end({ clean: false, cause: toError(err, "WebSocketStream failed to open") }); }, ); wss.closed.then( (info) => { // The socket went away without a CONNECTION_CLOSE. A peer close or a // local close() would already have transitioned us (and #end is // idempotent), so reaching here open means the session dropped - // even if the WebSocket itself closed with a "clean" status code. this.#end({ clean: false, cause: new Error(`Connection closed: ${info.closeCode ?? 0} ${info.reason ?? ""}`), }); }, (err: unknown) => { // Keep the socket failure itself - it becomes the SessionError's cause, and // it's the only description of *why* the transport died. this.#end({ clean: false, cause: toError(err, "WebSocketStream closed") }); }, ); } async #readLoop(reader: ReadableStreamDefaultReader) { try { while (true) { const { value, done } = await reader.read(); if (done) break; // QMux is binary-only; a text frame is a protocol error, not something // to silently drop (which would desync the session). if (typeof value === "string") { const reason = "text frames are not valid for QMux"; this.#end({ clean: false, cause: new Error(reason), send: { code: TransportCode.PROTOCOL_VIOLATION, reason }, }); return; } // `openWebSocketStream` normalizes the native API's ArrayBuffer chunks, // but a transport handed straight to the constructor or [[accept]] // hasn't been through it - and Chromium's WebSocketStream yields // ArrayBuffer. Normalize here so every inbound path reaches the decoder // as a Uint8Array. this.#onData(value instanceof ArrayBuffer ? new Uint8Array(value) : value); } } catch (err) { this.#end({ clean: false, cause: toError(err, "WebSocketStream read error") }); } } /** Derive the wire-format version, start the send scheduler, and (for QMux * drafts) exchange transport parameters. Shared by both transports. */ #startSession(rawProtocol: string, sink: SendSink) { const version = detectVersion(rawProtocol); this.#version = version; this.#protocol = parseProtocol(rawProtocol, version); // Datagrams rely on the record layer for framing, so don't advertise the // parameter - or accept datagrams - on any non-record wire format. The recv // path gates on #ourParams.maxDatagramFrameSize. RESET_STREAM_AT is only // permitted on draft-02, so advertise `reset_stream_at` there and nowhere // else; the recv path gates on #ourParams.resetStreamAt. this.#ourParams = { ...this.#ourParams, maxDatagramFrameSize: usesRecords(version) ? this.#ourParams.maxDatagramFrameSize : 0n, resetStreamAt: version === "qmux-02", }; // QMux01 over WebSocket uses the WS message boundary as the implicit record // boundary; no extra size prefix is required. const params = Frame.encode({ type: "transport_parameters", params: this.#ourParams }, this.#version); this.#validateRecordSize(params); this.#scheduler = new SendScheduler(sink, { first: params, onActivity: () => { this.#lastSendAt = now(); }, // A failed write leaves the session unable to send anything, even if the // socket hasn't reported closing yet. onFail: (err) => { this.#end({ clean: false, cause: err }); }, pending: () => this.#nextUpdate(), }); // Exchange transport parameters before granting send credit. this.#connCredit.close(); this.#bidiStreamCredit.close(); this.#uniStreamCredit.close(); this.#connCredit = new Credit(0n); this.#bidiStreamCredit = new Credit(0n); this.#uniStreamCredit = new Credit(0n); // Our own idle deadline applies until the peer's parameters arrive. this.#startIdleTimerIfEnabled(); // The handshake deadline also covers qmux-00 and a disabled idle timeout, so // a peer that never sends its parameters can't hold `ready` forever. const handshake = this.#config.handshakeTimeout; if (handshake !== null) { timeout(handshake, this.ready).catch((err) => { if (!(err instanceof Elapsed)) return; this.#end({ clean: false, cause: new Error("handshake timeout") }); }); } } #onData(data: Uint8Array) { this.#lastRecvAt = now(); // The WebSocket binding makes an empty message a no-op on every version, unlike an // empty record, as Rust's transport does. if (data.byteLength === 0) return; try { if (usesRecords(this.#version)) { if (BigInt(data.byteLength) > this.#ourParams.maxRecordSize) { throw new TransportError( TransportCode.FRAME_ENCODING_ERROR, `record exceeds our max_record_size (${data.byteLength} > ${this.#ourParams.maxRecordSize})`, ); } // Record-framed drafts: each WS message is a record with one or more frames const frames = Frame.decodeRecord(data); for (const frame of frames) { this.#recvFrame(frame); } } else { // draft-00 §5.2: `max_frame_size` bounds the whole frame, header // included, and may only be raised from its initial value - which we // never do, so the initial value is what a peer may send. Each message // is one frame here. if (this.#version === "qmux-00" && data.byteLength > Frame.MAX_FRAME_SIZE) { throw new TransportError( TransportCode.FRAME_ENCODING_ERROR, `frame exceeds max_frame_size (${data.byteLength} > ${Frame.MAX_FRAME_SIZE})`, ); } const frame = Frame.decode(data, this.#version); if (frame !== null) { this.#recvFrame(frame); } } } catch (error) { // A decode failure or a frame that violates a negotiated limit is fatal, closing // with the QUIC transport error code the violation carries. console.error("Protocol violation:", error); this.#end({ clean: false, cause: toError(error, "Protocol violation"), send: { code: transportCode(error), reason: "Protocol violation" }, }); } } #recvFrame(frame: Frame.Any) { // Draft-02: QX_TRANSPORT_PARAMETERS MUST be the first frame, and only the // first. A non-params frame before params, or a second params frame, is a // PROTOCOL_VIOLATION. (decodeRecord drops leading PADDING before we get here.) if (this.#version === "qmux-02") { const isParams = frame.type === "transport_parameters"; if (isParams === this.#paramsReceived) { throw new Error("QX_TRANSPORT_PARAMETERS must be the first frame"); } } if (frame.type === "stream") { this.#handleStreamFrame(frame); } else if (frame.type === "reset_stream") { this.#handleResetStream(frame); } else if (frame.type === "stop_sending") { this.#handleStopSending(frame); } else if (frame.type === "application_close" || frame.type === "connection_close") { if (frame.type === "application_close") { // APPLICATION_CLOSE (0x1d): the peer closed the session deliberately - // graceful, so `closed` fulfills with its code/reason. this.#end({ clean: true, code: Number(frame.code.value), reason: frame.reason, send: false }); } else { // CONNECTION_CLOSE (0x1c): the peer hit a protocol violation or // transport error, so `closed` rejects. A termination with *no* close // frame at all is a drop, which the socket's `closed` handles. this.#end({ clean: false, cause: new Error(`Connection closed: ${frame.code.value} ${frame.reason}`) }); } } else if (frame.type === "transport_parameters") { this.#handleTransportParameters(frame.params); } else if (frame.type === "max_data") { this.#connCredit.increaseMax(frame.max); } else if (frame.type === "max_stream_data") { this.#sendState(frame.id)?.send?.credit.increaseMax(frame.max); } else if (frame.type === "max_streams_bidi") { this.#bidiStreamCredit.increaseMax(frame.max); } else if (frame.type === "max_streams_uni") { this.#uniStreamCredit.increaseMax(frame.max); } else if (frame.type === "datagram") { // `max_datagram_frame_size` is negotiated: we advertised the largest // DATAGRAM frame we're willing to receive, so a peer that sends one we // never accepted - or one larger than we advertised - has violated the // contract. Per RFC 9221 that's a fatal PROTOCOL_VIOLATION, not a // droppable frame; throwing here closes the session via #onData (matching // the Rust implementation's DatagramsUnsupported / FrameTooLarge). // // The limit bounds the whole frame, whose size depends on the wire form: // the no-length `0x30` form is just a type byte plus payload, while `0x31` // adds a length varint. The decoder records which arrived so we can size // it exactly. if (this.#ourParams.maxDatagramFrameSize === 0n) { throw new Error("received a DATAGRAM but did not advertise datagram support"); } const len = frame.data.byteLength; const header = frame.lengthPrefixed === false ? 1 : 1 + VarInt.from(len).size(); const frameSize = BigInt(header + len); if (frameSize > this.#ourParams.maxDatagramFrameSize) { throw new Error("received a DATAGRAM larger than our advertised max_datagram_frame_size"); } pushDatagram(this.#datagrams, frame.data); } else if (frame.type === "ping_request") { // Draft-02: request sequence numbers must strictly increase. if (this.#version === "qmux-02") { if (this.#lastPingRecv !== undefined && frame.sequence <= this.#lastPingRecv) { throw new Error("QX_PING request sequence must strictly increase"); } this.#lastPingRecv = frame.sequence; } // Respond to ping requests this.#sendPriorityFrame({ type: "ping_response", sequence: frame.sequence }); } else if (frame.type === "ping_response") { // Draft-02: a response must echo a sequence we actually sent (0..nextPingSeq). if (this.#version === "qmux-02" && frame.sequence >= BigInt(this.#nextPingSeq)) { throw new Error("QX_PING response echoed a sequence we never sent"); } } else if ( frame.type === "data_blocked" || frame.type === "stream_data_blocked" || frame.type === "streams_blocked_bidi" || frame.type === "streams_blocked_uni" ) { // Informational, no action needed } } #handleTransportParameters(params: TransportParams) { if (this.#paramsReceived) return; // Record-framed drafts: an advertised max_record_size MUST NOT go below the // default minimum. Omitted values decode to the default, so only an explicit // smaller value trips this (TRANSPORT_PARAMETER_ERROR). if (usesRecords(this.#version) && params.maxRecordSize < Frame.DEFAULT_MAX_RECORD_SIZE) { throw new TransportError( TransportCode.TRANSPORT_PARAMETER_ERROR, "max_record_size below the default minimum", ); } this.#paramsReceived = true; this.#peerParams = params; this.#paramsSettled.resolve(); this.#connCredit.increaseMax(params.initialMaxData); this.#bidiStreamCredit.increaseMax(params.initialMaxStreamsBidi); this.#uniStreamCredit.increaseMax(params.initialMaxStreamsUni); // Resolve the datagram send limit. Datagrams are a QMux01-only feature, so // they stay disabled on any other wire format. Otherwise whether we may // *send* depends solely on the peer's willingness to receive (RFC 9221): // 0 means unsupported. if (usesRecords(this.#version) && params.maxDatagramFrameSize > 0n) { // A datagram must fit in one record, so the frame is capped by the // smaller of the peer's datagram-frame limit and its record size. const cap = // biome-ignore lint/complexity/useMathMinMax: bigint operands; Math.min/max throw on bigint. params.maxRecordSize < params.maxDatagramFrameSize ? params.maxRecordSize : params.maxDatagramFrameSize; // We encode the length-prefixed form (0x31): one type byte plus a length // varint sized for `cap`. Subtracting it keeps the frame within the limit. const overhead = BigInt(1 + VarInt.from(cap).size()); const payload = cap > overhead ? cap - overhead : 0n; setMaxDatagramSize(this.#datagrams, Number(payload)); } // Credit streams created before params arrived. Only qmux-02 requires the // params first, so an earlier draft's peer may already have opened streams: // the peer's bidi_local limits its own bidi streams, bidi_remote ours. for (const [streamIdVal, stream] of this.#streams) { if (!stream.send) continue; const id = new Stream.Id(VarInt.from(streamIdVal)); let sendLimit = params.initialMaxStreamDataUni; if (id.dir === Stream.Dir.Bi) { sendLimit = this.#isPeerStream(id) ? params.initialMaxStreamDataBidiLocal : params.initialMaxStreamDataBidiRemote; } stream.send.credit.increaseMax(sendLimit); } // The peer's limit may be shorter than ours. this.#startIdleTimerIfEnabled(); this.#readyResolve(); } /** Effective idle timeout in ms, or 0 if disabled. * * Per RFC 9000 §10.1, the effective value is `min(our, peer)` of the non-zero advertised values * (or the single non-zero one). If both are zero, idle timeouts are disabled. */ #effectiveIdleTimeoutMs(): bigint { if (!usesRecords(this.#version)) return 0n; const a = this.#ourParams.maxIdleTimeout; const b = this.#peerParams.maxIdleTimeout; if (a === 0n && b === 0n) return 0n; if (a === 0n) return b; if (b === 0n) return a; // biome-ignore lint/complexity/useMathMinMax: bigint operands; Math.min/max throw on bigint. return a < b ? a : b; } #startIdleTimerIfEnabled() { this.#idleTimer?.close(); this.#idleTimer = undefined; const timeoutMs = this.#effectiveIdleTimeoutMs(); if (timeoutMs === 0n) return; // Poll at a fraction of the timeout - frequent enough to trigger pings on time // but not so frequent it burns CPU on otherwise-quiet sessions. const timeout = Duration.millis(Number(timeoutMs)); const timer = interval(Duration.millis(Math.max(50, Number(timeoutMs) / 6))); timer.setMissedTickBehavior(MissedTickBehavior.Delay); this.#idleTimer = timer; void this.#idleLoop(timer, timeout); } async #idleLoop(timer: Interval, timeout: Duration) { // The first tick is immediate; the first check belongs one period in. let first = true; for (;;) { try { await timer.tick(); } catch { return; // #end closed the timer. } if (this.#closed) { timer.close(); return; } if (!first) this.#idleTick(timeout); first = false; } } /** * Newest activity that counts toward the idle deadline. * * A received frame always restarts the timer: it is the only direct proof the * peer is still there. A send restarts it too, but at most once per receive * (RFC 9000 §10.1). That proviso is what keeps the deadline reachable: our own * keep-alive pings advance `#lastSendAt`, so counting every send would let them * restart the very deadline they exist to test, and a peer that goes silent * while its socket still accepts our writes would never be reclaimed. * * Crediting the first send after each receive is what still lets a mostly * one-way sender stay open - its peer answers the keep-alive, and each answer * re-arms the credit. */ #idleActivityAt(): Instant { if (this.#lastRecvAt.gt(this.#recvSeen)) { this.#recvSeen = this.#lastRecvAt; this.#sendCredit = true; } if (this.#sendCredit && this.#lastSendAt.gt(this.#sendResetAt)) { this.#sendResetAt = this.#lastSendAt; this.#sendCredit = false; } return this.#recvSeen.max(this.#sendResetAt); } #idleTick(timeout: Duration) { const at = now(); if (at.since(this.#idleActivityAt()).gt(timeout)) { // No frames have been sent or received within the negotiated limit. Abnormal: // without a rejection this is indistinguishable from a graceful close(), which // also settles with closeCode 0. this.#end({ clean: false, cause: new Error("idle timeout") }); return; } // Keep-alive: nudge the peer when our outbound side has been silent for a third // of the timeout. Any frame counts as activity, so this only fires when truly idle. // Nothing to keep alive before the peer has spoken at all. if (this.#paramsReceived && at.since(this.#lastSendAt).gt(timeout.div(3))) { const seq = this.#nextPingSeq; // Monotonic (never wraps within a session's life): the draft-02 // strictly-increasing rule requires it, and it must not wrap earlier // than the Rust peer's u64 counter or a valid ping would be rejected. this.#nextPingSeq += 1; try { this.#sendPriorityFrame({ type: "ping_request", sequence: BigInt(seq) }); } catch (e) { // Best effort - if the send fails, the close path will fire shortly. // Log a breadcrumb so a never-fire encoder bug doesn't vanish silently. console.warn("qmux: keep-alive ping failed", e); } } } /** Encode the next window update owed to the peer, or undefined once none is. * The scheduler polls this as it writes, so each carries the newest limit. */ #nextUpdate(): Uint8Array | undefined { let frame: Frame.Any | undefined; if (this.#recvData.takePending()) { frame = { type: "max_data", max: this.#recvData.max }; } else if (this.#recvBiLimit.takePending()) { frame = { type: "max_streams_bidi", max: this.#recvBiLimit.max }; } else if (this.#recvUniLimit.takePending()) { frame = { type: "max_streams_uni", max: this.#recvUniLimit.max }; } else { for (const streamId of this.#updates) { this.#updates.delete(streamId); const recv = this.#streams.get(streamId)?.recv; // Moot once the peer sent its last byte or we stopped reading. if (!recv?.wantsCredit || !recv.window.takePending()) continue; frame = { type: "max_stream_data", id: new Stream.Id(VarInt.from(streamId)), max: recv.window.max }; break; } } if (!frame) return undefined; const bytes = Frame.encode(frame, this.#version); this.#validateRecordSize(bytes); return bytes; } #isPeerStream(id: Stream.Id): boolean { return id.serverInitiated !== this.#isServer; } #recvOpen(dir: Stream.DirType): RecvOpen { return dir === Stream.Dir.Bi ? this.#recvOpenBi : this.#recvOpenUni; } #recvLimit(dir: Stream.DirType): StreamLimit { return dir === Stream.Dir.Bi ? this.#recvBiLimit : this.#recvUniLimit; } /** A receive half charging the connection window, with a stream window of `size`. */ #recvHalf(id: Stream.Id, size: bigint): RecvStream { const streamId = id.value.value; return new RecvStream({ conn: this.#recvData, window: new Window(size, () => { this.#updates.add(streamId); this.#scheduler?.notify(); }), stop: (reason) => { this.#sendPriorityFrame({ type: "stop_sending", id, code: VarInt.from(resetCode(reason)) }); }, }); } /** Forget a stream once both its halves are done on the wire. */ #reap(streamId: bigint) { const stream = this.#streams.get(streamId); if (!stream) return; if (stream.send && !stream.send.terminal) return; if (stream.recv && !stream.recv.sizeKnown) return; this.#streams.delete(streamId); this.#updates.delete(streamId); stream.onClose?.(); } /** Open a peer stream on its first STREAM frame, implicitly opening every lower index. */ #openPeerStream(id: Stream.Id): StreamState & { recv: RecvStream } { // Per QUIC RFC 9000 §4.6, the limit applies to the stream index. const limit = this.#recvLimit(id.dir); if (!limit.open(id.index)) throw new TransportError(TransportCode.STREAM_LIMIT_ERROR, "stream limit exceeded"); this.#recvOpen(id.dir).record(id.index); const bidi = id.dir === Stream.Dir.Bi; const recv = this.#recvHalf( id, bidi ? this.#ourParams.initialMaxStreamDataBidiRemote : this.#ourParams.initialMaxStreamDataUni, ); // Its slot returns once the application has the stream and both halves are done, // as in QUIC, so it bounds the streams a peer holds open. let holds = 2; const stream = { recv, // The peer's bidi_local limits what we send on its bidi streams. send: bidi ? new SendHalf(this.#peerParams.initialMaxStreamDataBidiLocal) : undefined, onClose: () => { if (--holds === 0) limit.close(); }, }; this.#streams.set(id.value.value, stream); return stream; } /** Hand a newly opened peer stream to the application. */ #announce(id: Stream.Id, stream: StreamState & { recv: RecvStream }) { // Taking the stream is the slot's other hold, counted by the same closure as onClose. const accept = stream.onClose as () => void; // A refused stream stays registered until its FIN or RESET, so in-flight frames // cannot reopen it, and discards what they carry. The application will never // take it, so it releases that hold and resets a bidi stream's send half, and // the slot returns once the peer's half is done too. const drop = (err: Error) => { stream.recv.stop(err); accept(); if (stream.send) this.#resetSend(id, stream, err, VarInt.from(resetCode(err))); else this.#reap(id.value.value); }; const refused = () => drop(new Error("incoming stream acceptor cancelled")); if (stream.send) { const writable = this.#sendWritable(id, stream, stream.send, DEFAULT_SEND_ORDER); const bidi = { readable: stream.recv.readable, writable }; if (!this.#incomingBidirectionalQueue.push(bidi, accept, drop)) refused(); } else if (!this.#incomingUnidirectionalQueue.push(stream.recv.readable, accept, drop)) { refused(); } } #handleStreamFrame(frame: Frame.Data) { // The read loop can still deliver frames after #end() has torn down the // incoming-stream controllers and the streams; drop them, matching the // #sendDatagram/#sendPriorityFrame post-close guards. if (this.#closed) return; const id = frame.id; const streamId = id.value.value; if (!id.canRecv(this.#isServer)) { throw new TransportError(TransportCode.STREAM_STATE_ERROR, "Invalid stream ID direction"); } const recv = this.#streams.get(streamId)?.recv; if (recv) { recv.data(frame.offset, frame.data, frame.fin); if (frame.fin) this.#reap(streamId); return; } if (!this.#isPeerStream(id)) { // One of ours whose receive half already ended: a late frame, dropped. // One we never opened is malformed (canRecv leaves only bidi here). if (id.index >= this.#nextBiStreamId) throw new TransportError(TransportCode.STREAM_STATE_ERROR, "STREAM frame for a stream we never opened"); return; } // A peer stream whose receive half already ended stays closed. if (this.#recvOpen(id.dir).isClosed(id.index)) return; const stream = this.#openPeerStream(id); // Charge the frame before the application sees the stream, so one that breaks // flow control never reaches it. stream.recv.data(frame.offset, frame.data, frame.fin); this.#announce(id, stream); if (frame.fin) this.#reap(streamId); } #handleResetStream(frame: Frame.ResetStream) { // A RESET_STREAM_AT frame (reliableSize present, draft-02) is only legal if // we advertised the `reset_stream_at` transport parameter. Receiving it // otherwise - or on an earlier draft, which never advertises it - is a // FRAME_ENCODING_ERROR. Plain RESET_STREAM is always allowed. if (frame.reliableSize !== undefined && !this.#ourParams.resetStreamAt) { throw new TransportError( TransportCode.FRAME_ENCODING_ERROR, "RESET_STREAM_AT received without advertising reset_stream_at", ); } const id = frame.id; if (!id.canRecv(this.#isServer)) { throw new TransportError(TransportCode.STREAM_STATE_ERROR, "Invalid stream ID direction"); } if (this.#closed) return; const streamId = id.value.value; const err = new StreamError(streamCode(frame.code.value), "RESET_STREAM"); const recv = this.#streams.get(streamId)?.recv; if (recv) { recv.reset(err, frame.finalSize, frame.reliableSize); this.#reap(streamId); return; } if (!this.#isPeerStream(id)) { // One of ours whose receive half already ended, unless we never opened it. const opened = id.dir === Stream.Dir.Bi ? this.#nextBiStreamId : this.#nextUniStreamId; if (id.index >= opened) throw new TransportError(TransportCode.STREAM_STATE_ERROR, "RESET_STREAM for a stream we never opened"); return; } // A terminal peer stream stays terminal, so a duplicate RESET can't charge its final size twice. if (this.#recvOpen(id.dir).isClosed(id.index)) return; // A reset as the stream's first frame opens and closes it at once, and the // application never sees it: charge its final size and return its slot. const limit = this.#recvLimit(id.dir); if (!limit.open(id.index)) throw new TransportError(TransportCode.STREAM_LIMIT_ERROR, "stream limit exceeded"); this.#recvOpen(id.dir).record(id.index); const size = id.dir === Stream.Dir.Bi ? this.#ourParams.initialMaxStreamDataBidiRemote : this.#ourParams.initialMaxStreamDataUni; this.#recvHalf(id, size).reset(err, frame.finalSize, frame.reliableSize); // Nobody will write our half of a bidi stream, so end it for the peer's reader. if (id.dir === Stream.Dir.Bi) { this.#sendPriorityFrame({ type: "reset_stream", id, code: VarInt.from(0), finalSize: 0n }); } limit.close(); } /** The stream a MAX_STREAM_DATA or STOP_SENDING names. As in QUIC, either can be * the first frame of a peer's bidi stream, and opens it like a STREAM frame. */ #sendState(id: Stream.Id): StreamState | undefined { if (this.#closed) return undefined; const stream = this.#streams.get(id.value.value); if (stream) return stream; if (!this.#isPeerStream(id) || id.dir !== Stream.Dir.Bi) return undefined; if (this.#recvOpen(id.dir).isClosed(id.index)) return undefined; const opened = this.#openPeerStream(id); this.#announce(id, opened); return opened; } #handleStopSending(frame: Frame.StopSending) { const stream = this.#sendState(frame.id); if (!stream?.send) return; const stopped = new StreamError(streamCode(frame.code.value), "STOP_SENDING"); this.#resetSend(frame.id, stream, stopped, frame.code); } /** Reset a stream's send half, unless it already ended: fail its writable and its * queued frame, and send RESET_STREAM with every byte that took credit. */ #resetSend(id: Stream.Id, stream: StreamState, reason: Error, code: VarInt) { const finalSize = stream.send?.reset(reason); if (finalSize === undefined) return; const streamId = id.value.value; try { stream.writable?.error(reason); } catch {} this.#scheduler?.dropStream(streamId, reason); this.#sendPriorityFrame({ type: "reset_stream", id, code, finalSize }); this.#reap(streamId); } /** The largest STREAM frame the peer accepts, in bytes. * * Record-framed drafts negotiate it: a frame rides in one record, so the * peer's `max_record_size` is the limit (the draft-01 default until its * TRANSPORT_PARAMETERS arrive, so we never send something it would reject). * Draft-00 has no record layer, * so draft-00's whole-frame `max_frame_size` stands in. */ #sendFrameBudget(): bigint { if (!usesRecords(this.#version)) return BigInt(Frame.MAX_FRAME_SIZE); return this.#paramsReceived ? this.#peerParams.maxRecordSize : Frame.DEFAULT_MAX_RECORD_SIZE; } /** The largest payload we may send in one STREAM frame at `offset`. * * This respects the peer's frame budget and the send-only compatibility * ceiling for released receivers. A `bigint`: the peer's `max_record_size` is * a varint, so it can exceed what `number` holds exactly. Callers clamp it to * the bytes they actually have before converting. */ #maxStreamPayload(id: Stream.Id, offset: bigint): bigint { const peerMax = Frame.maxStreamPayload(this.#version, this.#sendFrameBudget(), id, offset); const compatibilityMax = BigInt(Frame.MAX_FRAME_PAYLOAD); // biome-ignore lint/complexity/useMathMinMax: bigint operands; Math.min/max throw on bigint. const max = peerMax < compatibilityMax ? peerMax : compatibilityMax; // Unreachable with a conforming peer: max_record_size is validated against // the draft-01 minimum on arrival. Guard anyway - a zero budget would make // the chunking loops below spin forever instead of failing. if (max === 0n) throw new Error("peer frame limit leaves no room for stream data"); return max; } /** Validate an encoded record against the peer's max_record_size (QMux01+). */ #validateRecordSize(bytes: Uint8Array) { if (usesRecords(this.#version)) { // Before the peer's TRANSPORT_PARAMETERS arrive, use the draft-01 default // (16382) so we don't accidentally send something the peer will reject. const limit = this.#paramsReceived ? this.#peerParams.maxRecordSize : Frame.DEFAULT_MAX_RECORD_SIZE; if (BigInt(bytes.byteLength) > limit) { throw new Error(`record exceeds peer max_record_size (${bytes.byteLength} > ${limit})`); } } } /** Encode and enqueue a stream-data/fin frame, resolving once it hits the wire. * Refuses once `signal` aborts: its listener drops only what is already queued. */ async #enqueueStreamFrame(streamId: bigint, frame: Frame.Data, signal?: AbortSignal) { signal?.throwIfAborted(); const scheduler = this.#scheduler; if (!scheduler) throw this.#closed ?? new Error("session not open"); const bytes = Frame.encode(frame, this.#version); this.#validateRecordSize(bytes); await scheduler.enqueueStream(streamId, bytes); } async #sendStreamData( id: Stream.Id, send: SendHalf, data: Uint8Array, signal: AbortSignal, stats: SendStreamStats, ) { const streamId = id.value.value; stats.bytesWritten += data.byteLength; for (let offset = 0; offset < data.byteLength; ) { const remaining = BigInt(data.byteLength - offset); // Size from the peer's frame budget and this frame's actual header, then // apply the compatibility ceiling for released receivers. const start = send.offset; const payloadMax = this.#maxStreamPayload(id, start); // biome-ignore lint/complexity/useMathMinMax: bigint operands; Math.min/max throw on bigint. const chunkMax = payloadMax < remaining ? payloadMax : remaining; const sendable = Number(await send.claim(chunkMax, this.#connCredit, signal)); // A STOP_SENDING may have reset the half while this resumed. send.throwIfReset(); const chunk = data.subarray(offset, offset + sendable); await this.#enqueueStreamFrame( streamId, { type: "stream", id, offset: start, data: chunk, fin: false }, signal, ); offset += sendable; stats.bytesSent += sendable; stats.bytesAcknowledged = stats.bytesSent; } } /** Enqueue a DATAGRAM frame on the scheduler's bounded, lossy datagram lane - * dropped under transport backpressure or once closed, rather than piling up * on the (lossless, unbounded) control lane. Size/support checks happen in * {@link Datagrams} before we get here. */ #sendDatagram(data: Uint8Array) { if (this.#closed) return; const bytes = Frame.encode({ type: "datagram", data }, this.#version); this.#validateRecordSize(bytes); this.#scheduler?.enqueueDatagram(bytes); } #sendPriorityFrame(frame: Frame.Any) { // Once closed, the scheduler rejects new control frames; a late reset/stop // from a stream teardown callback must be a no-op, not a throw. (The close // frame goes through #end instead.) if (this.#closed) return; const bytes = Frame.encode(frame, this.#version); this.#validateRecordSize(bytes); if (frame.type === "ping_request" || frame.type === "ping_response") { // Only the newest ping matters: answering the latest request proves // liveness for all before it, and a newer keep-alive makes an unsent one // moot. Coalescing keeps a peer that pings without reading from growing // the control backlog. this.#scheduler?.replaceControl(frame.type, bytes); } else { this.#scheduler?.enqueueControl(bytes); } } /** Take one of the peer's stream slots for a new outgoing stream. * * With `waitUntilAvailable: false` an exhausted limit rejects at once, the way * Chrome's WebTransport does, instead of queueing behind the peer's next * MAX_STREAMS. It still waits for the peer's TRANSPORT_PARAMETERS, the * counterpart of the QUIC handshake that tells Chrome the limit up front. */ async #claimStream(dir: Stream.DirType, options: SendStreamOptions | undefined, refused: string) { await this.ready; if (this.#closed) throw this.#closed; if (options?.waitUntilAvailable === false) { await this.#paramsSettled.promise; if (this.#closed) throw this.#closed; const credit = dir === Stream.Dir.Bi ? this.#bidiStreamCredit : this.#uniStreamCredit; if (credit.tryClaim(1n) === 0n) throw new DOMException(refused, "NetworkError"); return; } await (dir === Stream.Dir.Bi ? this.#bidiStreamCredit : this.#uniStreamCredit).claim(1n); } /** Register a stream's initial send priority and expose a mutable `sendOrder` * accessor on its writable (matching the W3C `WebTransportSendStream` API). * Updating it re-prioritizes the stream's queued data immediately. */ #attachSendOrder(writable: WritableStream, streamId: bigint, initial: number) { this.#scheduler?.setSendOrder(streamId, initial); let order = initial; Object.defineProperty(writable, "sendOrder", { configurable: true, enumerable: true, get: () => order, set: (value: number) => { order = value; this.#scheduler?.setSendOrder(streamId, value); }, }); } /** Open a bidirectional stream, waiting for the peer to grant stream credit * unless `waitUntilAvailable` is false. */ async createBidirectionalStream(options?: SendStreamOptions): Promise { await this.#claimStream(Stream.Dir.Bi, options, "Failed to create bidirectional stream."); // close() may have torn down the session while the claim resumed. if (this.#closed) throw this.#closed; const id = Stream.Id.create(this.#nextBiStreamId++, Stream.Dir.Bi, this.#isServer); const stream = { send: new SendHalf(this.#peerParams.initialMaxStreamDataBidiRemote), recv: this.#recvHalf(id, this.#ourParams.initialMaxStreamDataBidiLocal), }; this.#streams.set(id.value.value, stream); const writable = this.#sendWritable(id, stream, stream.send, options?.sendOrder ?? DEFAULT_SEND_ORDER); return { readable: stream.recv.readable, writable }; } /** Open a send-only stream, waiting for the peer to grant stream credit * unless `waitUntilAvailable` is false. */ async createUnidirectionalStream(options?: SendStreamOptions): Promise { await this.#claimStream(Stream.Dir.Uni, options, "Failed to create send stream."); // close() may have torn down the session while the claim resumed. if (this.#closed) throw this.#closed; const id = Stream.Id.create(this.#nextUniStreamId++, Stream.Dir.Uni, this.#isServer); const stream = { send: new SendHalf(this.#peerParams.initialMaxStreamDataUni) }; this.#streams.set(id.value.value, stream); return this.#sendWritable(id, stream, stream.send, options?.sendOrder ?? DEFAULT_SEND_ORDER); } /** The writable for a stream's send half. */ #sendWritable(id: Stream.Id, stream: StreamState, send: SendHalf, sendOrder: number): SendStream { const streamId = id.value.value; const stats: SendStreamStats = { bytesWritten: 0, bytesSent: 0, bytesAcknowledged: 0 }; let signal!: AbortSignal; const reset = (e: unknown) => { const reason = e instanceof Error ? e : new Error("stream aborted"); this.#resetSend(id, stream, reason, VarInt.from(resetCode(e))); }; const writable = new WritableStream({ start: (controller) => { signal = controller.signal; stream.writable = controller; // An abort fires the signal at once but runs `abort` below only after the // in-flight write settles, so the signal has to end that write: here if // it is queued behind other frames, in SendHalf.claim if it is parked // on the peer's credit. controller.signal.addEventListener( "abort", () => { const reason = controller.signal.reason; this.#scheduler?.dropStream( streamId, reason instanceof Error ? reason : new Error("stream aborted"), ); }, { once: true }, ); }, write: async (chunk, controller) => { try { await this.#sendStreamData(id, send, chunk, controller.signal, stats); } catch (e) { // A failed write errors the writable without running `abort`, so end the // half here; an abort runs `abort` itself. if (!controller.signal.aborted) reset(e); throw e; } }, abort: reset, close: async () => { try { const offset = send.finish(); // Routed through the stream's own queue so it stays ordered after that // stream's data (not via the control lane, which would jump ahead). await this.#enqueueStreamFrame(streamId, { type: "stream", id, offset, data: new Uint8Array(), fin: true, }); } catch (e) { // An abort during close drops the queued FIN, and WritableStream never // runs `abort` once an in-flight close fails, so reset here instead. if (!signal.aborted) throw e; reset(signal.reason); return; } send.finished(); this.#scheduler?.forget(streamId); this.#reap(streamId); }, }); this.#attachSendOrder(writable, streamId, sendOrder); // W3C `WebTransportSendStream.getStats()`, so a caller can tell what the peer has. Object.defineProperty(writable, "getStats", { configurable: true, value: async (): Promise => ({ ...stats }), }); // Both properties are defined above. return writable as SendStream; } /** The one terminal transition; a no-op once closed. A clean end fulfills `closed`, * and per the WebTransport contract is reached only by a local {@link close} or a * peer's APPLICATION_CLOSE (0x1d). Everything else aborts, rejecting `closed` * with a `WebTransportError`: a socket failure, read error, idle timeout, a * protocol violation we detected, or a peer's CONNECTION_CLOSE (0x1c). Close * codes can't carry that distinction, since they are application-defined. * * Settles `ready` and `closed`, then tears down streams, credits, and the * scheduler, and closes the socket once it has the close frame. */ #end(end: End) { if (this.#closed) return; // Encode before the transition, so an oversized reason throws with the session still open. const send = end.clean ? end.send && { type: "application_close" as const, code: end.code, reason: end.reason } : end.send && { type: "connection_close" as const, ...end.send }; let frame: Uint8Array | undefined; if (send) { frame = Frame.encode({ type: send.type, code: VarInt.from(send.code), reason: send.reason }, this.#version); this.#validateRecordSize(frame); } const error = end.clean ? new Error(`Connection closed: ${end.code} ${end.reason}`) : end.cause; this.#closed = error; // Rejecting `ready` is a no-op once it has resolved (after a successful open). this.#readyReject(error); if (end.clean) this.#closedResolve({ closeCode: end.code, reason: end.reason }); else this.#closedReject(new SessionError(error.message, { cause: error })); this.#idleTimer?.close(); this.#idleTimer = undefined; // A clean end ends the incoming readables; an abort errors them with its cause. const cause = end.clean ? undefined : error; this.#incomingBidirectionalQueue.close(cause); this.#incomingUnidirectionalQueue.close(cause); closeDatagrams(this.#datagrams, cause); for (const stream of this.#streams.values()) { try { stream.writable?.error(error); } catch {} stream.send?.credit.close(error); // A receive half whose final size is known keeps what it still owes the reader, // as it would once forgotten. if (stream.recv && !stream.recv.sizeKnown) stream.recv.refuse(error); } this.#streams.clear(); this.#updates.clear(); this.#paramsSettled.resolve(); // Close global credits so blocked claim() calls reject. this.#connCredit.close(error); this.#bidiStreamCredit.close(error); this.#uniStreamCredit.close(error); // Drop whatever is still queued so the close frame goes out next. const flushed = this.#scheduler?.close(error, frame); if (frame && flushed !== undefined) { // Close the socket once it has the close frame. A socket the peer stopped // draining can't hold it open: past CLOSE_TIMEOUT it closes without it. const close = () => this.#transportClose(); void timeout(CLOSE_TIMEOUT, flushed).then(close, close); } else { this.#transportClose(); } } /** Tear down the underlying transport. The meaningful close code/reason * already travels in the close frame, so the WebSocket-level close is bare * (avoids the WebSocket close-code validity constraints). */ #transportClose() { try { this.#wss?.close(); } catch {} } /** Close the session with an application code and reason; a no-op once closed. */ close(info?: { closeCode?: number; reason?: string }) { this.#end({ clean: true, code: info?.closeCode ?? 0, reason: info?.reason ?? "", send: true }); } /** Resize the send-buffer high-water mark (bytes) used for write * backpressure. A QMux extension beyond the standard `WebTransport` API: * set this to roughly the bandwidth-delay product (RTT × estimated * throughput) to keep the pipe full while leaving as much queued data as * possible reprioritizable by the send scheduler. */ setSendBufferSize(bytes: number) { this.#sendBufferSize = sendBufferSize(bytes); this.#wss?.setHighWaterMark?.(this.#sendBufferSize); this.#backlog?.setHighWaterMark(this.#sendBufferSize); } /** Always `"default"`: the underlying TCP connection does its own congestion control. */ get congestionControl(): WebTransportCongestionControl { return "default"; } /** Always `"reliable-only"`: datagrams ride the WebSocket, so nothing is unreliable. */ get reliability() { return "reliable-only" as const; } /** Reports no counters: the WebSocket exposes none. `datagrams` is required by the W3C dictionary. */ async getStats() { return { datagrams: {} }; } } /** `err` if it is an Error, else a new one saying `fallback`. */ function toError(err: unknown, fallback: string): Error { return err instanceof Error ? err : new Error(fallback); }