From 0c47a1916f75f46c481be266be5cf7975d10c3c4 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 13 Nov 2026 22:13:24 -0800 Subject: [PATCH 1/5] chore(quest): claim quest/m1/js-bundle-audit.md Quest-Claim: 98a0ba0f2ca88ef5 From d426f5a2adbc4dc6ccb7c4d95a669f8c8768d2c6 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 13 Nov 2026 22:29:56 -0800 Subject: [PATCH 2/5] perf(net): lazy-load the WebSocket fallback and drop zod from the static graph @moq/qmux now loads on demand when the fallback dials, and transportOf reads a "websocket" label on the qmux Session instead of instanceof. The internal HopSchema becomes a plain branded bigint with toHop(). Every consumer bundle loses 10.5 to 12.9 KB of brotli, which clears Nightly's 30-day size comparison from 2026-12-05 instead of 12-13. Finishes quest/m1/js-bundle-audit.md. Co-Authored-By: Claude Opus 5.5 --- doc/lib/js/net.md | 4 +- js/net/bench/broadcasts.ts | 14 +- js/net/src/announced.test.ts | 4 +- js/net/src/connection/connect.ts | 22 +-- js/net/src/connection/stats.test.ts | 9 +- js/net/src/connection/transport.ts | 8 +- js/net/src/hop.ts | 23 ++-- js/net/src/ietf/cluster.test.ts | 4 +- js/net/src/ietf/cluster.ts | 6 +- js/net/src/ietf/peer-violations.test.ts | 10 +- js/net/src/ietf/publisher.test.ts | 20 +-- js/net/src/ietf/subscriber.test.ts | 14 +- js/net/src/lite/announce.test.ts | 32 +++-- js/net/src/lite/announce.ts | 8 +- js/net/src/lite/connection.ts | 6 +- js/net/src/lite/setup.test.ts | 10 +- js/net/src/lite/setup.ts | 4 +- js/net/src/lite/subscriber.test.ts | 170 +++++++++++------------- js/net/src/origin.test.ts | 10 +- js/net/src/request-deadline.test.ts | 14 +- js/net/src/resume.model.test.ts | 4 +- js/net/src/session-limits.test.ts | 6 +- js/qmux/api/index.api.md | 1 + js/qmux/src/session.test.ts | 7 + js/qmux/src/session.ts | 2 + quest/m1/js-bundle-audit.md | 74 ----------- 26 files changed, 199 insertions(+), 287 deletions(-) delete mode 100644 quest/m1/js-bundle-audit.md diff --git a/doc/lib/js/net.md b/doc/lib/js/net.md index d117e70e20e..17119d4c02e 100644 --- a/doc/lib/js/net.md +++ b/doc/lib/js/net.md @@ -65,7 +65,9 @@ route.announce(); Examples: [`js/net/examples/`](https://github.com/moq-dev/moq/tree/main/js/net/examples). Runs in the browser and, over WebSocket, in Node, Bun, and Deno; see -[server-side](/lib/js/#server-side). Path patterns are on the +[server-side](/lib/js/#server-side). The WebSocket fallback and the moq-transport stack load +on demand as separate chunks, so a session over WebTransport and moq-lite never downloads them. +Path patterns are on the [concept page](/concept/moq-lite#path-patterns). Groups retain a 32 MiB live tail without limiting their lifetime or frame count. diff --git a/js/net/bench/broadcasts.ts b/js/net/bench/broadcasts.ts index 2e71de90c2d..3a3c9dd5837 100644 --- a/js/net/bench/broadcasts.ts +++ b/js/net/bench/broadcasts.ts @@ -5,7 +5,7 @@ import { Signal } from "@moq/signals"; import type { Grant } from "../src/auth.ts"; import { Producer as BroadcastProducer } from "../src/broadcast.ts"; import { BroadcastCache } from "../src/consume.ts"; -import { HopSchema, WireRoute } from "../src/hop.ts"; +import { toHop, WireRoute } from "../src/hop.ts"; import * as Instance from "../src/instance.ts"; import { AnnounceRequest } from "../src/lite/announce.ts"; import { Publisher } from "../src/lite/publisher.ts"; @@ -202,15 +202,7 @@ for (const patternCount of [8, 32, 128]) { ...Array.from({ length: patternCount - 1 }, (_, i) => Path.Pattern.literal(`other/${i}`)), ]); const grant = new Signal({ publish: new Path.Patterns(), subscribe }); - const subscriber = new Subscriber( - quic, - Version.DRAFT_05, - HopSchema.parse(1n), - undefined, - undefined, - undefined, - grant, - ); + const subscriber = new Subscriber(quic, Version.DRAFT_05, toHop(1n), undefined, undefined, undefined, grant); const groups = await Promise.all( Array.from({ length: fetchCount }, (_, i) => subscriber.fetchGroup(Path.from(`room/${i}`), "video", 0n)), ); @@ -409,7 +401,7 @@ for (const routeCount of routeCounts) { }); const senders = Array.from({ length: observerCount }, () => { const pair = createMockTransportPair(ALPN_07_WIP); - const publisher = new Publisher(pair.server, Version.DRAFT_07, HopSchema.parse(1n), origin.consume()); + const publisher = new Publisher(pair.server, Version.DRAFT_07, toHop(1n), origin.consume()); const entered = Promise.withResolvers(); const release = Promise.withResolvers(); const stream = new Stream({ diff --git a/js/net/src/announced.test.ts b/js/net/src/announced.test.ts index 3150cbe359d..762422c3efc 100644 --- a/js/net/src/announced.test.ts +++ b/js/net/src/announced.test.ts @@ -3,7 +3,7 @@ import { yieldNow } from "@moq/clock"; import * as Announce from "./announced.ts"; import type { Credential } from "./auth.ts"; import type { Producer as BroadcastProducer } from "./broadcast.ts"; -import { HopSchema, UNKNOWN_HOP, WireRoute } from "./hop.ts"; +import { toHop, UNKNOWN_HOP, WireRoute } from "./hop.ts"; import * as Instance from "./instance.ts"; import { Producer as OriginProducer } from "./origin.ts"; import * as Path from "./path.ts"; @@ -51,7 +51,7 @@ test("a listing shows a route's facts, never its epoch, hops, credential, or dra const route = WireRoute.normalize({ instance, epoch: 3n, - hops: [HopSchema.parse(7n), UNKNOWN_HOP], + hops: [toHop(7n), UNKNOWN_HOP], cost: 5n, auth: {} as Credential, draining: true, diff --git a/js/net/src/connection/connect.ts b/js/net/src/connection/connect.ts index 9cde0906da7..1009a90e11b 100644 --- a/js/net/src/connection/connect.ts +++ b/js/net/src/connection/connect.ts @@ -1,5 +1,5 @@ import { Duration, Elapsed, sleep, timeout } from "@moq/clock"; -import { Session as Qmux, type SessionOptions as QmuxOptions, type Version as QmuxVersion } from "@moq/qmux"; +import type { Session as Qmux, SessionOptions as QmuxOptions, Version as QmuxVersion } from "@moq/qmux"; import { type Getter, race } from "@moq/signals"; import type * as Auth from "../auth.ts"; import { vacant } from "../auth_session.ts"; @@ -20,6 +20,7 @@ import { DEFAULT_TIMEOUT, exchangeSetup, handsOff } from "./handshake.ts"; import type { Session } from "./session.ts"; import { inspect } from "./stats.ts"; import { credential, fallback, hold, type Presentation } from "./tokens.ts"; +import { transportOf } from "./transport.ts"; // Default head start for WebTransport before attempting the WebSocket fallback. const DEFAULT_WEBSOCKET_DELAY = Duration.millis(500); @@ -496,7 +497,8 @@ async function connectInner( void abort.then(() => session.close()); // Record who won the race to this server, so QUIC's next head start follows the last result. - if (session instanceof Qmux) { + const websocket = transportOf(session) === "websocket"; + if (websocket) { console.debug(show(parse(url)), "connected via WebSocket"); websocketWon.add(server); } else { @@ -514,9 +516,9 @@ async function connectInner( session.close(); throw new Error("server negotiated no protocol, and no offered version negotiates in SETUP"); } - const won = session instanceof Qmux && fallbackDial ? fallbackDial : dial; + const won = websocket && fallbackDial ? fallbackDial : dial; const connection = await connectTransport(url, session as WebTransport, wiring(won), offered.setup); - if (session instanceof Qmux) { + if (websocket) { const forget = () => websocketWon.delete(server); void connection.closed.then(forget, forget); } @@ -952,13 +954,15 @@ async function connectWebSocket( cancel: Promise, options: QmuxOptions, ): Promise { - const timer = sleep(delay); - - const active = await Promise.race([cancel, timer.then(() => true)]); - if (!active) return undefined; + // qmux loads on demand, since most sessions win over WebTransport; fetch it during the head + // start so the fallback dials as soon as it would have. + const loaded = Promise.all([import("@moq/qmux"), sleep(delay)]); + const qmux = await race([cancel, loaded]); + if (!qmux) return undefined; + const [{ Session }] = qmux; for (let wait = WEBSOCKET_REDIAL; ; wait = wait.mul(2)) { - const quic = new Qmux(url, options); + const quic = new Session(url, options); // Wait for the WebSocket to connect, for the cancel promise to resolve, or for the // redial. `ready` rejects on a refused/failed connection, so a throw here is the diff --git a/js/net/src/connection/stats.test.ts b/js/net/src/connection/stats.test.ts index 570274af09c..855d513e62f 100644 --- a/js/net/src/connection/stats.test.ts +++ b/js/net/src/connection/stats.test.ts @@ -1,11 +1,10 @@ import { expect, spyOn, test } from "bun:test"; import { Duration, yieldNow } from "@moq/clock"; import { Manual } from "@moq/clock/test"; -import { Session as QmuxSession } from "@moq/qmux"; import { Effect } from "@moq/signals"; import * as Ietf from "../ietf/index.ts"; import * as Lite from "../lite/index.ts"; -import { createMockTransportPair, MockTransport } from "../mock.ts"; +import { createMockTransportPair, type MockTransport } from "../mock.ts"; import { type AcceptProps, accept as acceptSession, type ConnectProps, connect as connectSession } from "./index.ts"; import { Reload } from "./reload.ts"; import { canEstimate, estimates, type TransportStats, transportStats } from "./stats.ts"; @@ -120,11 +119,9 @@ const kinds: { name: string; estimates: boolean; shape: (quic: MockTransport) => { name: "the WebSocket fallback", estimates: false, - // A qmux session is what marks the fallback; the mock keeps its own behavior. + // A qmux session labels itself as the fallback; the mock keeps its own behavior. shape: (quic) => { - const proto = Object.create(QmuxSession.prototype); - Object.defineProperties(proto, Object.getOwnPropertyDescriptors(MockTransport.prototype)); - Object.setPrototypeOf(quic, proto); + Object.assign(quic, { transport: "websocket" }); }, }, { diff --git a/js/net/src/connection/transport.ts b/js/net/src/connection/transport.ts index cab9312702c..43eea5707d3 100644 --- a/js/net/src/connection/transport.ts +++ b/js/net/src/connection/transport.ts @@ -1,15 +1,13 @@ -import { Session } from "@moq/qmux"; - /** The wire transport a session runs over. */ export type Transport = "webtransport" | "websocket" | "webrtc"; /** * The transport a live session is actually running over. WebSocket and WebRTC adapters - * share the WebTransport shape; WebRTC carries its label to avoid a dependency cycle. + * share the WebTransport shape and carry their label, so `@moq/qmux` stays a lazy chunk. * * @internal Not re-exported from the package entrypoint. */ export function transportOf(quic: WebTransport): Transport { - if ("transport" in quic && quic.transport === "webrtc") return "webrtc"; - return quic instanceof Session ? "websocket" : "webtransport"; + const label = "transport" in quic ? quic.transport : undefined; + return label === "webrtc" || label === "websocket" ? label : "webtransport"; } diff --git a/js/net/src/hop.ts b/js/net/src/hop.ts index 415b9ff5355..ab69cc998e9 100644 --- a/js/net/src/hop.ts +++ b/js/net/src/hop.ts @@ -8,7 +8,6 @@ * @module */ import type { Duration } from "@moq/clock"; -import * as z from "zod/mini"; import type { Credential } from "./auth.ts"; import type * as Instance from "./instance.ts"; import { isLeadingOnes, type StreamVersion } from "./stream.ts"; @@ -20,17 +19,19 @@ import { isLeadingOnes, type StreamVersion } from "./stream.ts"; * stamps into a chain as an announcement passes through, so a receiver can spot its own * id and reject a loop. The SETUP parameter that carries it session-wide is `Hop` too. * - * The {@link HopSchema} validates any incoming value and brands it so the type system + * {@link toHop} validates any incoming value and brands it so the type system * enforces "only validated ids flow into hop chains." Internal code that synthesizes one - * (e.g. `randomHop`) uses `HopSchema.parse(...)` to brand a raw bigint. + * (e.g. `randomHop`) brands a raw bigint the same way. */ -export const HopSchema = z - .bigint() - .check(z.refine((value) => value >= 0n && value < 1n << 64n, "Hop must be a non-negative 64-bit integer")) - .brand("Hop"); +export type Hop = bigint & { readonly [hopBrand]: true }; -/** A relay's hop id, validated by {@link HopSchema}. */ -export type Hop = z.infer; +declare const hopBrand: unique symbol; + +/** Brand `value` as a {@link Hop}, refusing anything outside the unsigned 64-bit range. */ +export function toHop(value: bigint): Hop { + if (value < 0n || value >= 1n << 64n) throw new RangeError("Hop must be a non-negative 64-bit integer"); + return value as Hop; +} /** * The reserved id 0, meaning "no identity". @@ -40,7 +41,7 @@ export type Hop = z.infer; * in common, and never excluded from an advertisement. A chain that holds a 0 anywhere * is anonymous for route selection. */ -export const UNKNOWN_HOP: Hop = HopSchema.parse(0n); +export const UNKNOWN_HOP: Hop = toHop(0n); /** * The id `hop` carries on a wire in `version`'s varint form. @@ -77,7 +78,7 @@ export function randomHop(): Hop { // Mask to 53 bits. const raw = buf[0] & 0x1f_ffff_ffff_ffffn; // Guard against the (astronomically unlikely) zero draw. - return HopSchema.parse(raw === 0n ? 1n : raw); + return toHop(raw === 0n ? 1n : raw); } /** The static cost of pulling content through a route; lower wins. */ diff --git a/js/net/src/ietf/cluster.test.ts b/js/net/src/ietf/cluster.test.ts index 82159734ac9..4882ca6d18f 100644 --- a/js/net/src/ietf/cluster.test.ts +++ b/js/net/src/ietf/cluster.test.ts @@ -1,6 +1,6 @@ import { expect, test } from "bun:test"; import { ProtocolViolation, StreamCode, StreamError } from "../error.ts"; -import { type Hop, HopSchema, UNKNOWN_HOP } from "../hop.ts"; +import { type Hop, toHop, UNKNOWN_HOP } from "../hop.ts"; import * as Path from "../path.ts"; import { Reader, Writer } from "../stream.ts"; import * as Cluster from "./cluster.ts"; @@ -19,7 +19,7 @@ const VERSION = Version.DRAFT_18; const CLUSTER = { cluster: true }; function origin(id: bigint): Hop { - return HopSchema.parse(id); + return toHop(id); } function hops(...ids: bigint[]): Hop[] { diff --git a/js/net/src/ietf/cluster.ts b/js/net/src/ietf/cluster.ts index ac0814b9e54..2b1b8cf098b 100644 --- a/js/net/src/ietf/cluster.ts +++ b/js/net/src/ietf/cluster.ts @@ -25,7 +25,7 @@ */ import { ProtocolViolation, reason } from "../error.ts"; -import { type Hop, HopSchema, MAX_HOPS, UNKNOWN_HOP } from "../hop.ts"; +import { type Hop, MAX_HOPS, toHop, UNKNOWN_HOP } from "../hop.ts"; import * as Varint from "../varint.ts"; // Type-only: SETUP loads eagerly and must not pull in the message parameter codec. import type { Parameters } from "./parameters.ts"; @@ -93,7 +93,7 @@ export function fromSetup(params: SetupOptions): Hop | undefined { // 0 is legal: the peer speaks the extension but withholds its identity. const value = params.getVarint(SetupOption.HopId); if (value === undefined) return undefined; - return HopSchema.parse(value); + return toHop(value); } /** @@ -233,7 +233,7 @@ function decodeHops(value: Uint8Array): Hop[] { while (rest.length > 0) { // A short read here means the entries did not exactly fill the length. const [hop, remain] = Varint.decodeLeadingOnes(rest); - hops.push(HopSchema.parse(hop)); + hops.push(toHop(hop)); rest = remain; // Bail before the buffer does: a hostile length would otherwise cost us one diff --git a/js/net/src/ietf/peer-violations.test.ts b/js/net/src/ietf/peer-violations.test.ts index 28539a57aab..70a8bb6b184 100644 --- a/js/net/src/ietf/peer-violations.test.ts +++ b/js/net/src/ietf/peer-violations.test.ts @@ -1,6 +1,6 @@ import { expect, spyOn, test } from "bun:test"; import { SessionCode, StreamCode, StreamError } from "../error.ts"; -import { HopSchema } from "../hop.ts"; +import { toHop } from "../hop.ts"; import { createMockTransportPair } from "../mock.ts"; import * as Path from "../path.ts"; import { Stream, Writer } from "../stream.ts"; @@ -111,8 +111,8 @@ for (const [version, alpn] of versions) { ); await writer.u53(RequestOk.id); await new RequestOk({}).encode(writer, version); - const self = HopSchema.parse(5n), - peer = HopSchema.parse(9n); + const self = toHop(5n), + peer = toHop(9n); const entry = async (name: string) => { await writer.u53(SubscribeNamespaceEntry.id); await new SubscribeNamespaceEntry({ @@ -161,8 +161,8 @@ for (const [version, alpn] of versions) { `${alpn}: %s releases a slot after route reflection and reattachment`, async (ending) => { const pair = createMockTransportPair(alpn); - const self = HopSchema.parse(5n), - peer = HopSchema.parse(9n); + const self = toHop(5n), + peer = toHop(9n); const subscriber = new Subscriber({ session: new NativeSession(pair.server, version, true), quic: pair.server, diff --git a/js/net/src/ietf/publisher.test.ts b/js/net/src/ietf/publisher.test.ts index 6ad40173ee6..ef7703ae1c9 100644 --- a/js/net/src/ietf/publisher.test.ts +++ b/js/net/src/ietf/publisher.test.ts @@ -15,7 +15,7 @@ import { Stream as StreamError, unauthorized, } from "../error.ts"; -import { type Hop, HopSchema } from "../hop.ts"; +import { type Hop, toHop } from "../hop.ts"; import * as Instance from "../instance.ts"; import { hooks } from "../internal.ts"; import { createMockTransportPair, manual, SessionBroadcast, settlesWithin } from "../mock.ts"; @@ -1537,9 +1537,9 @@ test("closing the session ends the unsolicited announce loop", async () => { * not read ours either, so sending it the parameters would be a protocol violation. */ test("an advertisement carries our hop id once the peer declared one", async () => { - const self: Hop = HopSchema.parse(7n); + const self: Hop = toHop(7n); - for (const peer of [HopSchema.parse(9n), undefined]) { + for (const peer of [toHop(9n), undefined]) { const pair = createMockTransportPair(ALPN.DRAFT_18); const { pub, origin } = publisher(pair.server, { cluster: { self, peer } }); publish(origin, Path.from("mine")); @@ -1631,8 +1631,8 @@ async function readUpdate(stream: Stream): Promise { function clustered(requiresSolicitation = false, auth?: Tokens) { const clock = new Manual(); const installed = clock.install(); - const self: Hop = HopSchema.parse(7n); - const peer: Hop = HopSchema.parse(9n); + const self: Hop = toHop(7n); + const peer: Hop = toHop(9n); const pair = createMockTransportPair(ALPN.DRAFT_18); const { pub, origin } = publisher(pair.server, { cluster: { self, peer }, requiresSolicitation, auth }); const streams = accepted(pair.client); @@ -1643,9 +1643,9 @@ function clustered(requiresSolicitation = false, auth?: Tokens) { return { clock, self, pair, pub, origin, streams, close }; } -const VIA: Hop = HopSchema.parse(3n); -const MID: Hop = HopSchema.parse(4n); -const OTHER: Hop = HopSchema.parse(5n); +const VIA: Hop = toHop(3n); +const MID: Hop = toHop(4n); +const OTHER: Hop = toHop(5n); /** * A reprice is a REQUEST_UPDATE on the request that already carries the namespace, with @@ -2165,11 +2165,11 @@ test("an unanswered update drops the request and re-offers the namespace fresh", * the peer cannot see must not withdraw and advertise the namespace again. */ test.each([ - ["an unchanged price with Cluster", HopSchema.parse(9n)], + ["an unchanged price with Cluster", toHop(9n)], ["any re-price without Cluster", undefined], ])("%s sends nothing", async (_, peer) => { using clock = manual(); - const self: Hop = HopSchema.parse(7n); + const self: Hop = toHop(7n); const pair = createMockTransportPair(ALPN.DRAFT_18); const { pub, origin } = publisher(pair.server, { cluster: { self, peer } }); const broadcast = origin.route(Path.from("mine"), { cost: 4n }); diff --git a/js/net/src/ietf/subscriber.test.ts b/js/net/src/ietf/subscriber.test.ts index 4dcd964d106..2395a09c4e2 100644 --- a/js/net/src/ietf/subscriber.test.ts +++ b/js/net/src/ietf/subscriber.test.ts @@ -4,7 +4,7 @@ import { Manual } from "@moq/clock/test"; import { Once } from "@moq/signals"; import type * as announce from "../announced.ts"; import { ProtocolViolation, StreamCode, Stream as StreamError } from "../error.ts"; -import { type Hop, HopSchema, UNKNOWN_HOP } from "../hop.ts"; +import { type Hop, toHop, UNKNOWN_HOP } from "../hop.ts"; import { hooks } from "../internal.ts"; import { createMockTransportPair, manual, settlesWithin } from "../mock.ts"; import * as Path from "../path.ts"; @@ -321,8 +321,8 @@ test("an entry buffered past a consumer close does not pin the path", async () = }); /** The Hop IDs a cluster-negotiated session declared, ours first. */ -const SELF: Hop = HopSchema.parse(7n); -const PEER: Hop = HopSchema.parse(9n); +const SELF: Hop = toHop(7n); +const PEER: Hop = toHop(9n); /** * A peer that knows our Hop ID never advertises a path that already ran through us, so @@ -491,7 +491,7 @@ test("a PUBLISH_NAMESPACE update that starts looping back is detached", async () await acceptSubscribeNamespace(pair.client); // Published by 11, relayed by the peer. Every update keeps that publisher. - const publisher = HopSchema.parse(11n); + const publisher = toHop(11n); const request = await Stream.open(pair.server, { version: VERSION }); const handler = subscriber.runPublishNamespace( new PublishNamespace({ @@ -598,7 +598,7 @@ test("a PUBLISH_NAMESPACE update that changes the publisher applies in place", a new PublishNamespace({ requestId: 0n, trackNamespace: Path.from("theirs"), - params: { cluster: { hops: [HopSchema.parse(11n), PEER], cost: 0n } }, + params: { cluster: { hops: [toHop(11n), PEER], cost: 0n } }, }), request, ); @@ -610,7 +610,7 @@ test("a PUBLISH_NAMESPACE update that changes the publisher applies in place", a const held = subscriber.consume(Path.from("theirs")); await peer.writer.u53(PublishNamespaceUpdate.id); - await new PublishNamespaceUpdate({ requestId: 3n, update: { hops: [HopSchema.parse(8n), PEER] } }).encode( + await new PublishNamespaceUpdate({ requestId: 3n, update: { hops: [toHop(8n), PEER] } }).encode( peer.writer, VERSION, ); @@ -619,7 +619,7 @@ test("a PUBLISH_NAMESPACE update that changes the publisher applies in place", a expect(await announced.next()).toMatchObject({ prefix: Path.from("theirs"), kind: "update", - route: { hops: [HopSchema.parse(8n), PEER] }, + route: { hops: [toHop(8n), PEER] }, }); expect(subscriber.consume(Path.from("theirs")).closed).toBe(held.closed); diff --git a/js/net/src/lite/announce.test.ts b/js/net/src/lite/announce.test.ts index 94f00636027..1153220158a 100644 --- a/js/net/src/lite/announce.test.ts +++ b/js/net/src/lite/announce.test.ts @@ -1,6 +1,6 @@ import { expect, test } from "bun:test"; import { ProtocolViolation } from "../error.ts"; -import { Cost, HopSchema, UNKNOWN_HOP } from "../hop.ts"; +import { Cost, toHop, UNKNOWN_HOP } from "../hop.ts"; import * as Instance from "../instance.ts"; import * as Path from "../path.ts"; import { Reader, Writer } from "../stream.ts"; @@ -53,7 +53,7 @@ async function roundTrip(msg: AnnounceBroadcast, version: Version): Promise { - const hops = [HopSchema.parse(7n)]; + const hops = [toHop(7n)]; const gotActive = await roundTrip({ status: "active", suffix: Path.from("room/cam"), hops }, Version.DRAFT_05); expect(gotActive).toEqual({ status: "active", suffix: Path.from("room/cam"), hops }); @@ -62,7 +62,7 @@ test("AnnounceBroadcast round-trips on draft-05", async () => { }); test("AnnounceBroadcast round-trips on draft-06", async () => { - const hops = [HopSchema.parse(7n)]; + const hops = [toHop(7n)]; // An absent cost encodes as zero and decodes explicitly. const gotActive = await roundTrip({ status: "active", suffix: Path.from("room/cam"), hops }, Version.DRAFT_06); expect(gotActive).toEqual({ status: "active", suffix: Path.from("room/cam"), hops, cost: 0n }); @@ -184,14 +184,14 @@ async function requestRoundTrip(msg: AnnounceRequest, version: Version): Promise // Draft04/05 carry the subscriber's Hop ID so the publisher can skip reflected // announces before they hit the wire. test("AnnounceRequest carries excludeHop on draft-05", async () => { - const got = await requestRoundTrip(new AnnounceRequest(Path.from("room"), HopSchema.parse(42n)), Version.DRAFT_05); - expect(got.excludeHop).toBe(HopSchema.parse(42n)); + const got = await requestRoundTrip(new AnnounceRequest(Path.from("room"), toHop(42n)), Version.DRAFT_05); + expect(got.excludeHop).toBe(toHop(42n)); }); // Draft06 dropped the field: the receiver's reflected-announce check catches the same // loops, so a value set locally is simply not sent and decodes as zero. test("AnnounceRequest drops excludeHop on draft-06", async () => { - const msg = new AnnounceRequest(Path.from("room"), HopSchema.parse(42n)); + const msg = new AnnounceRequest(Path.from("room"), toHop(42n)); const got = await requestRoundTrip(msg, Version.DRAFT_06); expect(got.excludeHop).toBe(UNKNOWN_HOP); @@ -225,21 +225,21 @@ test("AnnounceOk accepts the reserved unknown origin", async () => { }); test("AnnounceOk round-trips a declared origin", async () => { - const msg = new AnnounceOk(HopSchema.parse(42n), 1); + const msg = new AnnounceOk(toHop(42n), 1); const reader = new Reader( undefined, await bytes((w) => msg.encode(w, Version.DRAFT_05), Version.DRAFT_05), Version.DRAFT_05, ); const got = await AnnounceOk.decode(reader, Version.DRAFT_05); - expect(got.hop).toBe(HopSchema.parse(42n)); + expect(got.hop).toBe(toHop(42n)); expect(got.active).toBe(1); }); // A QUIC varint stops at 2^62-1, so draft-06 carries a wider hop as unknown. test("a 64-bit hop is unknown on draft-06", async () => { const version = Version.DRAFT_06; - const wide = HopSchema.parse((1n << 64n) - 1n); + const wide = toHop((1n << 64n) - 1n); const got = await roundTrip({ status: "active", suffix: Path.from("room"), hops: [wide] }, version); expect(got).toMatchObject({ hops: [UNKNOWN_HOP] }); @@ -249,8 +249,8 @@ test("a 64-bit hop is unknown on draft-06", async () => { }); test("a hop chain that revisits a hop is refused in both directions", async () => { - const four = HopSchema.parse(4n); - const eight = HopSchema.parse(8n); + const four = toHop(4n); + const eight = toHop(8n); const looped: AnnounceBroadcast = { status: "active", suffix: Path.from("room"), hops: [four, eight, four] }; // Outbound: refused before it reaches the wire. A receiver must close the session over @@ -265,7 +265,7 @@ test("a hop chain that revisits a hop is refused in both directions", async () = const legal: AnnounceBroadcast = { status: "active", suffix: Path.from("room"), - hops: [four, eight, HopSchema.parse(9n)], + hops: [four, eight, toHop(9n)], }; const forged = await bytes((w) => encodeAnnounceBroadcast(w, legal, Version.DRAFT_06), Version.DRAFT_06); const nine = forged.lastIndexOf(9); @@ -284,7 +284,7 @@ test("a hop chain that revisits a hop is refused in both directions", async () = // Repeated unknowns are not a loop: 0 identifies nothing, so any number of hops may // be unknown. A lite-03 announcement is nothing but these. - const unknown = HopSchema.parse(0n); + const unknown = toHop(0n); const anonymous: AnnounceBroadcast = { status: "active", suffix: Path.from("room"), @@ -419,9 +419,7 @@ test("the route layer round-trips on draft-07", async () => { const literal: AnnounceBroadcast = { status: "active", suffix: Path.from("x"), route: 2n, instance: a, epoch: 1n }; expect(await roundTrip(literal, v)).toEqual({ ...literal, cost: 0n }); await expect(bytes((w) => encodeAnnounceBroadcast(w, { ...literal, route: undefined }, v), v)).rejects.toThrow(); - await expect( - bytes((w) => encodeAnnounceBroadcast(w, { ...literal, hops: [HopSchema.parse(1n)] }, v), v), - ).rejects.toThrow(); + await expect(bytes((w) => encodeAnnounceBroadcast(w, { ...literal, hops: [toHop(1n)] }, v), v)).rejects.toThrow(); }); test("the route layer refuses the last seqno and Node ID 0", async () => { @@ -655,7 +653,7 @@ test("SYNCED is empty and belongs only to lite-07", async () => { // Lite-07 drops both: the count for SYNCED, and the Hop ID for the route layer. test("ANNOUNCE_OK is empty on lite-07", async () => { for (const version of [Version.DRAFT_06, Version.DRAFT_07]) { - const wire = await bytes((w) => new AnnounceOk(HopSchema.parse(1n), 7).encode(w, version), version); + const wire = await bytes((w) => new AnnounceOk(toHop(1n), 7).encode(w, version), version); expect(wire).toEqual(new Uint8Array(version === Version.DRAFT_06 ? [2, 1, 7] : [0])); } }); diff --git a/js/net/src/lite/announce.ts b/js/net/src/lite/announce.ts index a4b5bebd8c0..8fab402ce09 100644 --- a/js/net/src/lite/announce.ts +++ b/js/net/src/lite/announce.ts @@ -1,5 +1,5 @@ import { ProtocolViolation } from "../error.ts"; -import { type Cost, type Hop, HopSchema, MAX_HOPS, UNKNOWN_HOP, wireHop } from "../hop.ts"; +import { type Cost, type Hop, MAX_HOPS, toHop, UNKNOWN_HOP, wireHop } from "../hop.ts"; import type * as Instance from "../instance.ts"; import * as Path from "../path.ts"; import type { Reader, Writer } from "../stream.ts"; @@ -204,7 +204,7 @@ async function decodeHops(r: Reader, version: Version): Promise { if (count > MAX_HOPS) throw new Error(`hop count ${count} exceeds maximum ${MAX_HOPS}`); const hops: Hop[] = []; for (let i = 0; i < count; i++) { - hops.push(HopSchema.parse(await r.u62())); + hops.push(toHop(await r.u62())); } checkHops(hops); return hops; @@ -619,7 +619,7 @@ export class AnnounceRequest { static async #decode(r: Reader, version: Version): Promise { const prefix = Path.decode(await r.string()); - const excludeHop = hasExcludeHop(version) ? HopSchema.parse(await r.u62()) : UNKNOWN_HOP; + const excludeHop = hasExcludeHop(version) ? toHop(await r.u62()) : UNKNOWN_HOP; const hidden = hasHidden(version) ? await r.bool() : false; return new AnnounceRequest(prefix, excludeHop, hidden); } @@ -721,7 +721,7 @@ export class AnnounceOk { // The draft reserves 0 for "unknown": the responder was never assigned an id, or // withholds it to obscure its routing. It names nobody, so callers must not stamp // it onto a hop chain, but it is a legal message and not grounds to drop the stream. - const origin = HopSchema.parse(await r.u62()); + const origin = toHop(await r.u62()); const active = hasSynced(version) ? 0 : await r.u53(); return new AnnounceOk(origin, active); } diff --git a/js/net/src/lite/connection.ts b/js/net/src/lite/connection.ts index 32ab0788079..05b102f939b 100644 --- a/js/net/src/lite/connection.ts +++ b/js/net/src/lite/connection.ts @@ -8,7 +8,7 @@ import type { Session } from "../connection/session.ts"; import { detect, type Probe, type Stats, statsOf, type TransportStats, transportStats } from "../connection/stats.ts"; import { type Transport, transportOf } from "../connection/transport.ts"; import { closeError, error, fromClose, ProtocolViolation, StreamCode, sessionCause } from "../error.ts"; -import { type Hop, HopSchema, randomHop } from "../hop.ts"; +import { type Hop, randomHop, toHop } from "../hop.ts"; import { IMPLEMENTATION } from "../implementation.ts"; import { hooks } from "../internal.ts"; import { lines } from "../open.ts"; @@ -213,7 +213,7 @@ export class Connection implements Session { lines(quic).probe = this.#probe; this.#own = publish && wireOf(publish).own; - this.hop = hasRoutes(version) && this.#own ? HopSchema.parse(this.#own.hop) : randomHop(); + this.hop = hasRoutes(version) && this.#own ? toHop(this.#own.hop) : randomHop(); // What the peer's connection credential earns by default: publishing anything to us, // since we consume on demand, and subscribing to whatever we publish. this.#auth = new AuthSession({ @@ -439,7 +439,7 @@ export class Connection implements Session { const routeKey = hasRouteKey(this.#version) ? await proveRouteKey(this.#quic, this.#client) : undefined; await new Setup({ probe, - hop: hasRoutes(this.#version) ? this.#own && HopSchema.parse(this.#own.node) : this.hop, + hop: hasRoutes(this.#version) ? this.#own && toHop(this.#own.node) : this.hop, token: this.#token, implementation: this.#implementation, routeKey, diff --git a/js/net/src/lite/setup.test.ts b/js/net/src/lite/setup.test.ts index 0ac430ce02d..2111f82702c 100644 --- a/js/net/src/lite/setup.test.ts +++ b/js/net/src/lite/setup.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { HopSchema } from "../hop.ts"; +import { toHop } from "../hop.ts"; import { encodeVarint, Reader, Writer } from "../stream.ts"; import * as Varint from "../varint.ts"; import { ProbeLevel, Role, Setup } from "./setup.ts"; @@ -138,7 +138,7 @@ test("unknown probe level saturates to Increase", async () => { }); test("SETUP with hop round-trips", async () => { - const hop = HopSchema.parse(42n); + const hop = toHop(42n); const got = await roundTrip(new Setup({ hop })); expect(got.hop).toBe(hop); }); @@ -153,17 +153,17 @@ test("lite-07 Node ID is never 0 or qualified", async () => { for (const id of [0n, (1n << 63n) | 7n]) { await expect(decodeParam(PARAM_HOP, encodeVarint(id, Version.DRAFT_07), Version.DRAFT_07)).rejects.toThrow(); } - const qualified = new Setup({ hop: HopSchema.parse((1n << 63n) | 7n) }); + const qualified = new Setup({ hop: toHop((1n << 63n) | 7n) }); await expect(bytes((w) => qualified.encode(w, Version.DRAFT_07), Version.DRAFT_07)).rejects.toThrow(); }); test("SETUP with implementation round-trips", async () => { const got = await roundTrip( - new Setup({ hop: HopSchema.parse(7n), implementation: "moq-ffi/0.4.12 moq-net-rs/0.3.10" }), + new Setup({ hop: toHop(7n), implementation: "moq-ffi/0.4.12 moq-net-rs/0.3.10" }), Version.DRAFT_07, ); expect(got.implementation).toBe("moq-ffi/0.4.12 moq-net-rs/0.3.10"); - expect(got.hop).toBe(HopSchema.parse(7n)); + expect(got.hop).toBe(toHop(7n)); }); test("an empty implementation is omitted rather than encoded", async () => { diff --git a/js/net/src/lite/setup.ts b/js/net/src/lite/setup.ts index 68b7d2c1662..63c665e77ed 100644 --- a/js/net/src/lite/setup.ts +++ b/js/net/src/lite/setup.ts @@ -5,7 +5,7 @@ * @module */ -import { type Hop, HopSchema, wireHop } from "../hop.ts"; +import { type Hop, toHop, wireHop } from "../hop.ts"; import { encodeVarint, Reader, type Writer } from "../stream.ts"; import { decodeUtf8 } from "../util/utf8.ts"; import * as Message from "./message.ts"; @@ -313,7 +313,7 @@ export class Setup { if (hopRaw !== undefined && hasRoutes(version) && (hopRaw === 0n || hopRaw >= QUALIFIED)) { throw new Error("setup Node ID must be non-zero and unqualified"); } - const hop = hopRaw === undefined || hopRaw === 0n ? undefined : HopSchema.parse(hopRaw); + const hop = hopRaw === undefined || hopRaw === 0n ? undefined : toHop(hopRaw); // An older version does not know the token parameter, so it ignores it like any other. const token = hasAuth(version) ? params.getBytes(PARAM_TOKEN) : undefined; diff --git a/js/net/src/lite/subscriber.test.ts b/js/net/src/lite/subscriber.test.ts index 212fd5e044a..d08b0838efa 100644 --- a/js/net/src/lite/subscriber.test.ts +++ b/js/net/src/lite/subscriber.test.ts @@ -22,7 +22,7 @@ import { toTransport, } from "../error.ts"; import type { Consumer as GroupConsumer } from "../group.ts"; -import { type Hop, HopSchema, isAnonymous, MAX_HOPS, UNKNOWN_HOP, WireRoute } from "../hop.ts"; +import { type Hop, isAnonymous, MAX_HOPS, toHop, UNKNOWN_HOP, WireRoute } from "../hop.ts"; import * as Instance from "../instance.ts"; import { hooks, rendezvousHash } from "../internal.ts"; import { GRACE } from "../ledger.ts"; @@ -71,7 +71,7 @@ test("closing the subscriber suppresses probe stream warnings", async () => { writable: new WritableStream(), }), } as unknown as WebTransport; - const subscriber = new Subscriber(quic, Version.DRAFT_03, HopSchema.parse(1n), new Signal({})); + const subscriber = new Subscriber(quic, Version.DRAFT_03, toHop(1n), new Signal({})); const warn = spyOn(console, "warn").mockImplementation(() => {}); try { @@ -125,7 +125,7 @@ function announceHarness(version: Version, origin = 1n) { }, } as unknown as WebTransport; - const subscriber = new Subscriber(quic, version, HopSchema.parse(origin)); + const subscriber = new Subscriber(quic, version, toHop(origin)); const send = async (f: (w: Writer) => Promise) => { const written: Uint8Array[] = []; @@ -183,10 +183,10 @@ function announceHarness(version: Version, origin = 1n) { }; } -const PUBLISHER_A = HopSchema.parse(7n); -const PUBLISHER_B = HopSchema.parse(8n); -const PUBLISHER_C = HopSchema.parse(9n); -const PEER = HopSchema.parse(2n); +const PUBLISHER_A = toHop(7n); +const PUBLISHER_B = toHop(8n); +const PUBLISHER_C = toHop(9n); +const PEER = toHop(2n); // Lite-07 origin nodes, and the route a peer advertises to each. const NODE_A = 0x7an; @@ -234,7 +234,7 @@ test("an announce consumer closed while its stream opens sends nothing on it", a }; }, } as unknown as WebTransport; - const subscriber = new Subscriber(quic, Version.DRAFT_06, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_06, toHop(1n)); const announced = subscriber.routes(Path.Pattern.subtree(Path.from("room"))); announced.close(); @@ -255,7 +255,7 @@ test("a max-length chain plus withheld responder is dropped", async () => { const announced = subscriber.routes(); await settle(); - const hops = Array.from({ length: MAX_HOPS }, (_, i) => HopSchema.parse(BigInt(i + 1))); + const hops = Array.from({ length: MAX_HOPS }, (_, i) => toHop(BigInt(i + 1))); await send((w) => new AnnounceOk(UNKNOWN_HOP, 0).encode(w, Version.DRAFT_06)); await send((w) => encodeAnnounceBroadcast(w, { status: "active", suffix: Path.from("full"), hops }, Version.DRAFT_06), @@ -509,7 +509,7 @@ test("a lite-05 duplicate announce follows the same update rule", async () => { await settle(); await send((w) => new AnnounceOk(PEER, 0).encode(w, Version.DRAFT_05)); - const active = (hops: ReturnType[]) => (w: Writer) => + const active = (hops: Hop[]) => (w: Writer) => encodeAnnounceBroadcast(w, { status: "active", suffix: Path.from("room"), hops }, Version.DRAFT_05); await send(active([PUBLISHER_A])); @@ -591,7 +591,7 @@ async function runProbeScript(version: Version, probes: Probe[], initial: ProbeS } as unknown as WebTransport; const signal = new Signal(initial); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n), signal); + const subscriber = new Subscriber(quic, version, toHop(1n), signal); const running = subscriber.runProbe(); await Promise.resolve(); @@ -646,7 +646,7 @@ test("an announce skipped as a reflected loop still holds its path", async () => await send((w) => encodeAnnounceBroadcast( w, - { status: "active", suffix: Path.from("room"), hops: [HopSchema.parse(SELF)] }, + { status: "active", suffix: Path.from("room"), hops: [toHop(SELF)] }, Version.DRAFT_06, ), ); @@ -687,7 +687,7 @@ test("an update replaces an announce that was skipped as a reflected loop", asyn await send((w) => encodeAnnounceBroadcast( w, - { status: "active", suffix: Path.from("room"), hops: [HopSchema.parse(SELF)] }, + { status: "active", suffix: Path.from("room"), hops: [toHop(SELF)] }, Version.DRAFT_06, ), ); @@ -717,7 +717,7 @@ test("retiring an id whose announce was skipped ends nothing", async () => { await send((w) => encodeAnnounceBroadcast( w, - { status: "active", suffix: Path.from("room"), hops: [HopSchema.parse(SELF)] }, + { status: "active", suffix: Path.from("room"), hops: [toHop(SELF)] }, Version.DRAFT_06, ), ); @@ -782,7 +782,7 @@ test("a duplicate start is reported even when its own route reflects", async () await send((w) => encodeAnnounceBroadcast( w, - { status: "active", suffix: Path.from("room"), hops: [HopSchema.parse(SELF)] }, + { status: "active", suffix: Path.from("room"), hops: [toHop(SELF)] }, Version.DRAFT_06, ), ); @@ -1068,7 +1068,7 @@ test.each([ ["a stream slot for the FETCH", "open", undefined], ] as const)("closing the subscriber rejects a fetch waiting on %s", async (_, stage, cause) => { const { quic, streams, opened } = fakeSession(stage === "open" ? [1] : []); - const subscriber = new Subscriber(quic, Version.DRAFT_05, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_05, toHop(1n)); let settled = false; const fetch = subscriber.fetchGroup(Path.from("room"), "video", 0n).then( @@ -1117,7 +1117,7 @@ test.each([ const installed = clock.install(); const warn = spyOn(console, "warn").mockImplementation(() => {}); const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); try { const track = subscriber.consume(Path.from("room")).track("video").subscribe(); await opened(0); @@ -1155,7 +1155,7 @@ test("a lite subscribe waiting on a stream slot for the SUBSCRIBE outlasts the d const installed = clock.install(); const warn = spyOn(console, "warn").mockImplementation(() => {}); const { quic, streams, opened } = fakeSession([1]); - const subscriber = new Subscriber(quic, Version.DRAFT_05, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_05, toHop(1n)); try { const track = subscriber.consume(Path.from("room")).track("video").subscribe(); await opened(0); @@ -1180,7 +1180,7 @@ test("a lite subscribe waiting on a stream slot for the SUBSCRIBE outlasts the d // for it goes unused to the next open, rather than being reset. test("a lite SUBSCRIBE open given up leaves its stream to the next open", async () => { const { quic, streams, opened } = fakeSession([1]); - const subscriber = new Subscriber(quic, Version.DRAFT_05, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_05, toHop(1n)); const warn = spyOn(console, "warn").mockImplementation(() => {}); try { // Closing the broadcast retires the setup while its SUBSCRIBE waits for a stream. @@ -1209,7 +1209,7 @@ test("a lite SUBSCRIBE open given up leaves its stream to the next open", async // Leaving during SUBSCRIBE setup releases its TRACK bridge while the broadcast stays live. test.each(["credit", "answer"] as const)("abandoning SUBSCRIBE during %s releases TRACK", async (stage) => { const { quic, streams, opened } = fakeSession(stage === "credit" ? [1] : []); - const subscriber = new Subscriber(quic, Version.DRAFT_07, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_07, toHop(1n)); const warn = spyOn(console, "warn").mockImplementation(() => {}); const room = subscriber.consume(Path.from("room")); try { @@ -1242,7 +1242,7 @@ test.each(["credit", "answer"] as const)("abandoning SUBSCRIBE during %s release // the stream admitted for it goes unused to the next open. test("a lite subscribe whose readers leave while it waits for a stream gives up the wait", async () => { const { quic, streams, opened } = fakeSession([0]); - const subscriber = new Subscriber(quic, Version.DRAFT_05, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_05, toHop(1n)); const warn = spyOn(console, "warn").mockImplementation(() => {}); const room = subscriber.consume(Path.from("room")); try { @@ -1271,7 +1271,7 @@ test("a lite subscribe abandoned while its SUBSCRIBE write stalls closes its TRA const installed = clock.install(); const warn = spyOn(console, "warn").mockImplementation(() => {}); const { quic, streams, opened } = fakeSession([], [1]); - const subscriber = new Subscriber(quic, Version.DRAFT_05, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_05, toHop(1n)); try { const track = subscriber.consume(Path.from("room")).track("video").subscribe(); await opened(0); @@ -1300,7 +1300,7 @@ test.each( )("$name: a subscribe goes out with its track (forced yields: $forced)", async ({ version, forced }) => { const yielding = forced ? spyOn(Budget.prototype, "poll").mockImplementation(() => yieldNow()) : undefined; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const track = subscriber .consume(Path.from("room")) .track("video") @@ -1343,7 +1343,7 @@ test.each( test("a group that beats its track info waits for it", async () => { const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const track = subscriber.consume(Path.from("room")).track("video").subscribe(); try { await opened(0); @@ -1405,7 +1405,7 @@ function handStream(version: Version) { test.each([false, true])("a yielded group continues without loss (overtakes: %p)", async (overtakes) => { const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const track = subscriber .consume(Path.from("room")) .track("video") @@ -1469,7 +1469,7 @@ test.each([false, true])("a yielded group continues without loss (overtakes: %p) test("a group yielded twice continues without loss", async () => { const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const track = subscriber .consume(Path.from("room")) .track("video") @@ -1519,7 +1519,7 @@ test("a group yielded twice continues without loss", async () => { test("a yielded group a drop named ends", async () => { const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const track = subscriber .consume(Path.from("room")) .track("video") @@ -1564,7 +1564,7 @@ test("a yielded group a drop named ends", async () => { test("a yielded group pauses once an update supersedes its stale drop", async () => { const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const track = subscriber .consume(Path.from("room")) .track("video") @@ -1611,7 +1611,7 @@ test("a yielded group pauses once an update supersedes its stale drop", async () test("a yielded group pauses once an update supersedes a stale drop before its header", async () => { const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const track = subscriber .consume(Path.from("room")) .track("video") @@ -1660,7 +1660,7 @@ test.each(["zero length", "resized", "unfinished", "past held"] as const)( async (fault) => { const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const track = subscriber .consume(Path.from("room")) .track("video") @@ -1716,7 +1716,7 @@ test.each(["zero length", "resized", "unfinished", "past held"] as const)( test("a lite-06 group reset with YIELDED ends", async () => { const version = Version.DRAFT_06; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const track = subscriber.consume(Path.from("room")).track("video").subscribe(); try { await opened(0); @@ -1747,7 +1747,7 @@ test("a lite-06 group reset with YIELDED ends", async () => { test.each([false, true])("a duplicate of an arriving copy waits for it to settle (first fails: %p)", async (fails) => { const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const track = subscriber.consume(Path.from("room")).track("video").subscribe(); try { await opened(0); @@ -1850,7 +1850,7 @@ test.each([false, true])("a duplicate of an arriving copy waits for it to settle test("a reset track rejects the subscription and resets its subscribe", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, Version.DRAFT_07, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_07, toHop(1n)); const track = subscriber.consume(Path.from("room")).track("video").subscribe(); try { await opened(0); @@ -1867,7 +1867,7 @@ test("a reset track rejects the subscription and resets its subscribe", async () test("a fetch started after the subscriber closes rejects without opening a stream", async () => { const { quic, streams } = fakeSession(); - const subscriber = new Subscriber(quic, Version.DRAFT_05, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_05, toHop(1n)); subscriber.close(); const err = await subscriber.fetchGroup(Path.from("room"), "video", 0n).catch((err: unknown) => err); @@ -1884,15 +1884,7 @@ test("a grant that shrinks while the subscription sets up refuses it", async () subscribe: new Path.Patterns([Path.Pattern.subtree(prefix)]), }); const grant = new Signal(scoped("room")); - const subscriber = new Subscriber( - quic, - Version.DRAFT_05, - HopSchema.parse(1n), - undefined, - undefined, - undefined, - grant, - ); + const subscriber = new Subscriber(quic, Version.DRAFT_05, toHop(1n), undefined, undefined, undefined, grant); const track = subscriber.consume(Path.from("room/cam")).track("video").subscribe().ordered(); const next = track.nextGroup().catch((err: unknown) => err); @@ -1913,7 +1905,7 @@ test("a grant that shrinks while the subscription sets up refuses it", async () test("an already-aborted fetch rejects without opening a stream", async () => { const { quic, streams } = fakeSession(); - const subscriber = new Subscriber(quic, Version.DRAFT_05, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_05, toHop(1n)); const cause = new Error("gone"); const err = await subscriber @@ -1927,7 +1919,7 @@ test("an already-aborted fetch rejects without opening a stream", async () => { // and its response is read only once TRACK_INFO says the timescale. test("the first FETCH goes out before TRACK_INFO answers", async () => { const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, Version.DRAFT_05, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_05, toHop(1n)); let fetched: GroupConsumer | undefined; const fetch = subscriber.fetchGroup(Path.from("room"), "video", 0n).then((group) => { @@ -1951,7 +1943,7 @@ test("the first FETCH goes out before TRACK_INFO answers", async () => { test("a failed TRACK_INFO fails the FETCH sent alongside it", async () => { const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, Version.DRAFT_05, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_05, toHop(1n)); const fetch = subscriber.fetchGroup(Path.from("room"), "video", 0n).catch((err: unknown) => err); await opened(0); @@ -1969,7 +1961,7 @@ test("a failed TRACK_INFO fails the FETCH sent alongside it", async () => { // stream is cancelled once the last sharer leaves, before its FETCH is sent if it can be. test("one of two fetch sharers aborting leaves the other's fetch", async () => { const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, Version.DRAFT_05, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_05, toHop(1n)); const controller = new AbortController(); const a = subscriber.fetchGroup(Path.from("room"), "video", 0n, { signal: controller.signal }); @@ -2002,7 +1994,7 @@ test.each([ ["the FETCH", "fetch"], ] as const)("the last fetch sharer aborting during %s cancels it", async (_, stage) => { const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, Version.DRAFT_05, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_05, toHop(1n)); const first = new AbortController(); const second = new AbortController(); @@ -2042,7 +2034,7 @@ test.each([ test("a fetch after the last sharer left is never failed with the cancelled one", async () => { for (let depth = 0; depth < 32; depth++) { const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, Version.DRAFT_05, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_05, toHop(1n)); const controller = new AbortController(); const a = subscriber.fetchGroup(Path.from("room"), "video", 0n, { signal: controller.signal }); @@ -2081,7 +2073,7 @@ test("a fetch after the last sharer left is never failed with the cancelled one" // old one's, even while the old FETCH is still open. test("a fresh consume never joins a fetch an earlier one opened", async () => { const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, Version.DRAFT_05, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_05, toHop(1n)); const room = Path.from("room"); const old = subscriber.consume(room); @@ -2111,7 +2103,7 @@ test("a fresh consume never joins a fetch an earlier one opened", async () => { // must not end clean, as a FIN would make it read whole. test("the last reader leaving mid-response cancels the fetch", async () => { const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, Version.DRAFT_05, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_05, toHop(1n)); const fetch = subscriber.fetchGroup(Path.from("room"), "video", 0n); await opened(0); @@ -2140,15 +2132,7 @@ test.each(["initial", "track", "fetch", "body"] as const)( subscribe: new Path.Patterns([Path.Pattern.subtree(prefix)]), }); const grant = new Signal(scoped(stage === "initial" ? "other" : "room")); - const subscriber = new Subscriber( - quic, - Version.DRAFT_05, - HopSchema.parse(1n), - undefined, - undefined, - undefined, - grant, - ); + const subscriber = new Subscriber(quic, Version.DRAFT_05, toHop(1n), undefined, undefined, undefined, grant); let result: unknown; const pending = subscriber.fetchGroup(Path.from("room/cam"), "video", 0n).then( (group) => { @@ -2201,7 +2185,7 @@ test.each([Version.DRAFT_05, Version.DRAFT_06])( "a retired handle on a wire without instances refuses new metadata on %s", async (version) => { const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const announced = subscriber.routes(); await opened(0); const send = async (encode: (writer: Writer) => Promise) => { @@ -2321,7 +2305,7 @@ test.each([ ] as const)("an unpinned SUBSCRIBE %s at a replacement or withdrawal", async (_, version, outcome) => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const announced = subscriber.routes(); try { await opened(0); @@ -2372,7 +2356,7 @@ test("a withdrawal while the subscribe opens closes the answered track", async ( const version = Version.DRAFT_06; const warn = spyOn(console, "warn").mockImplementation(() => {}); const { quic, streams, opened } = fakeSession([2]); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const announced = subscriber.routes(); try { await opened(0); @@ -2418,7 +2402,7 @@ test("a listing whose readers leave as its token settles never reaches the wire" const subscriber = new Subscriber( quic, Version.DRAFT_07, - HopSchema.parse(1n), + toHop(1n), undefined, undefined, undefined, @@ -2441,7 +2425,7 @@ test.each(["track", "fetch", "open"] as const)( "retirement settles coalesced fetches during %s setup", async (stage) => { const { quic, streams, opened } = fakeSession(stage === "open" ? [1] : []); - const subscriber = new Subscriber(quic, Version.DRAFT_06, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_06, toHop(1n)); const retired = new AbortController(); const consumed = { id: 1, valid: retired.signal }; const path = Path.from("room"); @@ -2474,7 +2458,7 @@ test.each(["track", "fetch", "open"] as const)( test("retirement preserves an accepted fetch and its coalesced reads", async () => { const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, Version.DRAFT_06, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_06, toHop(1n)); const retired = new AbortController(); const consumed = { id: 1, valid: retired.signal }; const path = Path.from("room"); @@ -2499,7 +2483,7 @@ test("retirement preserves an accepted fetch and its coalesced reads", async () test("consumes resolve the serving prefix and pin its instance", async () => { const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const announced = subscriber.routes(); await opened(0); const peer = new Writer( @@ -2588,7 +2572,7 @@ test.each([Version.DRAFT_05, Version.DRAFT_06])( "pending metadata cancels on selection change and a live fallback can request again on %s", async (version) => { const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const announced = subscriber.routes(); await opened(0); const peer = new Writer( @@ -2642,7 +2626,7 @@ test.each([Version.DRAFT_05, Version.DRAFT_06])( test("a cancelled queued PROBE open sends no request and leaves its slot to the next open", async () => { const { quic, streams, opened } = fakeSession([0]); const signal = new Signal({}); - const subscriber = new Subscriber(quic, Version.DRAFT_03, HopSchema.parse(1n), signal); + const subscriber = new Subscriber(quic, Version.DRAFT_03, toHop(1n), signal); const abort = new AbortController(); const probing = subscriber.runProbe(abort.signal); await opened(0); @@ -2678,7 +2662,7 @@ function drainReactions(): Promise { test("a local unsubscribe owes no SUBSCRIBE_FINISH", async () => { const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, Version.DRAFT_07, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_07, toHop(1n)); const responseTask = Promise.withResolvers(); const outcome = responseTask.promise.then( () => undefined, @@ -2758,7 +2742,7 @@ test.each( ), )("subscription waits release losing signal listeners on %s after %s", async (version, stop) => { const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const counters: ReturnType[] = []; // Observe the accepted producer before its update loop starts, without exporting a test hook. const internal = subscriber as unknown as { @@ -2811,7 +2795,7 @@ test.each( test.each([0, 5, 9000])("a received group numbers its frames from transport offset %s", async (frameStart) => { const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const broadcast = subscriber.consume(Path.from("room")); const consumer = broadcast.track("video"); const early = consumer.subscribe(); @@ -2872,7 +2856,7 @@ async function groupStream(timestamp: number, version: Version = Version.DRAFT_0 // of order is accepted with its timestamp. test.each([Version.DRAFT_05, Version.DRAFT_06])("version %p passes received timestamps through", async (version) => { const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const broadcast = subscriber.consume(Path.from("room")); // Old enough to keep every group, however far behind the newest start. const track = broadcast.track("video").subscribe({ delay: { max: Duration.millis(60_000) } }); @@ -2909,7 +2893,7 @@ test.each([Version.DRAFT_05, Version.DRAFT_06])("version %p passes received time test("a lite-07 rewind is refused", async () => { const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const broadcast = subscriber.consume(Path.from("room")); const track = broadcast.track("video").subscribe({ delay: { max: Duration.millis(60_000) } }); try { @@ -2931,7 +2915,7 @@ test("a lite-07 rewind is refused", async () => { test("a publisher FIN without SUBSCRIBE_FINISH still violates an open subscription", async () => { const { quic, streams, opened, closes } = fakeSession(); - const subscriber = new Subscriber(quic, Version.DRAFT_07, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_07, toHop(1n)); const broadcast = subscriber.consume(Path.from("room")); const track = broadcast.track("video").subscribe(); try { @@ -2953,7 +2937,7 @@ test("a publisher FIN without SUBSCRIBE_FINISH still violates an open subscripti // Our SUBSCRIBE carries one range, so a lite-07 SUBSCRIBE_START with any other count is malformed. test.each([[[]], [[0, 5]]])("a lite-07 SUBSCRIBE_START resolving %j violates the protocol", async (starts) => { const { quic, streams, opened, closes } = fakeSession(); - const subscriber = new Subscriber(quic, Version.DRAFT_07, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_07, toHop(1n)); const broadcast = subscriber.consume(Path.from("room")); const track = broadcast.track("video").subscribe(); try { @@ -2977,7 +2961,7 @@ test.each([[[]], [[0, 5]]])("a lite-07 SUBSCRIBE_START resolving %j violates the test("a widened range's SUBSCRIBE_STARTED resolves the feed's start", async () => { const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const broadcast = subscriber.consume(Path.from("room")); const track = broadcast.track("video").subscribe({ ranges: [{ start: { absolute: 0n }, end: { absolute: 1n } }] }); try { @@ -3010,7 +2994,7 @@ test("a widened range's SUBSCRIBE_STARTED resolves the feed's start", async () = test("a group wins over its stale drop on lite-07", async () => { const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); type Entry = { track: Producer; tail: { covers(start: bigint, end: bigint): boolean; open(sequence: bigint): () => void }; @@ -3094,7 +3078,7 @@ test("a finished group wins over a late stale drop once evicted on lite-07", asy const installed = clock.install(); const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); type Entry = { track: Producer; tail: { @@ -3188,7 +3172,7 @@ test("a finished group wins over a late stale drop once evicted on lite-07", asy test("a skip or final drop replaces an earlier stale one on lite-07", async () => { const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); type Entry = { track: Producer; tail: { covers(start: bigint, end: bigint): boolean } }; let entry: Entry | undefined; const internal = subscriber as unknown as { @@ -3250,7 +3234,7 @@ test("a skip or final drop replaces an earlier stale one on lite-07", async () = test("a skip replaces a final drop but not a cached group on lite-07", async () => { const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); type Entry = { track: Producer; tail: { covers(start: bigint, end: bigint): boolean } }; let entry: Entry | undefined; const internal = subscriber as unknown as { @@ -3328,7 +3312,7 @@ test.each( const clock = new Manual(); const installed = clock.install(); const { quic, streams, opened, closes } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const broadcast = subscriber.consume(Path.from("room")); const track = broadcast.track("video").subscribe(); try { @@ -3367,7 +3351,7 @@ test.each([ ] as const)("a session death before the tail settles: %s", async (_, version, settled) => { const installed = new Manual().install(); const { quic, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const broadcast = subscriber.consume(Path.from("room")); const track = broadcast.track("video").subscribe(); const died = new Error("session died"); @@ -3420,7 +3404,7 @@ test.each([ ["lite-07 reset", Version.DRAFT_07, "reset"], ] as const)("an update the publisher stopped reading defers to its %s", async (_, version, end) => { const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const broadcast = subscriber.consume(Path.from("room")); const track = broadcast.track("video").subscribe(); try { @@ -3468,7 +3452,7 @@ test.each([ // track. Lite-05 sends the start group plus one, past the largest u62 here. test("an update whose bound the wire can't carry fails the track", async () => { const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, Version.DRAFT_05, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_05, toHop(1n)); const broadcast = subscriber.consume(Path.from("room")); const track = broadcast.track("video").subscribe(); try { @@ -3489,7 +3473,7 @@ test("an update whose bound the wire can't carry fails the track", async () => { test("a lite-07 drop naming an unsent update closes the session", async () => { const version = Version.DRAFT_07; const { quic, streams, opened, closes } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const broadcast = subscriber.consume(Path.from("room")); const track = broadcast.track("video").subscribe(); try { @@ -3521,7 +3505,7 @@ test("a lite-07 drop naming an unsent update closes the session", async () => { test("an unknown subscribe response type closes the session", async () => { const { quic, streams, opened, closes } = fakeSession(); - const subscriber = new Subscriber(quic, Version.DRAFT_07, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_07, toHop(1n)); const broadcast = subscriber.consume(Path.from("room")); const track = broadcast.track("video").subscribe(); try { @@ -3542,7 +3526,7 @@ test("an unknown subscribe response type closes the session", async () => { test("closing a broadcast while TRACK_INFO is pending leaves no unhandled rejection", async () => { const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, Version.DRAFT_07, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_07, toHop(1n)); const unhandled: unknown[] = []; const onUnhandled = (reason: unknown) => unhandled.push(reason); const broadcast = subscriber.consume(Path.from("room")); @@ -3664,7 +3648,7 @@ test.each(["answer", "credit"] as const)("FETCH waiting for %s ends with its cal const clock = new Manual(); const installed = clock.install(); const { quic, streams, opened } = fakeSession(stage === "credit" ? [1] : []); - const subscriber = new Subscriber(quic, Version.DRAFT_07, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_07, toHop(1n)); const cancel = new AbortController(); let failure: unknown; const fetch = subscriber @@ -3747,7 +3731,7 @@ function probeTargetHarness(level: ProbeLevel, options?: { failTarget?: boolean; }), } as unknown as WebTransport; const peerSetup = new Signal(new Setup({ probe: level })); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n), new Signal({}), peerSetup); + const subscriber = new Subscriber(quic, version, toHop(1n), new Signal({}), peerSetup); return { subscriber, sent, @@ -3904,7 +3888,7 @@ test("an interleaved replacement mints a fresh instance", () => { // Reader demand applies inside a frame too, including when its peer never sends another byte. test("a FETCH stops a stalled frame only after its last coalesced reader leaves", async () => { const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, Version.DRAFT_05, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, Version.DRAFT_05, toHop(1n)); try { const a = subscriber.fetchGroup(Path.from("room"), "video", 0n); const b = subscriber.fetchGroup(Path.from("room"), "video", 0n); @@ -3950,7 +3934,7 @@ test("a cancelled legacy datagram lookup cannot refuse a stream answer arriving const subscriber = new Subscriber( quic, version, - HopSchema.parse(1n), + toHop(1n), undefined, undefined, undefined, @@ -3993,7 +3977,7 @@ async function routedStream(options?: RouteOptions, getStats?: () => Promise { const announced = subscriber.routes(scope, options); const stream = await opened(index); diff --git a/js/net/src/origin.test.ts b/js/net/src/origin.test.ts index 6184045958b..41e8aaead47 100644 --- a/js/net/src/origin.test.ts +++ b/js/net/src/origin.test.ts @@ -4,7 +4,7 @@ import { getter, Once, race, Signal } from "@moq/signals"; import { announcedView } from "./announced.test-util"; import { type Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts"; import { StreamCode, StreamError } from "./error.ts"; -import { type Cost, HopSchema, WireRoute } from "./hop.ts"; +import { type Cost, toHop, WireRoute } from "./hop.ts"; import * as Instance from "./instance.ts"; import { chainHash, compareRouteCandidates, presented, rendezvousHash, spreadHash } from "./internal.ts"; import { SessionBroadcast, textFrame } from "./mock.ts"; @@ -22,7 +22,7 @@ function publish(origin: Producer, path: Path.Valid) { } /** A peer's hop, for a route that is not local. */ -const PEER = HopSchema.parse(10n); +const PEER = toHop(10n); // One publisher instance, so a local broadcast and a remote route compete on cost alone. const INSTANCE = Instance.parse("01900000-0000-7000-8000-000000000001"); @@ -2117,7 +2117,7 @@ test("a lite-07 and a lite-06 route beneath one prefix rank by each one's own ke const job = Path.from("pool/job"); const pool = Path.from("pool"); const claim = { ...WireRoute.default, instance: Instance.parse("a"), node: 0x7an, cost: 1n }; - const legacy = { ...WireRoute.default, instance: Instance.parse("b"), hops: [HopSchema.parse(11n)], cost: 1n }; + const legacy = { ...WireRoute.default, instance: Instance.parse("b"), hops: [toHop(11n)], cost: 1n }; expect(rendezvousHash(job, 0x7an)).toBe(0xc376be7bf47aebbfn); expect(spreadHash(job, "b")).toBe(0xd16a3821c67a2d25n); expect(compareRouteCandidates(job, pool, claim, legacy)).toBeLessThan(0); @@ -2148,7 +2148,7 @@ test("the spread hash matches rs/moq-net byte for byte", () => { }); test("an equal-cost pool spreads its paths the same way on every node", async () => { - const workers = [10n, 11n, 12n, 13n].map((id) => HopSchema.parse(id)); + const workers = [10n, 11n, 12n, 13n].map((id) => toHop(id)); const paths = Array.from({ length: 64 }, (_, i) => Path.from(`pool/job-${i}`)); // The worker each path resolves to on an origin whose pool arrived in `order`. @@ -2193,7 +2193,7 @@ test("an equal-cost replacement at its own path wins whatever its hop", async () for (const order of [ [11n, 10n], [10n, 11n], - ].map((hops) => hops.map((id) => HopSchema.parse(id)))) { + ].map((hops) => hops.map((id) => toHop(id)))) { const origin = new Producer(); const served: bigint[] = []; const handles = order.map((hop) => { diff --git a/js/net/src/request-deadline.test.ts b/js/net/src/request-deadline.test.ts index f37e2905d33..cb0eba142df 100644 --- a/js/net/src/request-deadline.test.ts +++ b/js/net/src/request-deadline.test.ts @@ -2,7 +2,7 @@ import { expect, test } from "bun:test"; import { Duration } from "@moq/clock"; import { Manual } from "@moq/clock/test"; import { SessionCode, SessionError } from "./error.ts"; -import { HopSchema } from "./hop.ts"; +import { toHop } from "./hop.ts"; import { NativeSession } from "./ietf/session.ts"; import { Subscriber as IetfSubscriber } from "./ietf/subscriber.ts"; import { Version as Ietf } from "./ietf/version.ts"; @@ -59,7 +59,7 @@ for (const protocol of ["lite", "ietf"] as const) { const transport = limited(mode); const subscriber = protocol === "lite" - ? new LiteSubscriber(transport.quic, Lite.DRAFT_07, HopSchema.parse(1n)) + ? new LiteSubscriber(transport.quic, Lite.DRAFT_07, toHop(1n)) : new IetfSubscriber({ session: new NativeSession(transport.quic, Ietf.DRAFT_18, true) }); const broadcast = subscriber.consume(Path.from("room")); const track = broadcast.track("video").subscribe(); @@ -96,7 +96,7 @@ for (const protocol of ["lite", "ietf"] as const) { const transport = limited("open"); const subscriber = protocol === "lite" - ? new LiteSubscriber(transport.quic, Lite.DRAFT_07, HopSchema.parse(1n)) + ? new LiteSubscriber(transport.quic, Lite.DRAFT_07, toHop(1n)) : new IetfSubscriber({ session: new NativeSession(transport.quic, Ietf.DRAFT_18, true) }); const broadcast = subscriber.consume(Path.from("room")); const cancel = new AbortController(); @@ -130,7 +130,7 @@ for (const operation of ["info", "fetch"] as const) { const clock = new Manual(); const installed = clock.install(); const transport = limited(mode); - const subscriber = new LiteSubscriber(transport.quic, Lite.DRAFT_07, HopSchema.parse(1n)); + const subscriber = new LiteSubscriber(transport.quic, Lite.DRAFT_07, toHop(1n)); const cancel = new AbortController(); let failure: unknown; const request = ( @@ -178,7 +178,7 @@ for (const protocol of ["lite", "ietf"] as const) { const transport = limited(mode); const subscriber = protocol === "lite" - ? new LiteSubscriber(transport.quic, Lite.DRAFT_07, HopSchema.parse(1n)) + ? new LiteSubscriber(transport.quic, Lite.DRAFT_07, toHop(1n)) : new IetfSubscriber({ session: new NativeSession(transport.quic, Ietf.DRAFT_18, true) }); const announced = subscriber.routes(); try { @@ -209,7 +209,7 @@ for (const protocol of ["lite", "ietf"] as const) { const transport = limited("queue"); const subscriber = protocol === "lite" - ? new LiteSubscriber(transport.quic, Lite.DRAFT_07, HopSchema.parse(1n)) + ? new LiteSubscriber(transport.quic, Lite.DRAFT_07, toHop(1n)) : new IetfSubscriber({ session: new NativeSession(transport.quic, Ietf.DRAFT_18, true) }); const broadcast = subscriber.consume(Path.from("room")); const track = broadcast.track("video").subscribe(); @@ -242,7 +242,7 @@ for (const protocol of ["lite", "ietf"] as const) { } as unknown as WebTransport; const subscriber = protocol === "lite" - ? new LiteSubscriber(quic, Lite.DRAFT_07, HopSchema.parse(1n)) + ? new LiteSubscriber(quic, Lite.DRAFT_07, toHop(1n)) : new IetfSubscriber({ quic, session: new NativeSession(quic, Ietf.DRAFT_18, true) }); const broadcast = subscriber.consume(Path.from("room")); const track = broadcast.track("video").subscribe(); diff --git a/js/net/src/resume.model.test.ts b/js/net/src/resume.model.test.ts index 3c59f6ebed2..70cefe8d426 100644 --- a/js/net/src/resume.model.test.ts +++ b/js/net/src/resume.model.test.ts @@ -18,7 +18,7 @@ import fc from "fast-check"; import { Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts"; import { NotFound, StreamCode, StreamError, TooFarBehind } from "./error.ts"; import type { Frame, Consumer as GroupConsumer, Producer as GroupProducer } from "./group.ts"; -import { HopSchema, WireRoute } from "./hop.ts"; +import { toHop, WireRoute } from "./hop.ts"; import * as Instance from "./instance.ts"; import { hooks } from "./internal.ts"; import { type Consumer as OriginConsumer, Producer as OriginProducer, type Requesting } from "./origin.ts"; @@ -450,7 +450,7 @@ class Model { if (publisher.routes[slot]) return; const route = WireRoute.normalize({ instance: INSTANCES[instance], - hops: [HopSchema.parse(BigInt(10 * (instance + 1) + slot))], + hops: [toHop(BigInt(10 * (instance + 1) + slot))], // The second instance's routes all undercut the first's. cost: BigInt((INSTANCES.length - instance) * SLOTS - slot), }); diff --git a/js/net/src/session-limits.test.ts b/js/net/src/session-limits.test.ts index af296baf1e1..ecb22a693b3 100644 --- a/js/net/src/session-limits.test.ts +++ b/js/net/src/session-limits.test.ts @@ -1,6 +1,6 @@ import { expect, spyOn, test } from "bun:test"; import { SessionCode, SessionError } from "./error.ts"; -import { HopSchema } from "./hop.ts"; +import { toHop } from "./hop.ts"; import { RequestOk } from "./ietf/request.ts"; import { SubscribeNamespaceEntry } from "./ietf/subscribe_namespace.ts"; import { Subscriber as IetfSubscriber } from "./ietf/subscriber.ts"; @@ -27,7 +27,7 @@ test.each(["lite", "ietf"] as const)("%s closes on the first advertisement beyon new WritableStream({ write: (chunk) => void chunks.push(chunk.slice()) }), version, ); - if (protocol === "lite") await new AnnounceOk(HopSchema.parse(2n), 0).encode(writer, LiteVersion.DRAFT_06); + if (protocol === "lite") await new AnnounceOk(toHop(2n), 0).encode(writer, LiteVersion.DRAFT_06); else { await writer.u53(RequestOk.id); await new RequestOk({}).encode(writer, IetfVersion.DRAFT_22); @@ -66,7 +66,7 @@ test.each(["lite", "ietf"] as const)("%s closes on the first advertisement beyon close: pair.server.close.bind(pair.server), } as unknown as WebTransport, LiteVersion.DRAFT_06, - HopSchema.parse(1n), + toHop(1n), undefined, undefined, undefined, diff --git a/js/qmux/api/index.api.md b/js/qmux/api/index.api.md index d17c3150b82..eda6aa58d5a 100644 --- a/js/qmux/api/index.api.md +++ b/js/qmux/api/index.api.md @@ -58,6 +58,7 @@ export class Session implements WebTransport { readonly ready: Promise; get reliability(): "reliable-only"; setSendBufferSize(bytes: number): void; + readonly transport: "websocket"; } export class SessionError extends Error implements Pick { diff --git a/js/qmux/src/session.test.ts b/js/qmux/src/session.test.ts index be2a8be6a7f..eebe9c0c3e1 100644 --- a/js/qmux/src/session.test.ts +++ b/js/qmux/src/session.test.ts @@ -276,6 +276,13 @@ function connect(config?: Config): { session: Session; peer: FakePeer } { const ORIGINAL_WSS = (globalThis as { WebSocketStream?: unknown }).WebSocketStream; +// @moq/net tells the fallback from native WebTransport by this label alone, without loading qmux. +test("a session labels its transport as websocket", () => { + const { session } = connect(); + expect(session.transport).toBe("websocket"); + session.close(); +}); + test("a non-finite sendBufferSize throws instead of parking every write", () => { (globalThis as { WebSocketStream?: unknown }).WebSocketStream = FakePeer; for (const sendBufferSize of [Number.NaN, Number.POSITIVE_INFINITY]) { diff --git a/js/qmux/src/session.ts b/js/qmux/src/session.ts index 95eb613c607..e6c4b6b6253 100644 --- a/js/qmux/src/session.ts +++ b/js/qmux/src/session.ts @@ -635,6 +635,8 @@ type End = /** 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. diff --git a/quest/m1/js-bundle-audit.md b/quest/m1/js-bundle-audit.md deleted file mode 100644 index 806912c37ca..00000000000 --- a/quest/m1/js-bundle-audit.md +++ /dev/null @@ -1,74 +0,0 @@ -# [M] Audit what the JS bundles carry - -## Goal - -Know what each consumer bundle the Nightly size report measures (`net`, `hang`, -`watch`, `watch-ui`, and `publish`, built by `sh/size/bundles.ts`) carries, and -shrink each by what can be split out, lazy-loaded, or dropped without changing -a package's behavior. Then Nightly's 30-day size comparison passes again, -either because the bundles shrank or because a post-growth report became its -anchor. - -## Plan - -Decided 2026-11-13 (maintainer, /quest-complete, in -[moq-dev/moq#8654](https://github.com/moq-dev/moq/pull/8654)): ✅ accept the JS -bundle growth as feature growth (lite-07 routes, the byte pool, Clock types) -and plan this audit (rejected: accepting it without an audit; holding until -the bundles shrink). The audit is not a gate on the acceptance. - -Measured 2026-11-13 on `main` at `a026b71b1`, built as Nightly does, against the -retained reports. After -[moq-dev/moq#8671](https://github.com/moq-dev/moq/pull/8671) dropped -`sorted-btree` and the test-only `Manual` clock from every bundle, brotli is -2% to 3% below the 11-13 report and still 9% to 12% above the 11-07 one: - -| Bundle | 10-22 | 11-07 | 11-13 | `main` | -|---|---:|---:|---:|---:| -| `net` | 98,909 | 136,880 | 157,282 | 153,149 | -| `hang` | 119,937 | 157,584 | 178,277 | 174,142 | -| `watch` | 133,560 | 175,294 | 196,114 | 192,662 | -| `watch-ui` | 144,409 | 186,072 | 206,966 | 203,518 | -| `publish` | 131,060 | 169,777 | 189,804 | 186,314 | - -Where the 30-day comparison (10%) stands, since the failure is the anchor, not -a new regression: - -- It starts failing on 2026-11-21 against the 10-22 report, where `main` is - 1.41x to 1.55x. The anchor then advances to the newest retained report at - least 30 days old, and every report before 11-07 is at least 10% below - `main` for every bundle. -- From 12-07 the 11-07 report is the anchor. `net` (1.119x) and `hang` - (1.105x) still fail by 1.7% and 0.5% of their size; `watch`, `watch-ui`, and - `publish` pass. This is the stretch the audit can clear. -- From 12-13 the 11-13 report is the anchor, and `main` passes unless it grows - again. -- Before 12-07 the anchors are the 10-22 to 11-06 reports, which `main` - exceeds by 13% (11-06) to 55% (10-22) for `net`. No non-breaking shrink - clears 11-21 to 11-30 (1.47x to 1.55x), so those nights are red by design, - and [Nightly artifact sizes](/sh/size/README.md) says the comparison is - neither waived nor reset (a reset deletes every series). Do not read them as - a new regression, and still read each night's other lines. - -Starting points, from the static chunks of the `main` metafiles (the lazy -chunks, such as the IETF stack and the libav polyfill, are already outside -them): - -- `net` is about 577 KB raw, 446 KB of it `js/net/dist`: `track.js` 56 KB, - `lite/subscriber.js` 45 KB, `lite/publisher.js` 30 KB, `origin.js` 30 KB, - `resume.js` 26 KB, `group.js` 18 KB. Then `pako` 42 KB, `js/qmux` 44 KB, and - `js/pattern` 14 KB. Does `pako` earn its size against `CompressionStream`? -- `hang`, `watch-ui`, and `publish` carry the same `net`, plus `zod` (37 to - 39 KB, against 9 KB in `net`), so what in `js/hang` pulls the larger part of - `zod` into every consumer is the first question. -- `watch-ui` adds 123 KB of `js/watch/dist` and `publish` 71 KB of - `js/publish/dist`; each is a bundle of its own to explain. - -Per package, record in the PR: what the bundle carries (the top inputs by -bytes), what can be split or lazy-loaded and what it costs a consumer, and what -the audit changed with before and after byte counts from `bundles.ts`. A change -that needs a breaking release for a published consumer, such as moving an export -behind a subpath, is its own m2 quest; the audit lands the non-breaking ones. -The thresholds stay as they are. - -Public API: none unless a finding says so. Wire: none. From c2c6196e2a243c1aff9d9a97b1d6a361dcb58890 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 13 Nov 2026 22:39:00 -0800 Subject: [PATCH 3/5] fix(net): load qmux only once the WebSocket fallback dials Co-Authored-By: Claude Opus 5.5 --- js/net/src/connection/connect.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/js/net/src/connection/connect.ts b/js/net/src/connection/connect.ts index 1009a90e11b..a2a8fc12ad1 100644 --- a/js/net/src/connection/connect.ts +++ b/js/net/src/connection/connect.ts @@ -954,12 +954,14 @@ async function connectWebSocket( cancel: Promise, options: QmuxOptions, ): Promise { - // qmux loads on demand, since most sessions win over WebTransport; fetch it during the head - // start so the fallback dials as soon as it would have. - const loaded = Promise.all([import("@moq/qmux"), sleep(delay)]); - const qmux = await race([cancel, loaded]); + const active = await race([cancel, sleep(delay).then(() => true)]); + if (!active) return undefined; + + // qmux loads only once the fallback dials, so a session WebTransport wins within its head + // start never downloads it. + const qmux = await race([cancel, import("@moq/qmux")]); if (!qmux) return undefined; - const [{ Session }] = qmux; + const { Session } = qmux; for (let wait = WEBSOCKET_REDIAL; ; wait = wait.mul(2)) { const quic = new Session(url, options); From 6e618410e0ae52b7c6260f4b4722cbb716aaefea Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 14 Nov 2026 09:27:42 -0800 Subject: [PATCH 4/5] docs(net): say the fallback chunk is skipped only within WebTransport's head start Co-Authored-By: Claude Opus 5.5 --- doc/lib/js/net.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/doc/lib/js/net.md b/doc/lib/js/net.md index 17119d4c02e..3b2b9325c1d 100644 --- a/doc/lib/js/net.md +++ b/doc/lib/js/net.md @@ -66,7 +66,8 @@ Examples: [`js/net/examples/`](https://github.com/moq-dev/moq/tree/main/js/net/examples). Runs in the browser and, over WebSocket, in Node, Bun, and Deno; see [server-side](/lib/js/#server-side). The WebSocket fallback and the moq-transport stack load -on demand as separate chunks, so a session over WebTransport and moq-lite never downloads them. +on demand as separate chunks, so a moq-lite session WebTransport wins within its head start +never downloads them. Path patterns are on the [concept page](/concept/moq-lite#path-patterns). From daf3f69554b382531049d5553697139b1ebb315d Mon Sep 17 00:00:00 2001 From: quest fixer Date: Sat, 14 Nov 2026 12:07:10 -0800 Subject: [PATCH 5/5] fix(net): complete hop constructor rename in merged tests --- js/net/src/lite/subscriber.test.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/js/net/src/lite/subscriber.test.ts b/js/net/src/lite/subscriber.test.ts index 905535418c2..632bdfb7e2e 100644 --- a/js/net/src/lite/subscriber.test.ts +++ b/js/net/src/lite/subscriber.test.ts @@ -1659,7 +1659,7 @@ test("a yielded group pauses once an update supersedes a stale drop before its h test.each(["continued", "dropped"] as const)("a reset without its code pauses the group (%s)", async (then) => { const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const track = subscriber .consume(Path.from("room")) .track("video") @@ -1721,7 +1721,7 @@ test.each([ const installed = clock.install(); const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const track = subscriber.consume(Path.from("room")).track("video").subscribe(); try { await opened(0); @@ -1778,7 +1778,7 @@ test("a stream whose gap the grace gave up on still holds the end", async () => const installed = clock.install(); const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const track = subscriber.consume(Path.from("room")).track("video").subscribe(); try { await opened(0); @@ -1825,7 +1825,7 @@ test("a recovery waits for the continuation of a group a reset without its code const installed = clock.install(); const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const consumed = subscriber.consume(Path.from("room")); const live = consumed.track("video").subscribe({ delay: { max: null } }); let history: ReturnType["subscribe"]> | undefined; @@ -1902,7 +1902,7 @@ test("an update restores the hold a stale drop excused", async () => { const installed = clock.install(); const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const track = subscriber.consume(Path.from("room")).track("video").subscribe(); try { await opened(0); @@ -1949,7 +1949,7 @@ test("an update while a continuation waits keeps its hold on the end", async () const installed = clock.install(); const version = Version.DRAFT_07; const { quic, streams, opened } = fakeSession(); - const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); + const subscriber = new Subscriber(quic, version, toHop(1n)); const track = subscriber.consume(Path.from("room")).track("video").subscribe(); try { await opened(0);