diff --git a/doc/lib/rs/moq-net.md b/doc/lib/rs/moq-net.md index 39fa0046481..8310beb727d 100644 --- a/doc/lib/rs/moq-net.md +++ b/doc/lib/rs/moq-net.md @@ -16,6 +16,7 @@ moq-transport at setup and presents one API either way. Media is a layer above What you use it for, beyond what the concept page already describes: - **An origin outlives the session.** `origin.route(path, options)` returns a `Route` that owns the broadcast to fill (`route.broadcast()`) and controls its announcement: `announce()`, `withdraw()`, `set_cost()`, and dropping the last clone retracts it. `origin.route_prefix(prefix, options)` serves requests beneath a prefix instead, each answered with `request.serve(held)`, `request.route(options)` (the path's own exact route) or `reject`. A standalone broadcast cannot announce; publish one only through a prefix route's `serve`. A reconnect announces existing routes again, and closing the session does not delete them. +- **Routes report what the mesh filled in.** An announcement's `route` gives its `instance()`, `cost()`, the hop ids it crossed (`hops()`, oldest first, 0 for an anonymous hop) and `is_anonymous()`; an application sets only `RouteOptions`. An origin's own hop id is `origin::Config::hop`, random unless a relay names one. - **Requests can pin an instance.** `consumer.request(path, Some(instance))` resolves only through a route announcing that [publisher instance](/concept/moq-lite#publisher-instances); `None` takes whichever route wins. The resolved consumer names its instance in `info().instance`, pinned or not. A route serves a random instance minted when it is created and kept across `withdraw()` and `announce()`; set one with `RouteOptions::with_instance(instance, epoch)` only for a publisher that continues its group sequences across restarts and raises the epoch each time. `route.instance()` names it. - **Rank several CDNs.** Dial each with its own subscribe handle, `origin.clone().with_preference(origin::Preference::new(rank))` (higher wins; 0 is neutral and a negative rank demotes), all on one origin. Requests use the preferred link that has a route and fail over to the next; see [multiple CDNs](/concept/moq-lite#multiple-cdns). - **Request one instance, or follow them all.** `consumer.request(path, None)` resolves the instance serving a path now, and fails `Unroutable` only once discovery has synced with no route for it. `consumer.follow(path, None)` hands out each publisher instance serving a path from `available()`: the first once announced, then each one that takes over, `None` once the path goes offline, and whatever serves it next, like JS `follow(path)`. `consumer.announced()` lists paths only as present or absent. A broadcast already resolved stays on the old instance until dropped or its route goes. See [identity and recovery](/concept/identity) to choose between following and holding one instance. diff --git a/js/net/api/index.api.md b/js/net/api/index.api.md index f065c755d4f..a8a6f90b6d5 100644 --- a/js/net/api/index.api.md +++ b/js/net/api/index.api.md @@ -1,11 +1,8 @@ # `@moq/net` ```ts -import { $ZodBranded } from "zod/v4/core"; import { Instant } from "@moq/clock"; import { Milli } from "@moq/clock"; -import { ZodMiniBigInt } from "zod/mini"; -import { infer } from "zod/mini"; export namespace Announce { export interface Announce { @@ -465,8 +462,6 @@ export namespace Origin { readonly closed: Signals.GetPromise; readonly path: Path.Valid; } - export type Hop = infer; - export const HopSchema: $ZodBranded, "Hop", "out">; export class Producer implements Origin.Table { constructor(); announced(scope?: Path.Pattern, options?: Announce.Options): Announce.Consumer; @@ -515,10 +510,9 @@ export namespace Origin { withdraw(): void; } export interface RouteInfo { - readonly auth?: Auth.Credential; + readonly anonymous: boolean; readonly cost: Origin.Cost; - readonly epoch?: bigint; - readonly hops: readonly Origin.Hop[]; + readonly hops: readonly bigint[]; readonly instance?: Instance.Valid; } export interface RouteOptions { @@ -532,7 +526,6 @@ export namespace Origin { route(path: Path.Valid, options?: Origin.RouteOptions): Origin.Route; routePrefix(prefix: Path.Valid, options?: Origin.RouteOptions): Origin.Route; } - export function isAnonymous(route: Origin.RouteInfo): boolean; } export namespace Path { diff --git a/js/net/bench/broadcasts.ts b/js/net/bench/broadcasts.ts index 6349cdc34e5..ec5b9d44e8d 100644 --- a/js/net/bench/broadcasts.ts +++ b/js/net/bench/broadcasts.ts @@ -4,7 +4,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, RouteInfo } from "../src/hop.ts"; +import { HopSchema, 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"; @@ -268,7 +268,7 @@ for (const routeCount of routeCounts) { for (const consumerCount of [8, 32, 128]) { const cache = new BroadcastCache(); const owners = Array.from({ length: routeCount }, () => ({})); - for (let i = 0; i < routeCount; i++) cache.announce(Path.from(`pool/${i}`), owners[i], RouteInfo.default); + for (let i = 0; i < routeCount; i++) cache.announce(Path.from(`pool/${i}`), owners[i], WireRoute.default); const sources = Array.from({ length: consumerCount }, () => new BroadcastProducer()); const held = sources.map((source, i) => { const path = Path.from(`pool/${i % routeCount}/job/${i}`); @@ -277,7 +277,7 @@ for (const routeCount of routeCounts) { const touched = Path.from("pool/0/job/0"); const start = performance.now(); for (let i = 0; i < 4096; i++) { - cache.announce(Path.from("pool/0"), owners[0], { ...RouteInfo.default, cost: BigInt(i) }); + cache.announce(Path.from("pool/0"), owners[0], { ...WireRoute.default, cost: BigInt(i) }); const shared = cache.get(touched, cache.instance(touched)); if (!shared || shared.closed !== held[0].closed) throw new Error("update replaced the source"); shared.close(); @@ -294,7 +294,7 @@ for (const routeCount of routeCounts) { for (const consumerCount of [1, 8, 32]) { const cache = new BroadcastCache(); const owners = Array.from({ length: routeCount }, () => ({})); - for (let i = 0; i < routeCount; i++) cache.announce(Path.from(`pool/${i}`), owners[i], RouteInfo.default); + for (let i = 0; i < routeCount; i++) cache.announce(Path.from(`pool/${i}`), owners[i], WireRoute.default); const sources = Array.from({ length: consumerCount }, () => new BroadcastProducer()); const paths = sources.map((_, i) => Path.from(`pool/0/job/${i}`)); const held = sources.map((source, i) => cache.insert(paths[i], cache.instance(paths[i]), source.consume())); @@ -304,7 +304,7 @@ for (const routeCount of routeCounts) { let duplicates = 0; const start = performance.now(); for (let round = 0; round < 256; round++) { - if (round % 2 === 0) cache.announce(prefix, specific, { ...RouteInfo.default, instance }); + if (round % 2 === 0) cache.announce(prefix, specific, { ...WireRoute.default, instance }); else cache.withdraw(prefix, specific); for (let i = 0; i < consumerCount; i++) { const instance = cache.instance(paths[i]); @@ -329,7 +329,7 @@ console.log("blind,announcements,consumers,invalidate_us,stale"); for (const routeCount of routeCounts) { for (const consumerCount of [1, 8, 32]) { const cache = new BroadcastCache(); - for (let i = 0; i < routeCount; i++) cache.announce(Path.from(`other/${i}`), {}, RouteInfo.default); + for (let i = 0; i < routeCount; i++) cache.announce(Path.from(`other/${i}`), {}, WireRoute.default); const source = new BroadcastProducer(); const keeper = source.consume(); const paths = Array.from({ length: consumerCount }, (_, i) => Path.from(`pool/job/${i}`)); @@ -340,7 +340,7 @@ for (const routeCount of routeCounts) { for (let round = 0; round < 256; round++) { const held = paths.map((path) => cache.insert(path, cache.instance(path), source.consume())); const start = performance.now(); - cache.announce(prefix, owner, RouteInfo.default); + cache.announce(prefix, owner, WireRoute.default); cache.withdraw(prefix, owner); elapsed += performance.now() - start; for (const path of paths) { @@ -371,7 +371,7 @@ for (const routeCount of routeCounts) { const held = []; for (let route = 0; route < routeCount; route++) { const prefix = Path.from(`route/${route}`); - cache.announce(prefix, owners[route], RouteInfo.default); + cache.announce(prefix, owners[route], WireRoute.default); for (let consumer = 0; consumer < (route === 0 ? consumerCount : 1); consumer++) { const path = Path.from(`${prefix}/job/${consumer}`); const instance = cache.instance(path); diff --git a/js/net/bench/forward.ts b/js/net/bench/forward.ts index 9fb7807daf5..35ee64e7977 100644 --- a/js/net/bench/forward.ts +++ b/js/net/bench/forward.ts @@ -10,7 +10,7 @@ import { AuthSession } from "../src/auth_session.ts"; import { Producer as BroadcastProducer } from "../src/broadcast.ts"; import type { Established } from "../src/connection/established.ts"; import { forwardAnnounced } from "../src/connection/forward.ts"; -import { RouteInfo } from "../src/hop.ts"; +import { WireRoute } from "../src/hop.ts"; import { Producer } from "../src/origin.ts"; import * as Path from "../src/path.ts"; import { registerWire } from "../src/wire.ts"; @@ -52,7 +52,7 @@ class FakeSession { } const announce = (stream: Announce.Producer, prefix: Path.Valid, cost: bigint, kind: "start" | "update") => - stream.append({ prefix, captures: undefined, kind, route: RouteInfo.normalize({ cost }) }); + stream.append({ prefix, captures: undefined, kind, route: WireRoute.normalize({ cost }) }); console.log("touched,heads,routes,update_us"); for (const touched of ["covering", "single"] as const) { diff --git a/js/net/src/announced.test-util.ts b/js/net/src/announced.test-util.ts index 5b36855a195..36056ca9d5f 100644 --- a/js/net/src/announced.test-util.ts +++ b/js/net/src/announced.test-util.ts @@ -1,6 +1,6 @@ import { Signal } from "@moq/signals"; import type { Options, Routes } from "./announced"; -import type { RouteInfo } from "./hop"; +import type { WireRoute } from "./hop"; import type * as Path from "./path"; /** A closeable announcement snapshot for tests and benchmarks. @internal */ @@ -10,7 +10,7 @@ export async function announcedView( options?: Options, ) { const stream = origin.routes(scope, options); - const value = new Signal>(new Map()); + const value = new Signal>(new Map()); const done = (async () => { for await (const event of stream) value.update((previous) => { diff --git a/js/net/src/announced.test.ts b/js/net/src/announced.test.ts index 87cd1fc24e2..a6bc527333f 100644 --- a/js/net/src/announced.test.ts +++ b/js/net/src/announced.test.ts @@ -1,8 +1,10 @@ import { expect, test } from "bun:test"; 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 { RouteInfo } from "./hop.ts"; +import { HopSchema, 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"; import { wireOf } from "./wire.ts"; @@ -19,7 +21,7 @@ test("next streams every appended event in order", async () => { const producer = new Announce.Producer(); const consumer = producer.consume(); - const route = RouteInfo.default; + const route = WireRoute.default; producer.append({ prefix: p("a"), captures: undefined, kind: "start", route }); producer.append({ prefix: p("a"), captures: undefined, kind: "end", route }); @@ -31,7 +33,7 @@ test("a listing reports only a path becoming present or absent", async () => { const producer = new Announce.Producer(); const listing = Announce.list(producer.consume()); - const route = RouteInfo.default; + const route = WireRoute.default; producer.append({ prefix: p("a"), captures: undefined, kind: "start", route }); producer.append({ prefix: p("a"), captures: undefined, kind: "update", route }); producer.append({ prefix: p("a"), captures: undefined, kind: "restart", route }); @@ -41,11 +43,35 @@ test("a listing reports only a path becoming present or absent", async () => { expect((await listing.next())?.kind).toBe("absent"); }); +test("a listing shows a route's facts, never its epoch or credential", async () => { + const producer = new Announce.Producer(); + const listing = Announce.list(producer.consume()); + + const instance = Instance.random(); + const route = WireRoute.normalize({ + instance, + epoch: 3n, + hops: [HopSchema.parse(7n), UNKNOWN_HOP], + cost: 5n, + auth: {} as Credential, + }); + producer.append({ prefix: p("a"), captures: undefined, kind: "start", route }); + + const event = await listing.next(); + expect(event).toEqual({ + kind: "present", + prefix: p("a"), + captures: undefined, + route: { instance, hops: [7n, 0n], cost: 5n, anonymous: true }, + }); + expect(Object.keys(event?.route ?? {}).sort()).toEqual(["anonymous", "cost", "hops", "instance"]); +}); + test("the consumer is an async iterable of the same events", async () => { const producer = new Announce.Producer(); const consumer = producer.consume(); - const route = RouteInfo.default; + const route = WireRoute.default; producer.append({ prefix: p("a"), captures: undefined, kind: "start", route }); producer.append({ prefix: p("a"), captures: undefined, kind: "end", route }); @@ -64,7 +90,7 @@ test("a same-name re-announce is a distinct update", async () => { // The stream is a log, not a set: it carries a redundant announce as its own update rather // than collapsing it. Deciding what a repeat means belongs to the session layer, which resolves // a restart into either nothing (an identical route) or an in-place update. - const route = RouteInfo.default; + const route = WireRoute.default; producer.append({ prefix: p("a"), captures: undefined, kind: "start", route }); producer.append({ prefix: p("a"), captures: undefined, kind: "start", route }); @@ -97,7 +123,7 @@ test("closing a consumer releases only that handle", async () => { expect(producer.closed.peek()).toBeUndefined(); // The other reader keeps the stream: an event still reaches it. - const route = RouteInfo.default; + const route = WireRoute.default; producer.append({ prefix: p("a"), captures: undefined, kind: "start", route }); expect((await second.next())?.prefix).toBe(p("a")); @@ -178,7 +204,7 @@ const start = (prefix: string): Announce.RouteEvent => ({ prefix: p(prefix), captures: undefined, kind: "start", - route: RouteInfo.default, + route: WireRoute.default, }); test("a stream syncs once the reader is past what was queued at the boundary", async () => { diff --git a/js/net/src/announced.ts b/js/net/src/announced.ts index f779130dd94..f188c6ab9e6 100644 --- a/js/net/src/announced.ts +++ b/js/net/src/announced.ts @@ -4,7 +4,7 @@ * @module */ import { type GetPromise, type Getter, Once, Signal } from "@moq/signals"; -import type { RouteInfo } from "./hop.js"; +import { type RouteInfo, routeInfo, type WireRoute } from "./hop.ts"; import type * as Path from "./path.js"; /** @@ -29,6 +29,13 @@ export interface Announce { route: RouteInfo; } +/** + * An {@link Announce} as the origin and sessions carry it, with the route's internal metadata. + * + * @internal + */ +export type Routed = Omit & { route: WireRoute }; + /** * What an announcement listing yields: a path becoming present or absent. * @@ -49,7 +56,7 @@ export type Event = { kind: "present" | "absent" } & Announce; * * @internal */ -export type RouteEvent = { kind: "start" | "update" | "restart" | "end" } & Announce; +export type RouteEvent = { kind: "start" | "update" | "restart" | "end" } & Routed; /** * Options for an announcement stream. @@ -316,9 +323,9 @@ export class Consumer { for (;;) { const event = await this.#routes.next(); if (!event) return undefined; - const { kind, ...announce } = event; - if (kind === "start") return { kind: "present", ...announce }; - if (kind === "end") return { kind: "absent", ...announce }; + const { kind, prefix, captures, route } = event; + if (kind === "start") return { kind: "present", prefix, captures, route: routeInfo(route) }; + if (kind === "end") return { kind: "absent", prefix, captures, route: routeInfo(route) }; } } diff --git a/js/net/src/connection/forward.test.ts b/js/net/src/connection/forward.test.ts index 396e9c3b40a..70d9eab1d16 100644 --- a/js/net/src/connection/forward.test.ts +++ b/js/net/src/connection/forward.test.ts @@ -3,7 +3,7 @@ import { type Installed, Manual, Milli, Nano } from "@moq/clock"; import * as Announce from "../announced.ts"; import { AuthSession } from "../auth_session.ts"; import { type Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "../broadcast.ts"; -import { RouteInfo } from "../hop.ts"; +import { WireRoute } from "../hop.ts"; import * as Instance from "../instance.ts"; import { Producer as OriginProducer } from "../origin.ts"; import * as Path from "../path.ts"; @@ -132,7 +132,7 @@ class FakeSession { } } -function start(stream: Announce.Producer, prefix: string, route: RouteInfo = RouteInfo.default) { +function start(stream: Announce.Producer, prefix: string, route: WireRoute = WireRoute.default) { stream.append({ prefix: Path.from(prefix), captures: undefined, kind: "start", route }); } @@ -411,12 +411,12 @@ for (const [name, instances] of [ const narrow = origin.routes(Path.Pattern.subtree(Path.from("a/b"))); await settle(); - start(session.stream("a/b/**"), "a/b/x", { ...RouteInfo.default, instance: instances[0] }); + start(session.stream("a/b/**"), "a/b/x", { ...WireRoute.default, instance: instances[0] }); await settle(); const broad = origin.routes(Path.Pattern.subtree(Path.from("a"))); const events = record(broad); await settle(); - start(session.stream("a/**"), "a/b/x", { ...RouteInfo.default, instance: instances[1] }); + start(session.stream("a/**"), "a/b/x", { ...WireRoute.default, instance: instances[1] }); await settle(); expect(events).toEqual(["start a/b/x"]); diff --git a/js/net/src/connection/forward.ts b/js/net/src/connection/forward.ts index bb2cfb6ba6d..7f290064a14 100644 --- a/js/net/src/connection/forward.ts +++ b/js/net/src/connection/forward.ts @@ -7,7 +7,7 @@ import { Milli, Nano } from "@moq/clock"; import { type Dispose, race } from "@moq/signals"; import type * as Announce from "../announced.ts"; -import { type RouteInfo, routesEqual } from "../hop.ts"; +import { routesEqual, type WireRoute } from "../hop.ts"; import { coveringPrefixes } from "../internal.ts"; import type { Producer as OriginProducer, Route } from "../origin.ts"; import * as Path from "../path.ts"; @@ -41,7 +41,7 @@ interface Interest { interface Reported { handle: Route; /** Each request's latest route for the prefix. */ - readonly reporters: Map; + readonly reporters: Map; } /** @@ -118,7 +118,7 @@ export function forwardAnnounced(conn: Established, origin: OriginProducer): voi * instance, so nothing resolved through the old one is joined again, and an in-place * update otherwise. */ - const updateReported = (existing: Reported, prefix: Path.Valid, route: RouteInfo, restart: boolean) => { + const updateReported = (existing: Reported, prefix: Path.Valid, route: WireRoute, restart: boolean) => { const current = wireOf(existing.handle).info; if (restart || route.epoch !== current?.epoch) { // Inserted before the old one leaves, so local readers see one restart rather than diff --git a/js/net/src/connection/reload.test.ts b/js/net/src/connection/reload.test.ts index 4b36caa5dcd..62833ec42b1 100644 --- a/js/net/src/connection/reload.test.ts +++ b/js/net/src/connection/reload.test.ts @@ -5,7 +5,7 @@ import * as Announce from "../announced.ts"; import { Viewers } from "../bandwidth.ts"; import type { Producer as BroadcastProducer } from "../broadcast.ts"; import { ConnectTimeout, SessionCode, SessionError, StreamCode, toTransport } from "../error.ts"; -import { RouteInfo } from "../hop.ts"; +import { WireRoute } from "../hop.ts"; import { ALPN as IetfALPN } from "../ietf/version.ts"; import * as Lite from "../lite/index.ts"; import { createMockTransportPair, type MockTransport, textFrame } from "../mock.ts"; @@ -1030,7 +1030,7 @@ test("closing an announce consumer during upstream teardown does not append retr prefix: Path.from("alice/camera.hang"), captures: undefined, kind: "start", - route: RouteInfo.default, + route: WireRoute.default, }); await consumer.next(); upstream.close(); @@ -1136,7 +1136,7 @@ test("a pump owes the retractions of the upstream it replaces", async () => { const consumer = producer.consume(); const first = new Announce.Producer(); - first.append({ prefix: Path.from("a"), captures: undefined, kind: "start", route: RouteInfo.default }); + first.append({ prefix: Path.from("a"), captures: undefined, kind: "start", route: WireRoute.default }); first.synced(); const upstream = new Signal(first); const pump = new Effect((effect) => pumpAnnounced(effect, effect.get(upstream).consume(), producer)); diff --git a/js/net/src/connection/reload.ts b/js/net/src/connection/reload.ts index 8074b972720..e1d830806a5 100644 --- a/js/net/src/connection/reload.ts +++ b/js/net/src/connection/reload.ts @@ -876,7 +876,7 @@ export class Reload { */ export function pumpAnnounced(effect: Effect, upstream: Announce.Routes, producer: Announce.Producer) { // The last event per active route rides along for its retraction. - const active = new Map(); + const active = new Map(); let live = true; const retract = () => { live = false; diff --git a/js/net/src/consume.test.ts b/js/net/src/consume.test.ts index 04a42fa4f34..ed66cc52f58 100644 --- a/js/net/src/consume.test.ts +++ b/js/net/src/consume.test.ts @@ -2,7 +2,7 @@ import { expect, test } from "bun:test"; import { Producer } from "./broadcast.ts"; import { BroadcastCache } from "./consume.ts"; import { StreamCode, StreamError } from "./error.ts"; -import { RouteInfo } from "./hop.ts"; +import { WireRoute } from "./hop.ts"; import * as Instance from "./instance.ts"; import * as Path from "./path.ts"; @@ -13,16 +13,16 @@ test("cache identity follows the serving announcement, preserving held tracks", const broad = {}; const specific = {}; const instance = Instance.random(); - cache.announce(pool, broad, { ...RouteInfo.default, instance }); + cache.announce(pool, broad, { ...WireRoute.default, instance }); const source = new Producer(); const track = source.createTrack("video"); const held = cache.insert(job, cache.instance(job), source.consume()); const ordered = held.track("video").subscribe().ordered(); - cache.announce(job, specific, { ...RouteInfo.default, instance }); + cache.announce(job, specific, { ...WireRoute.default, instance }); const same = cache.get(job, cache.instance(job)); expect(same?.closed).toBe(held.closed); - cache.announce(job, specific, RouteInfo.default, true); + cache.announce(job, specific, WireRoute.default, true); expect(cache.instance(job).route.instance).toBeUndefined(); expect(cache.get(job, cache.instance(job))).toBeUndefined(); const replacement = new Producer(); @@ -46,7 +46,7 @@ test("withdrawing one interest keeps another interest's explicit identity", () = const path = Path.from("room"); const first = {}; const second = {}; - const route = { ...RouteInfo.default, instance: Instance.random() }; + const route = { ...WireRoute.default, instance: Instance.random() }; cache.announce(path, first, route); cache.announce(path, second, route); const source = new Producer(); @@ -70,7 +70,7 @@ test("an announcement lifecycle retires a blind cache without disturbing unrelat const held = cache.insert(path, cache.instance(path), source.consume()); const otherHeld = cache.insert(other, cache.instance(other), unrelated.consume()); const owner = {}; - cache.announce(Path.from("pool"), owner, RouteInfo.default); + cache.announce(Path.from("pool"), owner, WireRoute.default); cache.withdraw(Path.from("pool"), owner); expect(cache.get(path, cache.instance(path))).toBeUndefined(); const same = cache.get(other, cache.instance(other)); @@ -87,10 +87,10 @@ test.each([false, true])("route alternation reuses every held instance (instance const broad = Path.from("pool"); const ownerA = {}; const ownerB = {}; - cache.announce(broad, ownerA, { ...RouteInfo.default, instance: explicit ? Instance.random() : undefined }); + cache.announce(broad, ownerA, { ...WireRoute.default, instance: explicit ? Instance.random() : undefined }); const a = new Producer(); const heldA = cache.insert(path, cache.instance(path), a.consume()); - cache.announce(path, ownerB, { ...RouteInfo.default, instance: explicit ? Instance.random() : undefined }); + cache.announce(path, ownerB, { ...WireRoute.default, instance: explicit ? Instance.random() : undefined }); const b = new Producer(); const heldB = cache.insert(path, cache.instance(path), b.consume()); cache.withdraw(path, ownerB); @@ -107,13 +107,13 @@ test("request validity cancels one selection period and permits the held fallbac const broad = Path.from("pool"); const a = {}; const b = {}; - cache.announce(broad, a, RouteInfo.default); + cache.announce(broad, a, WireRoute.default); const sourceA = new Producer(); const instanceA = cache.instance(path); const heldA = cache.insert(path, instanceA, sourceA.consume()); const first = instanceA.validity?.signal; expect(first?.aborted).toBe(false); - cache.announce(path, b, RouteInfo.default); + cache.announce(path, b, WireRoute.default); expect(first?.aborted).toBe(true); // A more specific route taking over ends the old instance's requests the way Rust does, so // players treat it as the instance going offline rather than an unexpected failure. @@ -142,16 +142,16 @@ test("request validity follows the selected interest and ignores unrelated withd const broad = {}; const first = {}; const second = {}; - cache.announce(Path.from("pool"), broad, RouteInfo.default); - cache.announce(path, first, RouteInfo.default); - cache.announce(path, second, RouteInfo.default); + cache.announce(Path.from("pool"), broad, WireRoute.default); + cache.announce(path, first, WireRoute.default); + cache.announce(path, second, WireRoute.default); const source = new Producer(); const instance = cache.instance(path); const held = cache.insert(path, instance, source.consume()); const signal = instance.validity?.signal; cache.withdraw(Path.from("pool"), broad); cache.withdraw(path, second); - cache.announce(path, first, { ...RouteInfo.default, cost: 1n }); + cache.announce(path, first, { ...WireRoute.default, cost: 1n }); expect(instance.validity?.signal).toBe(signal); expect(signal?.aborted).toBe(false); cache.withdraw(path, first); @@ -167,7 +167,7 @@ test("a blind selection retires on discovery while explicit instances need no pa const source = new Producer(); const held = cache.insert(path, blind, source.consume()); const owner = {}; - cache.announce(Path.from("pool"), owner, { ...RouteInfo.default, instance: Instance.random() }); + cache.announce(Path.from("pool"), owner, { ...WireRoute.default, instance: Instance.random() }); expect(blind.validity?.signal.aborted).toBe(true); expect(cache.instance(path).validity).toBeUndefined(); cache.withdraw(Path.from("pool"), owner); diff --git a/js/net/src/consume.ts b/js/net/src/consume.ts index 86b89c379c3..9f3a8dc5d2b 100644 --- a/js/net/src/consume.ts +++ b/js/net/src/consume.ts @@ -1,6 +1,6 @@ import type * as broadcast from "./broadcast.ts"; import { StreamCode, StreamError } from "./error.ts"; -import type { RouteInfo } from "./hop.ts"; +import type { WireRoute } from "./hop.ts"; import * as Instance from "./instance.ts"; import { compareRouteCandidates, coveringPrefixes, Epochs } from "./internal.ts"; import type * as Path from "./path.ts"; @@ -52,13 +52,13 @@ export class BroadcastCache { Path.Valid, Map >(); - #announced = new Map>(); + #announced = new Map>(); #blind = new Map(); #blindPrefixes = new Map>(); #paths = new Map>(); /** Record this interest's live advertisement, preserving identity across route updates. */ - announce(path: Path.Valid, owner: object, route: RouteInfo, restart = false): void { + announce(path: Path.Valid, owner: object, route: WireRoute, restart = false): void { // Only unannounced consumers covered by this advertisement lose their blind identity. for (const covered of this.#blindPrefixes.get(path) ?? []) this.#forgetBlind(covered); let entries = this.#announced.get(path); @@ -84,7 +84,7 @@ export class BroadcastCache { for (const prefix of coveringPrefixes(path)) { const entries = this.#announced.get(prefix); if (!entries) continue; - let best: { identity: object; route: RouteInfo } | undefined; + let best: { identity: object; route: WireRoute } | undefined; const epochs = new Epochs([...entries.values()].map((entry) => entry.route)); for (const entry of entries.values()) { if (epochs.supersedes(entry.route)) continue; diff --git a/js/net/src/hop.ts b/js/net/src/hop.ts index d01492d599b..f08cf878bc2 100644 --- a/js/net/src/hop.ts +++ b/js/net/src/hop.ts @@ -98,10 +98,49 @@ export const Cost = { export interface RouteInfo { /** * The stream the route serves: routes with one instance serve one continuous sequence - * space, so a subscription resumes from one to another. Always set on a route the origin - * delivers; pass it to an origin `request` to pin this stream. + * space, so a subscription resumes from one to another. Pass it to an origin `request` to + * pin this stream. */ readonly instance?: Instance.Valid; + /** + * The hop ids of the origins the route has traversed, oldest first. A 0 entry is the + * anonymous mark; see {@link anonymous}. A route announced on this origin has none. + */ + readonly hops: readonly bigint[]; + /** What pulling content via this route costs; lower wins. */ + readonly cost: Cost; + /** + * Whether the route passed through an anonymous hop (id 0) at any depth. An anonymous route + * ranks below every fully identified one, whatever the costs say. An empty chain is a local + * announcement, not the anonymous mark. + */ + readonly anonymous: boolean; +} + +/** + * The read-only facts an announcement shows of `route`, leaving its epoch and credential internal. + * + * @internal + */ +export function routeInfo(route: WireRoute): RouteInfo { + return { + instance: route.instance, + hops: [...route.hops], + cost: route.cost, + anonymous: isAnonymous(route), + }; +} + +/** + * A route as the origin and sessions carry it: the {@link RouteInfo} facts plus the epoch that + * orders an instance's incarnations and the credential that advertises it, which applications + * never see. + * + * @internal + */ +export interface WireRoute { + /** See {@link RouteInfo.instance}. Always set on a route the origin delivers. */ + readonly instance?: Instance.Valid; /** * Which incarnation of {@link instance} this is: among its routes at one prefix only the * highest epoch is eligible, cheaper or not. Never compared across instances. @@ -124,13 +163,13 @@ export interface RouteInfo { readonly auth?: Credential; } -/** Constructors and helpers for {@link RouteInfo}. @internal */ -export const RouteInfo = { +/** Constructors and helpers for {@link WireRoute}. @internal */ +export const WireRoute = { /** An empty hop chain at zero cost: what a publisher seeds for a live broadcast. */ - default: { hops: [], cost: Cost.zero } as RouteInfo, + default: { hops: [], cost: Cost.zero } as WireRoute, /** Fill route defaults and saturate the static price at the wire ceiling. */ - normalize(route: Partial = {}): RouteInfo { + normalize(route: Partial = {}): WireRoute { const cost = route.cost ?? Cost.zero; if (typeof cost !== "bigint" || cost < 0n) throw new RangeError("route cost must be a non-negative bigint"); const max = 2n ** 62n - 1n; @@ -150,13 +189,19 @@ export const RouteInfo = { * * An empty chain is a local announcement, not the anonymous mark. Ingress fills a * received empty list with the anonymous hop before yielding it. + * + * @internal */ -export function isAnonymous(route: RouteInfo): boolean { +export function isAnonymous(route: WireRoute): boolean { return route.hops.includes(UNKNOWN_HOP); } -/** Whether two routes name the same instance, epoch, hop chain, cost, and auth. */ -export function routesEqual(a: RouteInfo | undefined, b: RouteInfo | undefined): boolean { +/** + * Whether two routes name the same instance, epoch, hop chain, cost, and auth. + * + * @internal + */ +export function routesEqual(a: WireRoute | undefined, b: WireRoute | undefined): boolean { if (a === b) return true; if (!a || !b) return false; return ( diff --git a/js/net/src/ietf/publisher.ts b/js/net/src/ietf/publisher.ts index bf894ab6273..0b35ecd6056 100644 --- a/js/net/src/ietf/publisher.ts +++ b/js/net/src/ietf/publisher.ts @@ -21,7 +21,7 @@ import { unauthorized, } from "../error.ts"; import type * as group from "../group.ts"; -import type { Hop, RouteInfo } from "../hop.ts"; +import type { Hop, WireRoute } from "../hop.ts"; import { finalSequence, firstEligible, hiddenBelow, hooks, presented, type ReadGroupFrame } from "../internal.ts"; import type { Consumer as OriginConsumer } from "../origin.ts"; import * as Path from "../path.ts"; @@ -90,7 +90,7 @@ const RETRY_BASE = 100; const RETRY_MAX = 5000; /** Cluster parameters for one snapshot: the advertised hops, then our own id last. */ -function clusterFor(base: Cluster.Advert | undefined, route: RouteInfo): Cluster.Advert | undefined { +function clusterFor(base: Cluster.Advert | undefined, route: WireRoute): Cluster.Advert | undefined { if (!base) return undefined; const self = base.hops.at(-1); if (self === undefined) return undefined; @@ -2017,7 +2017,7 @@ export class Publisher { /** * The extension parameters an advertisement of `route` carries. */ - #params(route: RouteInfo): AdvertParams { + #params(route: WireRoute): AdvertParams { return { cluster: clusterFor(this.#advert, route) }; } @@ -2026,7 +2026,7 @@ export class Publisher { * is logged and skipped: a peer that wants none of this rejects each one and stays * connected. */ - async #advertise(path: Path.Valid, requests: Requests, route: RouteInfo): Promise { + async #advertise(path: Path.Valid, requests: Requests, route: WireRoute): Promise { const params = this.#params(route); const auth = this.#carry(route.auth); const requestId = await this.#session.nextRequestId(); diff --git a/js/net/src/ietf/subscriber.ts b/js/net/src/ietf/subscriber.ts index 9ac6792beaa..91cf11b65d3 100644 --- a/js/net/src/ietf/subscriber.ts +++ b/js/net/src/ietf/subscriber.ts @@ -22,7 +22,7 @@ import { } from "../error.ts"; import { type Fill, fillChanged, type Requests, wantedRuns } from "../fill.ts"; import type * as netGroup from "../group.ts"; -import { Cost, type RouteInfo, routesEqual, UNKNOWN_HOP } from "../hop.ts"; +import { Cost, routesEqual, UNKNOWN_HOP, type WireRoute } from "../hop.ts"; import * as Instance from "../instance.ts"; import { finalSequence, hiddenBelow, hooks, maxDelayOf, scopeCaptures, scopeHead, scopeOverlaps } from "../internal.ts"; import type { Lister } from "../listing.ts"; @@ -135,7 +135,7 @@ type SubscribeSetupState = { }; /** An announced path: each live advertisement referencing it, oldest first, and the route it holds. */ -type Announced = { adverts: { id: number; route: RouteInfo }[]; route: RouteInfo }; +type Announced = { adverts: { id: number; route: WireRoute }[]; route: WireRoute }; /** A local announce reader's filter: its scope, the prefix it asked for, and its hidden opt-in. */ type Filter = { scope: Path.Pattern; prefix: Path.Valid; hidden: boolean; covering: boolean }; @@ -288,7 +288,7 @@ export class Subscriber { } // What a route costs once the peer has asked us to leave. - #priced(route: RouteInfo): RouteInfo { + #priced(route: WireRoute): WireRoute { if (!this.#goingAway()) return route; if (route.cost === DRAIN_COST) return route; return { ...route, cost: DRAIN_COST }; @@ -322,7 +322,7 @@ export class Subscriber { /** * The route an advertisement carries, before it is minted an instance; one without a path is anonymous and free. */ - #route({ cluster }: AdvertParams): RouteInfo { + #route({ cluster }: AdvertParams): WireRoute { return cluster === undefined ? { hops: [UNKNOWN_HOP], cost: Cost.zero } : { ...cluster }; } @@ -392,7 +392,7 @@ export class Subscriber { * Record one more advertisement for a path, returning the id that names it. Consumers * hear `start` for the first; a later one stands as the newest (see `#settleAnnounce`). */ - #attachAnnounce(path: Path.Valid, route: RouteInfo): number { + #attachAnnounce(path: Path.Valid, route: WireRoute): number { const id = this.#nextAdvert++; const existing = this.#announced.get(path); if (existing) { @@ -418,7 +418,7 @@ export class Subscriber { } /** Replace the route of advertisement `id`, which moves the path only while it is the newest. */ - #updateAnnounce(path: Path.Valid, id: number, route: RouteInfo) { + #updateAnnounce(path: Path.Valid, id: number, route: WireRoute) { const existing = this.#announced.get(path); const advert = existing?.adverts.find((advert) => advert.id === id); if (existing === undefined || advert === undefined) return; diff --git a/js/net/src/internal.ts b/js/net/src/internal.ts index c9df2e06cc0..f44c02f8cbe 100644 --- a/js/net/src/internal.ts +++ b/js/net/src/internal.ts @@ -12,7 +12,7 @@ import type * as datagram from "./datagram.ts"; import type { Delivered } from "./delivered.ts"; import { toStreamCode } from "./error.ts"; import type { Frame, FrameConsumer, Consumer as GroupConsumer, Producer as GroupProducer } from "./group.ts"; -import { isAnonymous, type RouteInfo } from "./hop.ts"; +import { isAnonymous, type WireRoute } from "./hop.ts"; import type * as Instance from "./instance.ts"; import type { Consumer as OriginConsumer, Producer as OriginProducer } from "./origin.ts"; import * as Path from "./path.ts"; @@ -136,12 +136,12 @@ export function presented( * candidate supersedes. Supersession is decided among what the reader may see, so a higher epoch * it cannot see never hides a route it can. */ -export function firstEligible( +export function firstEligible( candidates: readonly T[], admits: (candidate: T) => boolean = () => true, ): T | undefined { const admitted = candidates.filter(admits); - const byPrefix = new Map(); + const byPrefix = new Map(); for (const candidate of admitted) { const routes = byPrefix.get(candidate.prefix); if (routes) routes.push(candidate.route); @@ -1139,7 +1139,7 @@ export function* coveringPrefixes(path: Path.Valid): Generator { * a higher epoch at the same prefix. An older incarnation of an instance is never eligible, * however cheap, since its publisher was replaced. */ -export function superseded(route: RouteInfo, others: Iterable): boolean { +export function superseded(route: WireRoute, others: Iterable): boolean { return new Epochs(others).supersedes(route); } @@ -1151,7 +1151,7 @@ export function superseded(route: RouteInfo, others: Iterable): boole export class Epochs { readonly #highest = new Map(); - constructor(routes: Iterable) { + constructor(routes: Iterable) { for (const route of routes) { const epoch = route.epoch ?? 0n; if (epoch === 0n) continue; @@ -1161,14 +1161,14 @@ export class Epochs { } /** Whether a route carries `route`'s instance at a higher epoch. */ - supersedes(route: RouteInfo): boolean { + supersedes(route: WireRoute): boolean { const highest = this.#highest.get(route.instance); return highest !== undefined && highest > (route.epoch ?? 0n); } } /** Prefer identified publishers, then lower static cost. */ -export function compareRoutes(a: RouteInfo, b: RouteInfo): number { +export function compareRoutes(a: WireRoute, b: WireRoute): number { return Number(isAnonymous(a)) - Number(isAnonymous(b)) || (a.cost < b.cost ? -1 : a.cost > b.cost ? 1 : 0); } @@ -1180,7 +1180,7 @@ export function compareRoutes(a: RouteInfo, b: RouteInfo): number { * matching `route_order` in rs/moq-net for routes a node did not get from a cluster peer, which * is every route here. */ -export function compareRouteCandidates(path: Path.Valid, prefix: Path.Valid, a: RouteInfo, b: RouteInfo): number { +export function compareRouteCandidates(path: Path.Valid, prefix: Path.Valid, a: WireRoute, b: WireRoute): number { const order = compareRoutes(a, b) || a.hops.length - b.hops.length; if (order !== 0 || path === prefix) return order; const ha = spreadHash(path, a.instance ?? ""); diff --git a/js/net/src/lite/publisher.ts b/js/net/src/lite/publisher.ts index f28663680fe..5ee4d96c4b8 100644 --- a/js/net/src/lite/publisher.ts +++ b/js/net/src/lite/publisher.ts @@ -19,7 +19,7 @@ import { unauthorized, } from "../error.ts"; import type * as group from "../group.ts"; -import { Cost, type Hop, type RouteInfo, routesEqual } from "../hop.ts"; +import { Cost, type Hop, routesEqual, type WireRoute } from "../hop.ts"; import { finalSequence, hiddenBelow, hooks, insertRun, presented, type Run, runGaps } from "../internal.ts"; import type { Consumer as OriginConsumer } from "../origin.ts"; import * as Path from "../path.ts"; @@ -612,7 +612,7 @@ export class Publisher { let nextAnnounceId = 0n; const announceIds = new Map(); - const wireHops = (route: RouteInfo): Hop[] => { + const wireHops = (route: WireRoute): Hop[] => { if (hasAnnounceOk(this.version)) return [...route.hops]; return [...route.hops, this.hop]; }; @@ -620,7 +620,7 @@ export class Publisher { // What the peer decodes for a route: pre-lite-06 wires carry no cost, so a re-price // there must not restart. // moq-lite carries no per-request auth, so a swap alone sends nothing. - const onWire = (route: RouteInfo): RouteInfo => ({ + const onWire = (route: WireRoute): WireRoute => ({ ...route, cost: hasRouteCost(this.version) ? route.cost : Cost.zero, auth: undefined, @@ -632,7 +632,7 @@ export class Publisher { !sameInstance(prev, next) || (hasInstance(this.version) && (prev.route.epoch ?? 0n) !== (next.route.epoch ?? 0n)); - const announce = async (suffix: Path.Valid, route: RouteInfo) => { + const announce = async (suffix: Path.Valid, route: WireRoute) => { console.debug(`announce: broadcast=${suffix} active=true instance=${route.instance}`); if (hasAnnounceId(this.version)) announceIds.set(suffix, nextAnnounceId++); await encodeAnnounceBroadcast( @@ -649,7 +649,7 @@ export class Publisher { ); }; - const update = async (suffix: Path.Valid, route: RouteInfo) => { + const update = async (suffix: Path.Valid, route: WireRoute) => { if (!hasAnnounceId(this.version)) { await retract(suffix); await announce(suffix, route); @@ -669,7 +669,7 @@ export class Publisher { }; // Another instance or epoch: ANNOUNCE_RESTART on lite-07, an end and a start before it. - const restart = async (suffix: Path.Valid, route: RouteInfo) => { + const restart = async (suffix: Path.Valid, route: WireRoute) => { const id = announceIds.get(suffix); if (id === undefined || !hasAnnounceRestart(this.version)) { await retract(suffix); diff --git a/js/net/src/lite/subscriber.test.ts b/js/net/src/lite/subscriber.test.ts index 5f99860d3a7..ba87eb6818b 100644 --- a/js/net/src/lite/subscriber.test.ts +++ b/js/net/src/lite/subscriber.test.ts @@ -17,7 +17,7 @@ import { TimestampMismatch, } from "../error.ts"; import type { Consumer as GroupConsumer } from "../group.ts"; -import { HopSchema, isAnonymous, MAX_HOPS, RouteInfo, UNKNOWN_HOP } from "../hop.ts"; +import { HopSchema, isAnonymous, MAX_HOPS, UNKNOWN_HOP, WireRoute } from "../hop.ts"; import * as Instance from "../instance.ts"; import { hooks } from "../internal.ts"; import { GRACE } from "../ledger.ts"; @@ -201,8 +201,8 @@ test("an announce consumer closed while its stream opens sends nothing on it", a }); test("a local empty hop chain is not anonymous", () => { - expect(isAnonymous(RouteInfo.default)).toBe(false); - expect(isAnonymous({ hops: [UNKNOWN_HOP], cost: RouteInfo.default.cost })).toBe(true); + expect(isAnonymous(WireRoute.default)).toBe(false); + expect(isAnonymous({ hops: [UNKNOWN_HOP], cost: WireRoute.default.cost })).toBe(true); }); test("a max-length chain plus withheld responder is dropped", async () => { diff --git a/js/net/src/lite/subscriber.ts b/js/net/src/lite/subscriber.ts index 5a2eb95690b..d9d62af4f43 100644 --- a/js/net/src/lite/subscriber.ts +++ b/js/net/src/lite/subscriber.ts @@ -21,7 +21,7 @@ import { unauthorized, } from "../error.ts"; import * as netGroup from "../group.ts"; -import { Cost, type Hop, MAX_HOPS, type RouteInfo, routesEqual, UNKNOWN_HOP } from "../hop.ts"; +import { Cost, type Hop, MAX_HOPS, routesEqual, UNKNOWN_HOP, type WireRoute } from "../hop.ts"; import * as Instance from "../instance.ts"; import { hiddenBelow, hooks, maxDelayOf, minDelayOf, scopeCaptures, scopeHead, scopeOverlaps } from "../internal.ts"; import type { Lister } from "../listing.ts"; @@ -423,7 +423,7 @@ export class Subscriber { // retract that one's state. type Advertisement = { live: boolean; - route: RouteInfo; + route: WireRoute; captures: Path.Pattern[] | undefined; }; // Each holds one of the session's announce slots, reflected and hidden ones included. @@ -735,7 +735,7 @@ export class Subscriber { }); continue; } - const route: RouteInfo = { instance, epoch, hops: fullHops, cost: this.#cost(cost) }; + const route: WireRoute = { instance, epoch, hops: fullHops, cost: this.#cost(cost) }; const captures = scopeCaptures(scope, path); if (!visible(path)) { advertised.set(path, { live: false, route, captures }); diff --git a/js/net/src/origin-request.test.ts b/js/net/src/origin-request.test.ts index aabf3d94108..874a5f38b7e 100644 --- a/js/net/src/origin-request.test.ts +++ b/js/net/src/origin-request.test.ts @@ -1,7 +1,7 @@ import { expect, test } from "bun:test"; import { Producer as BroadcastProducer } from "./broadcast"; import { StreamCode, StreamError } from "./error"; -import { RouteInfo } from "./hop"; +import { WireRoute } from "./hop"; import * as Instance from "./instance.ts"; import { type Following, Producer, type Requesting } from "./origin"; import * as Path from "./path"; @@ -294,7 +294,7 @@ for (const received of [false, true]) { const events: string[] = []; const stop = wireOf(origin).interests((prefix, wanted) => events.push(`${prefix} ${wanted}`)); const source = new BroadcastProducer(); - const route = received ? wireOf(origin).receive(path, RouteInfo.default) : origin.routePrefix(path); + const route = received ? wireOf(origin).receive(path, WireRoute.default) : origin.routePrefix(path); void (async () => { for await (const request of route.requested()) request.serve(source.consume()); })(); diff --git a/js/net/src/origin.test.ts b/js/net/src/origin.test.ts index 8c6ad7afda3..77833c9937b 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, RouteInfo } from "./hop.ts"; +import { type Cost, HopSchema, WireRoute } from "./hop.ts"; import * as Instance from "./instance.ts"; import { chainHash, presented, spreadHash } from "./internal.ts"; import { SessionBroadcast, textFrame } from "./mock.ts"; @@ -31,7 +31,7 @@ function serve( origin: Producer, prefix: Path.Valid, consume: () => BroadcastConsumer, - route: RouteInfo = RouteInfo.default, + route: WireRoute = WireRoute.default, ) { const handle = wireOf(origin).receive(prefix, route); void (async () => { @@ -124,7 +124,7 @@ test("a borrowed table exposes dynamic serving and a live scoped broadcast map", const table: Table = origin; const scope = Path.Pattern.parse("room/**"); const live = await announcedView(origin, scope); - const changes: ReadonlyMap[] = []; + const changes: ReadonlyMap[] = []; const stop = live.subscribe((value) => changes.push(value)); await new Promise((resolve) => setImmediate(resolve)); expect(live.peek().size).toBe(0); @@ -141,18 +141,18 @@ test("a borrowed table exposes dynamic serving and a live scoped broadcast map", localRoute.announce(); await settle(); await new Promise((resolve) => setImmediate(resolve)); - expect(live.peek().get(localPath)).toEqual(RouteInfo.normalize({ instance: INSTANCE, cost: 4n })); + expect(live.peek().get(localPath)).toEqual(WireRoute.normalize({ instance: INSTANCE, cost: 4n })); await new Promise((resolve) => setImmediate(resolve)); expect(changes.some((value) => value.get(localPath)?.cost === 4n)).toBe(true); const prefix = Path.from("room"); const dynamic = table.routePrefix(prefix, { cost: 2n }); await new Promise((resolve) => setImmediate(resolve)); - expect(live.peek().get(prefix)).toEqual(RouteInfo.normalize({ ...wireOf(dynamic).info, cost: 2n })); + expect(live.peek().get(prefix)).toEqual(WireRoute.normalize({ ...wireOf(dynamic).info, cost: 2n })); dynamic.setCost(3n); await settle(); await new Promise((resolve) => setImmediate(resolve)); - expect(live.peek().get(prefix)).toEqual(RouteInfo.normalize({ ...wireOf(dynamic).info, cost: 3n })); + expect(live.peek().get(prefix)).toEqual(WireRoute.normalize({ ...wireOf(dynamic).info, cost: 3n })); dynamic.close(); local.close(); @@ -171,26 +171,26 @@ test("an announced local path competes with a received route on cost", async () const remote = wireOf(origin).receive(path, { instance: INSTANCE, hops: [PEER], cost: 5n }); const live = await announcedView(consumer); await new Promise((resolve) => setImmediate(resolve)); - expect(live.peek().get(path)).toEqual(RouteInfo.normalize({ instance: INSTANCE, hops: [PEER], cost: 5n })); + expect(live.peek().get(path)).toEqual(WireRoute.normalize({ instance: INSTANCE, hops: [PEER], cost: 5n })); // Unannounced, it competes for nothing. const localRoute = origin.route(path, { hidden: true, instance: INSTANCE, cost: 9n }); const local = localRoute.broadcast; await new Promise((resolve) => setImmediate(resolve)); - expect(live.peek().get(path)).toEqual(RouteInfo.normalize({ instance: INSTANCE, hops: [PEER], cost: 5n })); + expect(live.peek().get(path)).toEqual(WireRoute.normalize({ instance: INSTANCE, hops: [PEER], cost: 5n })); // Cheaper wins; a tie falls to the local broadcast. localRoute.announce(); await new Promise((resolve) => setImmediate(resolve)); - expect(live.peek().get(path)).toEqual(RouteInfo.normalize({ instance: INSTANCE, hops: [PEER], cost: 5n })); + expect(live.peek().get(path)).toEqual(WireRoute.normalize({ instance: INSTANCE, hops: [PEER], cost: 5n })); localRoute.setCost(5n); await new Promise((resolve) => setImmediate(resolve)); - expect(live.peek().get(path)).toEqual(RouteInfo.normalize({ instance: INSTANCE, cost: 5n })); + expect(live.peek().get(path)).toEqual(WireRoute.normalize({ instance: INSTANCE, cost: 5n })); local.close(); await settle(); await new Promise((resolve) => setImmediate(resolve)); - expect(live.peek().get(path)).toEqual(RouteInfo.normalize({ instance: INSTANCE, hops: [PEER], cost: 5n })); + expect(live.peek().get(path)).toEqual(WireRoute.normalize({ instance: INSTANCE, hops: [PEER], cost: 5n })); remote.close(); await settle(); @@ -211,7 +211,7 @@ test("a scoped route remains visible when an exact local path is outside the sco await new Promise((resolve) => setImmediate(resolve)); - expect((await announcedView(origin)).peek().get(path)).toMatchObject(RouteInfo.default); + expect((await announcedView(origin)).peek().get(path)).toMatchObject(WireRoute.default); await new Promise((resolve) => setImmediate(resolve)); expect(live.peek().get(path)).toMatchObject({ cost: 5n }); @@ -441,7 +441,7 @@ test("a remote entry resolves by path and retracts on dispose", async () => { // Announced streams include remote entries. const announced = consumer.routes(); - expect(await announced.next()).toMatchObject({ prefix: path, kind: "start", route: RouteInfo.default }); + expect(await announced.next()).toMatchObject({ prefix: path, kind: "start", route: WireRoute.default }); dispose(); expect(await announced.next()).toMatchObject({ prefix: path, kind: "end" }); @@ -493,7 +493,7 @@ test("a local publish shadows a remote entry", async () => { // One path, one announcement, even though both tables route it. const announced = consumer.routes(); - expect(await announced.next()).toMatchObject({ prefix: path, kind: "start", route: RouteInfo.default }); + expect(await announced.next()).toMatchObject({ prefix: path, kind: "start", route: WireRoute.default }); // Dropping the local publish falls back to the remote entry without a retraction. local.close(); @@ -722,7 +722,7 @@ test("an identical reconnect restarts without an instance and is quiet with one" const consumer = origin.consume(); const path = Path.from("room"); const announced = consumer.routes(); - const route = RouteInfo.normalize({ instance, hops: [PEER] }); + const route = WireRoute.normalize({ instance, hops: [PEER] }); const old = wireOf(origin).receive(path, route); expect(await announced.next()).toMatchObject({ prefix: path, kind: "start" }); @@ -1121,7 +1121,7 @@ test("a prefix route can start hidden, withdraw and come back while it keeps yie route.announce(); expect(route.announced).toBe(true); expect(wireOf(consumer).advertised.peek()?.get(prefix)?.[0]?.route).toEqual( - RouteInfo.normalize({ instance: route.instance, cost: 3n }), + WireRoute.normalize({ instance: route.instance, cost: 3n }), ); const first = consumer.request(path); const asked = (await requests.next()).value; @@ -1177,7 +1177,7 @@ test("a request prefers a cheaper received route over an announced local broadca origin, path, provider(upstream), - RouteInfo.normalize({ instance: INSTANCE, hops: [PEER], cost: 1n }), + WireRoute.normalize({ instance: INSTANCE, hops: [PEER], cost: 1n }), ); const localRoute = origin.route(path, { instance: INSTANCE, cost: 3n }); const local = localRoute.broadcast; @@ -1224,13 +1224,13 @@ test("the cheapest received route competes with the local broadcast, not the new origin, path, via("cheap"), - RouteInfo.normalize({ instance: INSTANCE, hops: [PEER], cost: 1n }), + WireRoute.normalize({ instance: INSTANCE, hops: [PEER], cost: 1n }), ); const pricey = serve( origin, path, via("pricey"), - RouteInfo.normalize({ instance: INSTANCE, hops: [PEER], cost: 10n }), + WireRoute.normalize({ instance: INSTANCE, hops: [PEER], cost: 10n }), ); const localRoute = origin.route(path, { instance: INSTANCE, cost: 5n }); const local = localRoute.broadcast; @@ -1238,7 +1238,7 @@ test("the cheapest received route competes with the local broadcast, not the new await new Promise((resolve) => setImmediate(resolve)); expect((await announcedView(consumer)).peek().get(path)).toEqual( - RouteInfo.normalize({ instance: INSTANCE, hops: [PEER], cost: 1n }), + WireRoute.normalize({ instance: INSTANCE, hops: [PEER], cost: 1n }), ); const request = consumer.request(path); await settle(); @@ -1391,7 +1391,7 @@ test("a peer is offered and served the cheapest originated route", async () => { const pricey = origin.routePrefix(prefix, { instance: INSTANCE, cost: 10n }); expect(wireOf(consumer).advertised.peek()?.get(prefix)?.[0]?.route).toEqual( - RouteInfo.normalize({ instance: INSTANCE, cost: 1n }), + WireRoute.normalize({ instance: INSTANCE, cost: 1n }), ); const pending = wireOf(consumer).demand(Path.from("live/cam")); const { value: req } = await cheap.requested().next(); @@ -1403,11 +1403,11 @@ test("a peer is offered and served the cheapest originated route", async () => { const localRoute = origin.route(prefix, { instance: INSTANCE, cost: 5n }); const local = localRoute.broadcast; expect(wireOf(consumer).advertised.peek()?.get(prefix)?.[0]?.route).toEqual( - RouteInfo.normalize({ instance: INSTANCE, cost: 1n }), + WireRoute.normalize({ instance: INSTANCE, cost: 1n }), ); localRoute.setCost(0n); expect(wireOf(consumer).advertised.peek()?.get(prefix)?.[0]?.route).toEqual( - RouteInfo.normalize({ instance: INSTANCE, cost: 0n }), + WireRoute.normalize({ instance: INSTANCE, cost: 0n }), ); local.close(); @@ -1524,7 +1524,7 @@ test("an outranked route keeps serving until its replacement answers", async () const older = new BroadcastProducer(); const keepOlder = older.consume(); - const disposeOlder = serve(origin, path, () => keepOlder.clone(), RouteInfo.normalize({ instance: INSTANCE })); + const disposeOlder = serve(origin, path, () => keepOlder.clone(), WireRoute.normalize({ instance: INSTANCE })); const request = consumer.request(path); await settle(); @@ -1644,13 +1644,13 @@ test("a request on a replaced instance fails over to another route of it", async const primary = new BroadcastProducer(); const keepPrimary = primary.consume(); - const disposePrimary = serve(origin, path, () => keepPrimary.clone(), RouteInfo.normalize({ instance: INSTANCE })); + const disposePrimary = serve(origin, path, () => keepPrimary.clone(), WireRoute.normalize({ instance: INSTANCE })); const replica = new BroadcastProducer(); const disposeReplica = serve( origin, path, provider(replica), - RouteInfo.normalize({ instance: INSTANCE, cost: 5n }), + WireRoute.normalize({ instance: INSTANCE, cost: 5n }), ); const request = consumer.request(path); await settle(); @@ -1658,7 +1658,7 @@ test("a request on a replaced instance fails over to another route of it", async expect(first).toBeDefined(); const restarted = new BroadcastProducer(); - const disposeRestarted = serve(origin, path, provider(restarted), RouteInfo.normalize({ instance: newer })); + const disposeRestarted = serve(origin, path, provider(restarted), WireRoute.normalize({ instance: newer })); await settle(); expect(request.active.peek()).toBe(first); @@ -1697,7 +1697,7 @@ test("a request on a replaced instance fails over to a local replica of it", asy const primary = new BroadcastProducer(); const keepPrimary = primary.consume(); - const disposePrimary = serve(origin, path, () => keepPrimary.clone(), RouteInfo.normalize({ instance: INSTANCE })); + const disposePrimary = serve(origin, path, () => keepPrimary.clone(), WireRoute.normalize({ instance: INSTANCE })); const localRoute = origin.route(path, { instance: INSTANCE, cost: 5n }); const local = localRoute.broadcast; const request = consumer.request(path); @@ -1706,7 +1706,7 @@ test("a request on a replaced instance fails over to a local replica of it", asy expect(first).toBeDefined(); const restarted = new BroadcastProducer(); - const disposeRestarted = serve(origin, path, provider(restarted), RouteInfo.normalize({ instance: newer })); + const disposeRestarted = serve(origin, path, provider(restarted), WireRoute.normalize({ instance: newer })); await settle(); expect(request.active.peek()).toBe(first); @@ -1741,7 +1741,7 @@ test("a stale takeover's refusal leaves a request whose source came back", async const localRoute = origin.route(path, { instance: INSTANCE, cost: 2n }); const local = localRoute.broadcast; - const standby = wireOf(origin).receive(path, RouteInfo.normalize({ instance: INSTANCE, cost: 5n })); + const standby = wireOf(origin).receive(path, WireRoute.normalize({ instance: INSTANCE, cost: 5n })); const asked = standby.requested(); const request = consumer.request(path); await settle(); @@ -1754,7 +1754,7 @@ test("a stale takeover's refusal leaves a request whose source came back", async origin, path, provider(restarted), - RouteInfo.normalize({ instance: newer, cost: 1n }), + WireRoute.normalize({ instance: newer, cost: 1n }), ); await settle(); expect(request.active.peek()).toBe(first); @@ -1783,7 +1783,7 @@ test("a request ends when its winning source goes, even with a standby", async ( const path = Path.from("standby"); const standby = new BroadcastProducer(); - const disposeStandby = serve(origin, path, provider(standby), RouteInfo.normalize({ cost: 5n })); + const disposeStandby = serve(origin, path, provider(standby), WireRoute.normalize({ cost: 5n })); const winner = new BroadcastProducer(); const keepWinner = winner.consume(); const disposeWinner = serve(origin, path, () => keepWinner.clone()); @@ -1841,7 +1841,7 @@ test("a better route's refusal ends a served request", async () => { const consumer = origin.consume(); const served = new BroadcastProducer(); // One instance, so the narrower route serves the same instance and the request follows it. - const disposeWide = serve(origin, Path.from(""), provider(served), RouteInfo.normalize({ instance: INSTANCE })); + const disposeWide = serve(origin, Path.from(""), provider(served), WireRoute.normalize({ instance: INSTANCE })); const request = consumer.request(Path.from("live/cam")); await settle(); @@ -2679,14 +2679,14 @@ test("re-pricing from the current route keeps the instance", () => { const origin = new Producer(); const handle = origin.routePrefix(Path.from("live"), { instance: INSTANCE, cost: 5n }); handle.setCost(1n); - expect(wireOf(handle).info).toEqual(RouteInfo.normalize({ instance: INSTANCE, cost: 1n })); + expect(wireOf(handle).info).toEqual(WireRoute.normalize({ instance: INSTANCE, cost: 1n })); const broadcastRoute = origin.route(Path.from("room"), { hidden: true, instance: INSTANCE, cost: 5n }); const broadcast = broadcastRoute.broadcast; expect(wireOf(broadcastRoute).info).toBeUndefined(); broadcastRoute.announce(); broadcastRoute.setCost(1n); - expect(wireOf(broadcastRoute).info).toEqual(RouteInfo.normalize({ instance: INSTANCE, cost: 1n })); + expect(wireOf(broadcastRoute).info).toEqual(WireRoute.normalize({ instance: INSTANCE, cost: 1n })); broadcastRoute.withdraw(); expect(wireOf(broadcastRoute).info).toBeUndefined(); @@ -3016,7 +3016,7 @@ test("published names refuse navigation segments", () => { const path = Path.from(name); expect(() => origin.route(path, { hidden: true }).broadcast).toThrow(); expect(() => origin.routePrefix(path)).toThrow(); - expect(() => wireOf(origin).receive(path, RouteInfo.default)).toThrow(); + expect(() => wireOf(origin).receive(path, WireRoute.default)).toThrow(); } const scoped = origin.scope(Path.from("room/.."), new Path.Patterns([Path.Pattern.all()])); expect(() => scoped.route(Path.from("cam"), { hidden: true }).broadcast).toThrow(); diff --git a/js/net/src/origin.ts b/js/net/src/origin.ts index 7fc4a48be2b..a54395e7076 100644 --- a/js/net/src/origin.ts +++ b/js/net/src/origin.ts @@ -16,7 +16,7 @@ import * as announce from "./announced.ts"; import type { Credential } from "./auth.ts"; import * as broadcast from "./broadcast.ts"; import { StreamCode, StreamError } from "./error.ts"; -import { type Cost, RouteInfo, routesEqual } from "./hop.ts"; +import { type Cost, routesEqual, WireRoute } from "./hop.ts"; import * as Instance from "./instance.ts"; import { compareRouteCandidates, @@ -44,8 +44,7 @@ import { wireOf, } from "./wire.ts"; -export type { Cost, Hop, RouteInfo } from "./hop.ts"; -export { HopSchema, isAnonymous } from "./hop.ts"; +export type { Cost, RouteInfo } from "./hop.ts"; /** The rooted permissions shared by a handle and every route it inserts. */ class Scope { @@ -286,7 +285,7 @@ interface RouteEntry { readonly scope: Scope; /** The paths the entry may serve beneath its prefix, when its producer is scoped. */ readonly claim?: Path.Patterns; - readonly route: Signal; + readonly route: Signal; readonly originated: boolean; readonly server?: ServeState; } @@ -318,7 +317,7 @@ function preferredEntry( prefix: Path.Valid, entries: readonly RouteEntry[], skip?: (entry: RouteEntry) => boolean, - others: readonly RouteInfo[] = [], + others: readonly WireRoute[] = [], ): RouteEntry | undefined { const eligible = entries.filter((entry) => !skip?.(entry)); // `others` compete at the prefix too, such as a broadcast announced here at the path. @@ -528,7 +527,7 @@ class OriginState { // directions echo-free. created: Map | undefined = new Map(); local = new VersionedSignal | undefined>(new Map()); - advertisedLocal = new VersionedSignal | undefined>(new Map()); + advertisedLocal = new VersionedSignal | undefined>(new Map()); routes = new VersionedSignal | undefined>(new Map()); #snapshotVersion = ""; @@ -569,7 +568,7 @@ class OriginState { for (const [path, front] of this.local.peek() ?? []) { const local = { identity: front, - route: advertised?.get(path) ?? RouteInfo.default, + route: advertised?.get(path) ?? WireRoute.default, exact: true, }; const list = out.get(path); @@ -1435,7 +1434,7 @@ export class Producer implements Table { const created = this.#state.created; if (!created) throw new Error("origin is closed"); // Normalized first, so a bad cost throws before anything is created. - let info = RouteInfo.normalize({ + let info = WireRoute.normalize({ instance: options.instance ?? Instance.random(), epoch: options.instance === undefined ? 0n : options.epoch, cost: options.cost, @@ -1490,7 +1489,7 @@ export class Producer implements Table { } answerJob(job); }; - const change = (next: RouteInfo) => { + const change = (next: WireRoute) => { if (producer.closed.peek() !== undefined) throw new Error("broadcast is closed"); if (!this.#state.created) throw new Error("origin is closed"); info = next; @@ -1503,12 +1502,12 @@ export class Producer implements Table { announce, withdraw: () => this.#retractExact(path, front), announced, - change: (update) => change(RouteInfo.normalize({ ...info, ...update })), + change: (update) => change(WireRoute.normalize({ ...info, ...update })), requested: async function* () {}, close: release, info: () => (announced() ? this.#state.advertisedLocal.peek()?.get(path) : undefined), update: (next) => { - const named = RouteInfo.normalize(next); + const named = WireRoute.normalize(next); info = named.instance === undefined ? { ...named, instance: info.instance, epoch: info.epoch } : named; announce(); }, @@ -1517,7 +1516,7 @@ export class Producer implements Table { return route; } - #advertiseExact(path: Path.Valid, front: broadcast.Consumer, route: RouteInfo): void { + #advertiseExact(path: Path.Valid, front: broadcast.Consumer, route: WireRoute): void { if (!this.#state.local.peek()) throw new Error("origin is closed"); if (this.#state.created?.get(path)?.front !== front) throw new Error("broadcast is closed"); // Both maps move together, so every reader sees the broadcast and its route at once. @@ -1560,7 +1559,7 @@ export class Producer implements Table { * {@link route} instead, so subscribers can enumerate them. */ routePrefix(prefix: Path.Valid, options: RouteOptions = {}): Route { - const info = RouteInfo.normalize({ + const info = WireRoute.normalize({ instance: options.instance, epoch: options.epoch, cost: options.cost, @@ -1570,11 +1569,11 @@ export class Producer implements Table { } /** Land a route a peer announced, taken as given. Not originated, so a session never announces it back. */ - #receive(prefix: Path.Valid, route?: Partial): Route { - return this.#serving(prefix, RouteInfo.normalize(route), false, false, true); + #receive(prefix: Path.Valid, route?: Partial): Route { + return this.#serving(prefix, WireRoute.normalize(route), false, false, true); } - #serving(prefix: Path.Valid, route: RouteInfo, originated: boolean, publishes: boolean, visible: boolean): Route { + #serving(prefix: Path.Valid, route: WireRoute, originated: boolean, publishes: boolean, visible: boolean): Route { prefix = this.#scope.prefix(prefix); // A route that names no instance serves one of its own. if (route.instance === undefined) route = { ...route, instance: Instance.random(), epoch: 0n }; @@ -1645,7 +1644,7 @@ export class Producer implements Table { if (visible) insert(); } - const update = (next: RouteInfo) => { + const update = (next: WireRoute) => { open(); const previous = entry.route.peek().instance; const restart = inserted && previous !== next.instance; @@ -1667,13 +1666,13 @@ export class Producer implements Table { remove(() => server.reset()); }, announced: () => inserted && this.#state.routes.peek() !== undefined, - change: (changed) => update(RouteInfo.normalize({ ...entry.route.peek(), ...changed })), + change: (changed) => update(WireRoute.normalize({ ...entry.route.peek(), ...changed })), requested: () => serveRequests(server, publisher), close: release, info: () => (inserted && this.#state.routes.peek() ? entry.route.peek() : undefined), update: (next) => { // A route naming no instance keeps the one it serves. - const named = RouteInfo.normalize(next); + const named = WireRoute.normalize(next); const current = entry.route.peek(); update( named.instance === undefined @@ -2636,11 +2635,11 @@ interface RouteControl { announce(): void; withdraw(): void; announced(): boolean; - change(update: Partial>): void; + change(update: Partial>): void; requested(): AsyncIterableIterator; close(): void; - info(): RouteInfo | undefined; - update(info: Partial): void; + info(): WireRoute | undefined; + update(info: Partial): void; } /** The requests arriving on a prefix route's `server`, each answerable with a route of `publisher`'s when it has one. */ diff --git a/js/net/src/resume.model.test.ts b/js/net/src/resume.model.test.ts index 07e179baf35..fa9ee178bfe 100644 --- a/js/net/src/resume.model.test.ts +++ b/js/net/src/resume.model.test.ts @@ -17,7 +17,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, RouteInfo } from "./hop.ts"; +import { HopSchema, 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"; @@ -447,7 +447,7 @@ class Model { up(instance: number, slot: number): void { const publisher = this.instances[instance]; if (publisher.routes[slot]) return; - const route = RouteInfo.normalize({ + const route = WireRoute.normalize({ instance: INSTANCES[instance], hops: [HopSchema.parse(BigInt(10 * (instance + 1) + slot))], // The second instance's routes all undercut the first's. diff --git a/js/net/src/resume.test.ts b/js/net/src/resume.test.ts index c046d32d615..7f30a51a18f 100644 --- a/js/net/src/resume.test.ts +++ b/js/net/src/resume.test.ts @@ -3,7 +3,7 @@ import { Manual, Milli, Nano, yieldNow } from "@moq/clock"; import { Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts"; import { NotFound, SessionCode, SessionError, StreamCode, StreamError } from "./error.ts"; import { type Consumer as GroupConsumer, Producer as GroupProducer } from "./group.ts"; -import { RouteInfo } from "./hop.ts"; +import { WireRoute } from "./hop.ts"; import type { Session as IetfSession } from "./ietf/session.ts"; import { Subscriber as IetfSubscriber } from "./ietf/subscriber.ts"; import { Version as IetfVersion } from "./ietf/version.ts"; @@ -39,7 +39,7 @@ async function isPending(promise: Promise): Promise { /** A stand-in session announcing `path` under the shared instance at `cost`, serving `source`. */ function serve(origin: Producer, source: BroadcastProducer, cost: bigint) { - const handle = wireOf(origin).receive(path, RouteInfo.normalize({ instance: INSTANCE, cost })); + const handle = wireOf(origin).receive(path, WireRoute.normalize({ instance: INSTANCE, cost })); void (async () => { for await (const request of handle.requested()) request.serve(source.consume()); })(); @@ -1247,7 +1247,7 @@ test("between routes a reader keeps reading the copy it has", async () => { expect(drain(sub)).toEqual([0n]); // The next route has not answered when the old one is retracted. - const next = wireOf(origin).receive(path, RouteInfo.normalize({ instance: INSTANCE, cost: 1n })); + const next = wireOf(origin).receive(path, WireRoute.normalize({ instance: INSTANCE, cost: 1n })); const asked = next.requested(); disposeA(); await settle(); @@ -2136,7 +2136,7 @@ test("a fetched group that fails on the route still serving waits for the next r const b = new BroadcastProducer(); const ta = copy(a); const tb = copy(b); - // RouteInfo a's request handler holds the refetch of its failed group open, as Rust's tests do + // WireRoute a's request handler holds the refetch of its failed group open, as Rust's tests do // with `requests()`: without one, a miss there is NotFound at once. const pending = ta.producer.requests(); const failing = ta.write(5n, 1, false); @@ -2168,7 +2168,7 @@ test("a group handed out already failed with its route still continues on the ne const b = new BroadcastProducer(); const ta = copy(a); const tb = copy(b); - // RouteInfo a's request handler holds the refetch of its failed group open until the next route. + // WireRoute a's request handler holds the refetch of its failed group open until the next route. const pending = ta.producer.requests(); front.serve(a.consume()); const sub = front.consumer.track("seq").subscribe(); diff --git a/js/net/src/wire.ts b/js/net/src/wire.ts index f20374076f5..5913f25a88e 100644 --- a/js/net/src/wire.ts +++ b/js/net/src/wire.ts @@ -11,7 +11,7 @@ import type { Dispose, GetPromise, Getter } from "@moq/signals"; import type * as broadcast from "./broadcast.ts"; import type * as datagram from "./datagram.ts"; import type { Consumer as GroupConsumer } from "./group.ts"; -import type { RouteInfo } from "./hop.ts"; +import type { WireRoute } from "./hop.ts"; import type * as Instance from "./instance.ts"; import type { Lister, Tracks } from "./listing.ts"; import type * as origin from "./origin.ts"; @@ -62,7 +62,7 @@ export interface OriginProducer { /** Whether an advertised prefix overlaps the handle's allowed paths. */ accepts(prefix: Path.Valid): boolean; /** Land a route a peer announced, taken as given and never forwarded back to a peer. */ - receive(prefix: Path.Valid, route?: Partial): origin.Route; + receive(prefix: Path.Valid, route?: Partial): origin.Route; attach(discovery: boolean): Dispose; /** * Hold the origin's announcement streams overlapping `prefix` unsynced until @@ -80,13 +80,13 @@ export interface OriginProducer { /** The protocol-facing operations behind an origin route. */ export interface Route { /** The metadata the route is advertised with, or undefined while hidden. */ - readonly info: RouteInfo | undefined; + readonly info: WireRoute | undefined; /** * Advertise the route with `info` as given, as a session's update does: a named instance * replaces the route's, which restarts its readers; otherwise it keeps the route's own. * Announces a hidden route. */ - update(info: Partial): void; + update(info: Partial): void; } /** The protocol-facing operations behind an origin consumer. */ @@ -103,7 +103,7 @@ export interface OriginConsumer { /** One originated advertisement exposed to the publishing wire. */ export interface Advertised { readonly identity: object; - readonly route: RouteInfo; + readonly route: WireRoute; /** The paths a scoped route may serve beneath its prefix, relative like its key; unset for the whole subtree. */ readonly claim?: Path.Patterns; /** @@ -117,7 +117,7 @@ export interface Advertised { /** What names a stream: an advertisement, and the instance its route serves. */ export interface Served { readonly identity: object; - readonly route: Pick; + readonly route: Pick; } /** diff --git a/js/room/src/room.test.ts b/js/room/src/room.test.ts index 16beb40dcf4..2062c81f176 100644 --- a/js/room/src/room.test.ts +++ b/js/room/src/room.test.ts @@ -21,7 +21,7 @@ test("room restores the announce prefix and reconciles local identity changes", prefix: Net.Path.from("room-a/bob/camera.hang"), captures: [Net.Path.Pattern.literal(Net.Path.from("bob/camera.hang"))], kind: "present", - route: { hops: [], cost: 0n }, + route: { hops: [], cost: 0n, anonymous: false }, }; const stream = { next: async () => { diff --git a/quest/m1/api-audit/README.md b/quest/m1/api-audit/README.md index ba3863d96f1..1c3e73bdc31 100644 --- a/quest/m1/api-audit/README.md +++ b/quest/m1/api-audit/README.md @@ -1,4 +1,4 @@ -# A smaller, safer API than release +# [M] A smaller, safer API than release ## Goal @@ -8,6 +8,10 @@ or is removed or made private. Overlapping operations are collapsed into one. Names mirror across Rust, JS, and the bindings. Every break says how to migrate. +This epic's own work, now that its children have landed: diff `main`'s public +API against `release`'s once more, and make private, remove, or record here +each surface added since the audit below that breaks these rules. + Non-goals: redesigning independently scoped surfaces ([subscribe ranges](/quest/m2/subscribe-ranges/README.md), [archives](/doc/concept/archives.md), @@ -72,10 +76,6 @@ Rejected in planning: - A follow policy enum folding `linger` and `stitch`: one name per meaning (the export wait is `--follow`) fixes the confusion more cheaply. -## Required - -- [Routes are the origin API](/quest/m1/api-audit/route/README.md) - apps announce exact or prefix routes through one `Route` handle that owns its broadcast and carries an `instance`, prefix routes can serve a held broadcast, and readers get a listing plus `follow` - ## Related - [Main is no slower than release](/quest/m1/release-perf/README.md) - the other release-readiness check diff --git a/quest/m1/api-audit/route/README.md b/quest/m1/api-audit/route/README.md deleted file mode 100644 index 8b01bb75f62..00000000000 --- a/quest/m1/api-audit/route/README.md +++ /dev/null @@ -1,175 +0,0 @@ -# Routes are the origin API - -## Goal - -An application talks to the origin only in routes, as the wire does. On the -publishing side, ownership runs origin → route → broadcast → track → group → -frame: a `Route` handle, for an exact path or a prefix, creates and owns -its broadcast. Every route carries an `instance` naming one continuous -run of group numbers, and an `epoch` that is private and only orders a -single instance's incarnations. On the read side the chain is origin → -route(path, instance) → broadcast, and consumers see only the instance. A -prefix route answers each request by serving a broadcast it already holds, -or by creating the path's exact route under its instance. Readers see a -listing of paths, plus `follow` and `request` for instance changes, instead -of four announce event -kinds. Rust, JS, moq-ffi, moq-c and the wrappers -mirror it. - -Non-goals: the route layer's wire messages and federation -([Routes and announces](/quest/m2/cluster-routing/routes/README.md)), lite-07 -takeover ([announce takeover](/quest/m2/announce-takeover.md)), and any -moq-transport instance ([moq-transport carries no epoch](https://github.com/moq-dev/moq/pull/7239)). - -## Plan - -Planned 2026-10-30 (`/quest-plan`, maintainer). It started from an external -relay operator's question about [moq-dev/moq#6496](https://github.com/moq-dev/moq/pull/6496). -Their relay claims `requests("")`, a separate task publishes the pulled -broadcast at the exact path, and the client's first SUBSCRIBE fails with -Unroutable. A probe over `transport::memory` reproduced this on -moq-transport-18/22, moq-lite-06 and moq-lite-07-wip, whatever the handler -does: prepare and publish, drop, reject, or the crate-private `accept`. It -is the cold-start reset. The downstream's claim-prefix selection is replaced -once the exact route lands (`Selected::change`, -`rs/moq-net/src/model/origin.rs:4255-4299`). The one answer that never -resets is serving a held broadcast with no separate exact route. -The user's "it worked before #6496" did not reproduce on any older tree, -including one before [moq-dev/moq#5678](https://github.com/moq-dev/moq/pull/5678). -Their proposed `accept_published(&Publication)` would not avoid the reset, -so it was dropped. Their relay instead uses `Request::serve` for its held broadcast. - -The maintainer then asked for an audit of the origin, claim and epoch API. -Four read-only audits covered the Rust surface, JS and the bindings, the -epoch concept and its history, and moq.pro's usage. Findings that shaped -the decisions: - -- Every production publisher calls `Epoch::mint()` once per publication; - apps choose only when. The CLI already refuses a shared epoch. -- `Route` mixes what an app sets (epoch, cost, auth) with what relays fill - in (hops, via, source). `Route::default()` is epochless, so forgetting - `with_epoch`, or re-pricing with `Route::default().with_cost(..)`, - silently gives up resume. -- `Publication`, `Prepared`, `Announcer` and `Requests` describe one - lifecycle: unannounced, then announced. Claims and prepared answers - cannot carry cost or auth. -- Almost every caller merges `Start`/`Update`/`Restart`. Only moq-boy's - input handles `Restart` alone, and no JS consumer does. -- The worst internals exist for epochless routes, not because of epochs: - `Instance::Route(generation)`, `renew`, the held restart, and Selection - retirement. -- moq.pro needs prefix routes answered on demand. Its `.dash` dashboard - (`rs/dash/src/dashboard.rs`) answers with prepare and publish and works - around the reset in three places. Its sync-ingest mirror - (`rs/edge/src/sync/ingest.rs`) answers with `request.accept(broadcast)` - under a forwarded route. On `main` both calls are crate-private, so the - mirror breaks at its next moq bump. -- The selection order is documented three ways: `doc/concept/identity.md`, - the `Consumer::request` rustdoc, and the `Route.cost` doc. None of them - says that a more specific prefix outranks the epoch. - -Decision prompts (options separated by semicolons; the chosen one is marked ✅, -and every option after it was rejected): - -- Goal for the user's question: add a same-origin resolve; keep the reset; - fold it into takeover. The maintainer instead asked for the API audit. -- Mint the epoch in the library: ✅ yes, per announce; optional only; - leave as is. -- Claims: the maintainer asked what moq.pro needs. ✅ Keep prefix routes - with requests answered dynamically, since moq.pro's `.dash` and mirror - need them. -- Request answers: ✅ announce and serve; serve only; announce only. -- Lifecycle: ✅ one `Route` type for exact and prefix routes; two typed - route kinds. This came from "broadcasts don't actually exist on the - wire; only routes do". -- Where the epoch lives: ✅ on the route, minted at each announce; per - broadcast. A re-announce after js/publish's toggle is a restart, never a - splice. -- Announce events: ✅ shrink them, with continuity in `follow`; keep four - plus `Takeover`; keep four without it. -- Prefix routes get an instance like any route: ✅ yes, so a crashed - `.dash` that comes back up wins with its newer epoch. -- Explicit instance override for forwarders (mirror, archive resume, FFI): - ✅ yes; crate-private only. -- Pool tie-break: ✅ keep the per-path hash; newest first; out of scope. - The maintainer then reframed pools and restarts as identity. Routes with - one identity are runs of one publisher; different identities are - interchangeable and spread by hash. -- Naming: ✅ `identity` (a string, possibly a public key later) and `epoch` - (start time), paired as ✅ `Instance`. "group" is taken, and the UUIDv7 - epoch is retired. -- Wire: ✅ two explicit fields; packed into the UUIDv7. -- Epochless off the wire: ✅ the receiving hop mints one; keep it - wire-only. -- Run uniqueness: ✅ start time only. Pool hosts each use their own - identity, such as a hostname, so no two hosts share one. -- Ranking: ✅ newest-wins only within an identity, cost before the hash; - hash before cost. -- Default identity: ✅ random per process; hostname (it would leak machine - names across a CDN). -- Identity an edge mints: ✅ the session ID; auth subject, else session. -- Epochless machinery: ✅ [instance](https://github.com/moq-dev/moq/pull/7489) - deletes it; leave it to routes.md. -- Milestone: ✅ m1 under the API audit; m1 standalone; m2. -- The external user's PR offer: ✅ we do all of it; offer them serve. - -Second round, the same day. The maintainer asked whether broadcasts should -hang off routes (origin → route → broadcast → track → group → frame). An -audit found the producer side inverted today: the broadcast holds its own -announcer (`rs/moq-net/src/model/broadcast.rs:252-292`). A standalone -broadcast cannot be announced in Rust. A consumer's broadcast, by contrast, -moves between the routes that reach it (`origin.rs:6730`). These decisions -supersede the epoch-minting, pairing and run-uniqueness answers above: - -- Producer ownership: ✅ the route creates and owns its broadcast; pass a - broadcast in. -- Mint point: ✅ per Route, which keeps its identity across withdraw and - re-announce, so js/publish's toggle continues; per announce. -- Read side: ✅ origin → route(path, identity) → broadcast, with only the - identity public; the instance on the consumer; a consumer route handle. - The maintainer added: "we can never stitch broadcasts over two different - identities, only different epochs". The epoch is only a restart - tie-break, relative to its identity, and need not be a clock. moq.pro - records start times itself. -- Epoch change under a reader: the maintainer answered "that would be a - new identity?". So identity is one continuous sequence space, and a - publisher whose sequences restart is a new identity. ✅ Confirmed: the - default is a fresh identity per stream, and a stable identity promises - continued sequences and an increasing epoch. `Instance` and the - hostname advice for pools are dropped. -- Edge minting: ✅ per announcement (the session ID plus the announcement's - ID); per session, which would splice a job restarted on one session. -- Takeover: ✅ re-plan it around identity, where a job's exact route - inherits its claim's identity and ANNOUNCE_TAKEOVER is dropped; keep the - predecessor-ID plan. - The predecessor design then landed on main in - [moq-dev/moq#6994](https://github.com/moq-dev/moq/pull/6994). On - 2026-10-31 the maintainer kept identity: [announce takeover](/quest/m2/announce-takeover.md) - now also removes that work, so only one continuity rule remains. - -Third round, 2026-11-01, answering -[moq-dev/moq#7489](https://github.com/moq-dev/moq/pull/7489)'s open decisions: - -- Naming: ✅ rename `identity` to `instance` in that PR, before it lands, - so there is one breaking change instead of two; keep `identity`. - "Identity" reads as who publishes, which clashes with auth subjects - ([moq-dev/moq#6992](https://github.com/moq-dev/moq/pull/6992)). The token - names one continuous run of group numbers at a path, like a cloud - instance ID that survives a reboot, and its epoch counts the boots. A - broadcast's identity is its path plus its instance; the decisions above - say `identity` for what is now `instance`. -- A CLI flag for a stable instance: ✅ none, the stable instance stays a - route option in every library and `moq` refuses the flag; add - `--instance` and an epoch flag. - -The epic owns no work of its own: each child updates the docs it makes -stale, including `doc/concept/identity.md`. - -## Required - -- [Transit facts stay read-only](/quest/m1/api-audit/route/facts.md) - `Hop`, `Hops` and `HopLimit` leave the public API, and JS `RouteInfo` hides epoch and auth - -## Related - -- [A job's exact route continues its claim's readers](/quest/m2/announce-takeover.md) - a job's route inherits its claim's instance, so lite-07 readers keep the first subscribe -- [Routes and announces](/quest/m2/cluster-routing/routes/README.md) - the wire route layer; instances take over its epochless deletion diff --git a/quest/m1/api-audit/route/facts.md b/quest/m1/api-audit/route/facts.md deleted file mode 100644 index 6d7e201d9ef..00000000000 --- a/quest/m1/api-audit/route/facts.md +++ /dev/null @@ -1,42 +0,0 @@ -# [L] Transit facts stay read-only - -## Goal - -Hops, via, source, the epoch and the anonymous mark are facts the origin and -the relays fill in, never something an application sets. `Hop`, `Hops` and -`HopLimit` leave the public API in Rust, JS and the bindings, and a received -announcement exposes its hop chain as plain ids. JS `RouteInfo` stops exposing -`epoch` and `auth`, as Rust's already does not. - -Non-goals: the route handle and its options, which -[One Route handle](https://github.com/moq-dev/moq/pull/7806) landed, and the -wire. - -## Plan - -Split from [One Route handle](https://github.com/moq-dev/moq/pull/7806), which -made `origin::RouteInfo` read-only (getters, no public builders) and moved app -settings to `RouteOptions`, but kept these types public because removing them -reaches every origin construction: - -- **Rust.** `origin::Config::new(Hop)` and `Config::hop` take a plain non-zero - id, `Config::max_hops` a plain count, and `Producer::hop()`/`Consumer::hop()` - return ids or go crate-private. `RouteInfo::hops()` returns ids rather than - `&Hops`. `moq_net::fuzz` keeps whatever benches and tests need to build relay - chains (`fuzz::route_info`, `fuzz::excluding`). About 100 test and bench - sites build a config with `Hop::new(..)`; moq-relay's cluster id and - moq-ffi/moq-c already pass plain ids. -- **JS.** Stop exporting `Hop`, `HopSchema` and `isAnonymous` from `@moq/net`'s - entry, keep `RouteInfo` to instance, cost, hops (as bigints) and anonymity, - and move `epoch` and `auth` to the internal wire view (`wireOf`) that - sessions already use. -- **Docs and MIGRATE.** `rs/moq-net/MIGRATE.md`, `js/net/MIGRATE.md` and - `doc/lib/rs/moq-net.md`. - -Run `just check`. - -Public API: breaking in moq-net and @moq/net. Wire: none. - -## Related - -- [Routes are the origin API](/quest/m1/api-audit/route/README.md) - the epic this finishes diff --git a/quest/m2/announce-takeover.md b/quest/m2/announce-takeover.md index 710e5ae1799..7f0c565d315 100644 --- a/quest/m2/announce-takeover.md +++ b/quest/m2/announce-takeover.md @@ -26,7 +26,7 @@ edge mints a new instance for each announcement, ## Plan -Re-planned 2026-10-30 (maintainer, the [route epic](/quest/m1/api-audit/route/README.md)): +Re-planned 2026-10-30 (maintainer, the [route epic](https://github.com/moq-dev/moq/blob/1a6ac473d75fcbfd5d23bdbdfd64eb4750b077ad/quest/m1/api-audit/route/README.md)): continuity is the instance promise, not an `ANNOUNCE_TAKEOVER` predecessor ID. An instance is one continuous sequence space at a path, so the exact route and the claim's answer are the same consumer route, @@ -128,7 +128,7 @@ separate from the identity rewrite of this Plan, which landed with [moq-dev/moq#7420](https://github.com/moq-dev/moq/pull/7420). "We're replacing EPOCH with IDENTITY soon" (maintainer, 2026-10-31). The broadcast "identity" was renamed `instance` on 2026-11-01 (maintainer, in -[the route API audit](/quest/m1/api-audit/route/README.md), landed in +[the route API audit](https://github.com/moq-dev/moq/blob/1a6ac473d75fcbfd5d23bdbdfd64eb4750b077ad/quest/m1/api-audit/route/README.md), landed in [moq-dev/moq#7489](https://github.com/moq-dev/moq/pull/7489)), so that IDENTITY is now the instance. diff --git a/quest/m2/cluster-routing/routes/session.md b/quest/m2/cluster-routing/routes/session.md index 53002f8076c..a6f2c1a9dc0 100644 --- a/quest/m2/cluster-routing/routes/session.md +++ b/quest/m2/cluster-routing/routes/session.md @@ -111,7 +111,7 @@ mints at its own time, so mint order outranks cost, preference, and the local-broadcast tie and relays disagree on a pool path's winner, while ranking a minted epoch last keeps the renewal it was meant to delete. -Moved 2026-10-30 (maintainer, the [route epic](/quest/m1/api-audit/route/README.md)): +Moved 2026-10-30 (maintainer, the [route epic](https://github.com/moq-dev/moq/blob/1a6ac473d75fcbfd5d23bdbdfd64eb4750b077ad/quest/m1/api-audit/route/README.md)): [Instance and epoch](https://github.com/moq-dev/moq/pull/7489) now deletes that epochless machinery, so the route layer no longer does. A session mints an `instance` (`~` plus random bits) for any route that diff --git a/rs/moq-audio/src/decode/consumer.rs b/rs/moq-audio/src/decode/consumer.rs index f42deec3cbb..80fee172773 100644 --- a/rs/moq-audio/src/decode/consumer.rs +++ b/rs/moq-audio/src/decode/consumer.rs @@ -926,7 +926,7 @@ mod tests { /// An origin at `hop`, its driver spawned. fn origin(hop: u64) -> moq_net::origin::Producer { - let config = moq_net::origin::Config::new(moq_net::Hop::new(hop).unwrap()); + let config = moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap()); let (producer, driver) = moq_net::origin::Producer::new(config); tokio::spawn(moq_net::time::run(driver)); producer diff --git a/rs/moq-c/src/origin.rs b/rs/moq-c/src/origin.rs index ead137e4192..481ca1d27f2 100644 --- a/rs/moq-c/src/origin.rs +++ b/rs/moq-c/src/origin.rs @@ -117,7 +117,7 @@ impl AnnouncedRecord { _captures: captures, capture_views, kind, - hops: update.route.hops().iter().map(|hop| hop.id()).collect(), + hops: update.route.hops().collect(), cost: update.route.cost().value(), instance: update.route.instance().to_string(), } diff --git a/rs/moq-c/src/test.rs b/rs/moq-c/src/test.rs index 97f72e72e86..1484f49aaf1 100644 --- a/rs/moq-c/src/test.rs +++ b/rs/moq-c/src/test.rs @@ -7711,7 +7711,7 @@ fn announce_route_hops_cross_a_relay_session() { let sink = id(moq_origin_create()); let hops = { let state = State::lock(); - [source, relay].map(|origin| state.origin.get(Id::try_from(origin).unwrap()).unwrap().hop().id()) + [source, relay].map(|origin| state.origin.get(Id::try_from(origin).unwrap()).unwrap().hop().get()) }; let server_cb = Callback::new(); let (server, addr, fingerprint) = listen(&server_cb); diff --git a/rs/moq-crypto/tests/transport.rs b/rs/moq-crypto/tests/transport.rs index 8735d7efe5d..6d3c7a3dbd0 100644 --- a/rs/moq-crypto/tests/transport.rs +++ b/rs/moq-crypto/tests/transport.rs @@ -6,7 +6,7 @@ use std::time::Duration; use moq_crypto::e2ee::Credential; use moq_crypto::e2ee::credential::Config; -use moq_net::{Hop, Timestamp, Version}; +use moq_net::{Timestamp, Version}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; /// A millisecond track: the frames written here carry timestamps. @@ -17,7 +17,8 @@ fn timed() -> moq_net::track::Info { const TEST_TIMEOUT: Duration = Duration::from_secs(10); fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); tokio::spawn(support::harness::run(driver)); producer } diff --git a/rs/moq-ffi/src/origin.rs b/rs/moq-ffi/src/origin.rs index 8ffe5fc59c8..36b262da812 100644 --- a/rs/moq-ffi/src/origin.rs +++ b/rs/moq-ffi/src/origin.rs @@ -100,7 +100,7 @@ pub struct MoqRouteInfo { impl From for MoqRouteInfo { fn from(route: moq_net::origin::RouteInfo) -> Self { Self { - hops: route.hops().iter().map(|origin| origin.id()).collect(), + hops: route.hops().collect(), cost: route.cost().value(), anonymous: route.is_anonymous(), instance: route.instance().to_string(), diff --git a/rs/moq-mux/src/container/test_util.rs b/rs/moq-mux/src/container/test_util.rs index 42d6faca37e..7cb82777fd4 100644 --- a/rs/moq-mux/src/container/test_util.rs +++ b/rs/moq-mux/src/container/test_util.rs @@ -317,7 +317,7 @@ pub(crate) fn common_offset( /// An origin at `hop`, its driver spawned. pub(crate) fn origin(hop: u64) -> moq_net::origin::Producer { - let config = moq_net::origin::Config::new(moq_net::Hop::new(hop).unwrap()); + let config = moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap()); let (producer, driver) = moq_net::origin::Producer::new(config); tokio::spawn(moq_net::time::run(driver)); producer diff --git a/rs/moq-net-tests/tests/announce_allocs.rs b/rs/moq-net-tests/tests/announce_allocs.rs index 90fe6b3905c..7e01c4bdd7c 100644 --- a/rs/moq-net-tests/tests/announce_allocs.rs +++ b/rs/moq-net-tests/tests/announce_allocs.rs @@ -14,7 +14,7 @@ use std::alloc::{GlobalAlloc, Layout, System}; use std::cell::Cell; use moq_net::{ - Client, Hop, Hops, Path, Pattern, Patterns, Server, Version, + Client, Path, Pattern, Patterns, Server, Version, fuzz::{decode_path, decode_subscribe, encode_path, encode_subscribe}, kio, origin, time::{Driver, Instant}, @@ -78,12 +78,10 @@ static ALLOCATOR: Counting = Counting; /// Land `peer`'s route at `path`, as a session does: one hop, at `cost`. fn peer_route(producer: &origin::Producer, path: &'static str, peer: u64, cost: u64) -> origin::Route { - let mut hops = Hops::new(); - hops.push(Hop::new(peer).unwrap()).unwrap(); moq_net::fuzz::requests_route( producer, Path::from_static(path), - moq_net::fuzz::route_info(hops, cost, None), + moq_net::fuzz::route_info([peer], cost, None), ) .unwrap() } @@ -250,14 +248,14 @@ async fn a_lite_request_keeps_one_copy_of_its_track_name() { // before the SUBSCRIBE, so the publisher serves two requests to 03's one. for (version, requests) in [("moq-lite-03", 1), ("moq-lite-07-wip", 2)] { let version: Version = version.parse().unwrap(); - let (publisher, driver) = origin::Producer::new(origin::Config::new(Hop::new(1).unwrap())); + let (publisher, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(1).unwrap())); spawn(driver); let broadcast = publisher.route("room", origin::RouteOptions::default()).unwrap(); let track = broadcast .broadcast() .create_track(TRACK, track::Info::default()) .unwrap(); - let (viewer, driver) = origin::Producer::new(origin::Config::new(Hop::new(2).unwrap())); + let (viewer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(2).unwrap())); spawn(driver); let mut transport = memory::Config::default(); diff --git a/rs/moq-net-tests/tests/integration/hop_limit.rs b/rs/moq-net-tests/tests/integration/hop_limit.rs index c9b7ef88210..84ef63e2785 100644 --- a/rs/moq-net-tests/tests/integration/hop_limit.rs +++ b/rs/moq-net-tests/tests/integration/hop_limit.rs @@ -10,10 +10,11 @@ use crate::support::{ watch, }; -use moq_net::{Hop, cache, origin}; +use moq_net::{cache, origin}; +use std::num::NonZeroUsize; fn produce_origin(hop: u64) -> origin::Producer { - let mut config = origin::Config::new(Hop::new(hop).unwrap()); + let mut config = origin::Config::new(std::num::NonZeroU64::new(hop).unwrap()); config.pool = cache::Pool::unbounded(); let (producer, driver) = origin::Producer::new(config); spawn(driver); @@ -40,8 +41,8 @@ async fn hop_limit_bounds_receive_and_send() { ] { let version = name.parse().unwrap(); let source = produce_origin(1); - let mut config = origin::Config::new(Hop::new(2).unwrap()); - config.max_hops = origin::HopLimit::new(2).unwrap(); + let mut config = origin::Config::new(std::num::NonZeroU64::new(2).unwrap()); + config.max_hops = NonZeroUsize::new(2).unwrap(); config.pool = cache::Pool::unbounded(); let (relay, driver) = origin::Producer::new(config); spawn(driver); @@ -51,14 +52,7 @@ async fn hop_limit_bounds_receive_and_send() { let mut received = watch(relay.consume().routes()); let mut sent = watch(sink.consume().routes()); kio::clock::sim::idle().await; - let route = |count: u64| { - moq_net::fuzz::route_info( - moq_net::Hops::try_from((100..100 + count).map(|id| Hop::new(id).unwrap()).collect::>()) - .unwrap(), - 0, - None, - ) - }; + let route = |count: u64| moq_net::fuzz::route_info(100..100 + count, 0, None); let _long = forward(&source, "long", route(2)); let _boundary = forward(&source, "boundary", route(1)); let short = forward(&source, "short", route(0)); @@ -106,8 +100,8 @@ async fn hop_limit_falls_back_to_a_forwardable_route() { let version = name.parse().unwrap(); let near = produce_origin(1); let far = produce_origin(4); - let mut config = origin::Config::new(Hop::new(2).unwrap()); - config.max_hops = origin::HopLimit::new(3).unwrap(); + let mut config = origin::Config::new(std::num::NonZeroU64::new(2).unwrap()); + config.max_hops = NonZeroUsize::new(3).unwrap(); config.pool = cache::Pool::unbounded(); let (relay, driver) = origin::Producer::new(config); spawn(driver); @@ -118,18 +112,7 @@ async fn hop_limit_falls_back_to_a_forwardable_route() { let mut sent = watch(sink.consume().routes()); kio::clock::sim::idle().await; - let route = |first: u64, count: u64, cost: u64| { - moq_net::fuzz::route_info( - moq_net::Hops::try_from( - (first..first + count) - .map(|id| Hop::new(id).unwrap()) - .collect::>(), - ) - .unwrap(), - cost, - None, - ) - }; + let route = |first: u64, count: u64, cost: u64| moq_net::fuzz::route_info(first..first + count, cost, None); // Three hops at the relay once the sender is appended: in the cap, but full. let _cheap = forward(&far, "room", route(100, 2, 1)); // Two hops at the relay, so it has room for the relay's own. diff --git a/rs/moq-net-tests/tests/integration/ietf_conformance.rs b/rs/moq-net-tests/tests/integration/ietf_conformance.rs index 46e5bdf1982..cd9cb6c9ac4 100644 --- a/rs/moq-net-tests/tests/integration/ietf_conformance.rs +++ b/rs/moq-net-tests/tests/integration/ietf_conformance.rs @@ -4,7 +4,7 @@ //! claim does, so the claim lands through the hidden `fuzz` module. use crate::support::harness::{MockConnectOptions, connect_mock, spawn}; -use moq_net::{Hop, Version, broadcast, origin}; +use moq_net::{Version, broadcast, origin}; use std::sync::Arc; // Moxygen's moqtest/Utils.cpp, pinned in nix/moxygen-sources.nix. @@ -12,7 +12,7 @@ const PREFIX: &str = "moq-test-00"; const NAMESPACE: &str = "moq-test-00/0/0/0/1/2/2/1024/100/50/1/1/1/-1/-1/0"; fn origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); spawn(driver); producer } diff --git a/rs/moq-net-tests/tests/integration/refresh.rs b/rs/moq-net-tests/tests/integration/refresh.rs index 215523d8d42..c22b9b44794 100644 --- a/rs/moq-net-tests/tests/integration/refresh.rs +++ b/rs/moq-net-tests/tests/integration/refresh.rs @@ -1,10 +1,10 @@ //! Refresh joins traverse real protocol hops, judged independently from each cache. use crate::support::harness::{MockConnectOptions, connect_mock, peer, spawn, subscribed}; -use moq_net::{Hop, Version, kio, origin, track}; +use moq_net::{Version, kio, origin, track}; use std::time::Duration; fn origin(hop: u64) -> origin::Producer { - let (origin, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (origin, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); spawn(driver); origin } diff --git a/rs/moq-net-tests/tests/integration/restart.rs b/rs/moq-net-tests/tests/integration/restart.rs index 3e254c7f1f8..d31805f15b9 100644 --- a/rs/moq-net-tests/tests/integration/restart.rs +++ b/rs/moq-net-tests/tests/integration/restart.rs @@ -11,7 +11,7 @@ use crate::support; use std::{cell::RefCell, rc::Rc, time::Duration}; -use moq_net::{Hop, Instance, Timestamp, Version, announce, broadcast, origin, track}; +use moq_net::{Instance, Timestamp, Version, announce, broadcast, origin, track}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; /// A millisecond track: the frames written here carry timestamps. @@ -24,7 +24,7 @@ fn timed() -> moq_net::track::Info { const TEST_TIMEOUT: Duration = Duration::from_secs(60); fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } @@ -187,11 +187,7 @@ impl Worker { moq_net::fuzz::requests_route( &origin, moq_net::Path::from_static("pool"), - moq_net::fuzz::route_info( - moq_net::Hops::new(), - 0, - Some((format!("worker-{hop}").parse().unwrap(), 0)), - ), + moq_net::fuzz::route_info([], 0, Some((format!("worker-{hop}").parse().unwrap(), 0))), ) .unwrap(), ); @@ -316,7 +312,7 @@ struct Claim { impl Claim { fn new(origin: &origin::Producer, instance: Option) -> Self { - let route = moq_net::fuzz::route_info(moq_net::Hops::new(), 0, instance.map(|instance| (instance, 0))); + let route = moq_net::fuzz::route_info([], 0, instance.map(|instance| (instance, 0))); let dynamic = Rc::new(moq_net::fuzz::requests_route(origin, moq_net::Path::from_static("live"), route).unwrap()); let outputs = Rc::new(RefCell::new(Vec::new())); @@ -347,14 +343,14 @@ impl Claim { /// Move the claim to `instance` in place, keeping the rest of its route. fn update_instance(&self, instance: Instance) { - let route = moq_net::fuzz::route_info(moq_net::Hops::new(), self.cost.get(), Some((instance, 0))); + let route = moq_net::fuzz::route_info([], self.cost.get(), Some((instance, 0))); moq_net::fuzz::update_route(&self.dynamic, route).unwrap(); } /// Re-price the claim in place, keeping its instance. fn update_cost(&self, cost: u64) { self.cost.set(cost); - let route = moq_net::fuzz::route_info(moq_net::Hops::new(), cost, None); + let route = moq_net::fuzz::route_info([], cost, None); moq_net::fuzz::update_route(&self.dynamic, route).unwrap(); } } diff --git a/rs/moq-net-tests/tests/integration/serve.rs b/rs/moq-net-tests/tests/integration/serve.rs index 6e8c32996f5..053f91db9f2 100644 --- a/rs/moq-net-tests/tests/integration/serve.rs +++ b/rs/moq-net-tests/tests/integration/serve.rs @@ -2,12 +2,12 @@ use std::time::Duration; -use moq_net::{Hop, Timestamp, Version, broadcast, origin, track}; +use moq_net::{Timestamp, Version, broadcast, origin, track}; use crate::support::harness::{MockConnectOptions, connect_mock, spawn}; fn origin(hop: u64) -> origin::Producer { - let (origin, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (origin, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); spawn(driver); origin } diff --git a/rs/moq-net/benches/announce.rs b/rs/moq-net/benches/announce.rs index c30a7bbe082..519642cd6db 100644 --- a/rs/moq-net/benches/announce.rs +++ b/rs/moq-net/benches/announce.rs @@ -18,7 +18,7 @@ use criterion::{BatchSize, BenchmarkId, Criterion, Throughput, criterion_group, criterion_main}; use moq_net::{ - Hop, Hops, Path, announce, + Path, announce, fuzz::{AnnounceWriter, Announced, decode_announces, encode_announces}, origin, }; @@ -56,7 +56,7 @@ fn initial(c: &mut Criterion) { origin::RouteEvent::Update(announce::Announce { prefix: moq_net::Path::new(&format!("route/{route}")).unwrap(), captures: None, - route: moq_net::fuzz::route_info(moq_net::Hops::new(), cost, None), + route: moq_net::fuzz::route_info([], cost, None), }) }) }) @@ -103,12 +103,8 @@ fn id(seed: u64) -> u64 { ((z ^ (z >> 31)) & ((1 << 62) - 1)).max(1) } -fn hops(ids: &[u64]) -> Hops { - Hops::try_from(ids.iter().map(|id| Hop::new(*id).unwrap()).collect::>()).unwrap() -} - /// Announce `routes` routes, then replace `churn` of them, oldest first. -fn stream(routes: u64, churn: u64, route: impl Fn(u64) -> (Path, Hops)) -> Vec { +fn stream(routes: u64, churn: u64, route: impl Fn(u64) -> (Path, Vec)) -> Vec { let mut announced: Vec<_> = (0..routes) .map(|n| { let (path, hops) = route(n); @@ -123,7 +119,7 @@ fn stream(routes: u64, churn: u64, route: impl Fn(u64) -> (Path, Hops)) -> Vec (Path, Hops) { +fn health(n: u64) -> (Path, Vec) { let origin = n % ORIGINS; let path = format!( "{:x}/private/channel_{}/stream-health-{}", @@ -131,17 +127,17 @@ fn health(n: u64) -> (Path, Hops) { n % 16, 1_700_000_000 + n ); - (Path::new(&path).unwrap(), hops(&[id(origin), id(100), id(101)])) + (Path::new(&path).unwrap(), vec![id(origin), id(100), id(101)]) } -fn unique(n: u64) -> (Path, Hops) { +fn unique(n: u64) -> (Path, Vec) { ( moq_net::Path::new(&format!("{:x}", id(n))).unwrap(), - hops(&[id(n + 1_000_000), id(n + 2_000_000)]), + vec![id(n + 1_000_000), id(n + 2_000_000)], ) } -type Workload = (&'static str, fn(u64) -> (Path, Hops)); +type Workload = (&'static str, fn(u64) -> (Path, Vec)); const WORKLOADS: [Workload; 2] = [("health", health), ("unique", unique)]; fn report() { diff --git a/rs/moq-net/benches/auth.rs b/rs/moq-net/benches/auth.rs index 62ae2cdcd9d..f90c8b82fe3 100644 --- a/rs/moq-net/benches/auth.rs +++ b/rs/moq-net/benches/auth.rs @@ -16,7 +16,7 @@ mod support; use bytes::Bytes; use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main}; use futures::future::join_all; -use moq_net::{Hop, Session, Version, auth, origin}; +use moq_net::{Session, Version, auth, origin}; use std::time::Duration; use support::{harness, mock::create_mock_session_pair}; @@ -126,7 +126,7 @@ async fn publisher(origin: &origin::Producer) -> (Session, Session, auth::Reques client_extensions.auth = false; let mut server_extensions = moq_net::setup::Extensions::default(); server_extensions.solicit = false; - let (subscribe, driver) = origin::Producer::new(origin::Config::new(Hop::new(1).unwrap())); + let (subscribe, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(1).unwrap())); harness::spawn(driver); let client = async { let (session, driver) = moq_net::Client::new() @@ -176,7 +176,7 @@ fn renewal(c: &mut Criterion) { |b, &(sessions, routes)| { let _guard = runtime.enter(); // No hold, so an iteration times the renewal rather than the origin batching it. - let mut config = origin::Config::new(Hop::new(2).unwrap()); + let mut config = origin::Config::new(std::num::NonZeroU64::new(2).unwrap()); config.update_hold = Duration::ZERO; let (origin, driver) = origin::Producer::new(config); harness::spawn(driver); @@ -251,11 +251,12 @@ fn waiting(c: &mut Criterion) { &(tokens, paths), |b, &(tokens, paths)| { let _guard = runtime.enter(); - let mut config = origin::Config::new(Hop::new(2).unwrap()); + let mut config = origin::Config::new(std::num::NonZeroU64::new(2).unwrap()); config.update_hold = Duration::ZERO; let (publish, driver) = origin::Producer::new(config); harness::spawn(driver); - let (receive, driver) = origin::Producer::new(origin::Config::new(Hop::new(1).unwrap())); + let (receive, driver) = + origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(1).unwrap())); harness::spawn(driver); let mut pair = runtime.block_on(pair( version.parse().unwrap(), @@ -346,7 +347,7 @@ fn shared_requests(c: &mut Criterion) { &(tokens, requests), |b, &(tokens, requests)| { let _guard = runtime.enter(); - let mut config = origin::Config::new(Hop::new(2).unwrap()); + let mut config = origin::Config::new(std::num::NonZeroU64::new(2).unwrap()); config.update_hold = Duration::ZERO; let (origin, driver) = origin::Producer::new(config); harness::spawn(driver); diff --git a/rs/moq-net/benches/interests.rs b/rs/moq-net/benches/interests.rs index bd88a09630a..c5d6ebc04b0 100644 --- a/rs/moq-net/benches/interests.rs +++ b/rs/moq-net/benches/interests.rs @@ -15,7 +15,7 @@ //! Run with `cargo bench -p moq-net --features fuzz --bench interests`. use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; -use moq_net::{Hop, Pattern, Patterns, fuzz, origin}; +use moq_net::{Pattern, Patterns, fuzz, origin}; /// `(watches, sessions)` shapes. const SHAPES: [(usize, usize); 4] = [(10, 10), (1_000, 10), (10, 1_000), (1_000, 1_000)]; @@ -31,7 +31,7 @@ struct Table { } fn table(watches: usize, sessions: usize) -> Table { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(1).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(1).unwrap())); let mut held: Vec<_> = (0..watches) .map(|i| scoped(&producer, &format!("other/{i}")).routes()) .collect(); diff --git a/rs/moq-net/benches/memory.rs b/rs/moq-net/benches/memory.rs index 1786a4028fb..8150d8cf882 100644 --- a/rs/moq-net/benches/memory.rs +++ b/rs/moq-net/benches/memory.rs @@ -25,7 +25,7 @@ use std::time::{Duration, Instant}; use bytes::Bytes; use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main}; -use moq_net::{Client, Hop, Server, Timestamp, Version, cache, origin, track, transport::memory}; +use moq_net::{Client, Server, Timestamp, Version, cache, origin, track, transport::memory}; const VERSION: &str = "moq-lite-06"; @@ -115,7 +115,7 @@ impl Link { let mut pools = Vec::new(); let version: Version = VERSION.parse().unwrap(); let mut origin = |hop: u64| { - let mut config = origin::Config::new(Hop::new(hop).unwrap()); + let mut config = origin::Config::new(std::num::NonZeroU64::new(hop).unwrap()); config.pool = cache::Pool::new(cache::Config::default().with_expiry(cache::DEFAULT_EXPIRY)); pools.push(config.pool.clone()); let (producer, driver) = origin::Producer::new(config); diff --git a/rs/moq-net/benches/origin.rs b/rs/moq-net/benches/origin.rs index 73bca373821..c4e2bb6eab6 100644 --- a/rs/moq-net/benches/origin.rs +++ b/rs/moq-net/benches/origin.rs @@ -51,7 +51,7 @@ use std::time::Duration; use criterion::{BatchSize, BenchmarkId, Criterion, Throughput, criterion_group, criterion_main}; use futures::FutureExt; -use moq_net::{Hop, Hops, Instance, Pattern, Patterns, Timestamp, auth, broadcast, kio, origin, track}; +use moq_net::{Instance, Pattern, Patterns, Timestamp, auth, broadcast, kio, origin, track}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; /// A millisecond track: the frames written here carry timestamps. @@ -267,13 +267,7 @@ fn bench_withdraw_wave(c: &mut Criterion) { group.sample_size(10); let instance: Instance = "01900000-0000-7000-8000-000000000001".parse().unwrap(); // One instance, so the winner moving between the peers is an update, which is held. - let route = |chain: &[u64]| { - let mut hops = Hops::new(); - for &hop in chain { - hops.push(Hop::new(hop).unwrap()).unwrap(); - } - moq_net::fuzz::route_info(hops, 0, Some((instance.clone(), 0))) - }; + let route = |chain: &[u64]| moq_net::fuzz::route_info(chain.iter().copied(), 0, Some((instance.clone(), 0))); for broadcasts in [1_000, 10_000] { for subscribers in [1, 20, 100] { let id = BenchmarkId::from_parameter(format!("{broadcasts}b_{subscribers}s")); @@ -624,9 +618,7 @@ fn peer_route(peer: u64, cost: u64) -> origin::RouteInfo { /// [`peer_route`], serving `instance` when it names one. fn peer_instance(peer: u64, cost: u64, instance: Option) -> origin::RouteInfo { - let mut hops = Hops::new(); - hops.push(Hop::new(peer).expect("peer id")).expect("hop chain"); - moq_net::fuzz::route_info(hops, cost, instance.map(|instance| (instance, 0))) + moq_net::fuzz::route_info([peer], cost, instance.map(|instance| (instance, 0))) } /// An announcement of an unrelated prefix with `fronts` remote fronts parked on @@ -899,7 +891,7 @@ impl Pool { } fn pool(members: usize, paths: usize, cursors: usize) -> Pool { - let (producer, mut driver) = origin::Producer::new(origin::Config::new(Hop::new(1).unwrap())); + let (producer, mut driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(1).unwrap())); let consumer = producer.consume(); let cursors = (0..cursors).map(|_| consumer.routes()).collect(); let members: Vec<_> = (0..members) @@ -1190,7 +1182,7 @@ fn watched_path(index: usize) -> String { async fn watching(routes: usize, subscribers: usize) -> Watching { let spawn = |hop| { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer }; diff --git a/rs/moq-net/benches/path.rs b/rs/moq-net/benches/path.rs index fe055528674..52683bb9571 100644 --- a/rs/moq-net/benches/path.rs +++ b/rs/moq-net/benches/path.rs @@ -14,7 +14,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use futures::FutureExt; use moq_net::{ - Hop, Hops, Path, Pattern, Patterns, + Path, Pattern, Patterns, fuzz::{Announced, Messages, decode_announces, decode_namespaces, encode_announces, encode_namespaces}, kio, origin, }; @@ -64,10 +64,6 @@ const SHORT: &str = "room/alice"; const MEDIUM: &str = "anon/7f3a9c2e1b/camera"; const LONG: &str = "1234/private/channel_7/stream-health-1700000000"; -fn hops(ids: &[u64]) -> Hops { - Hops::try_from(ids.iter().map(|id| Hop::new(*id).unwrap()).collect::>()).unwrap() -} - fn paths() { for (name, s) in [("short", SHORT), ("medium", MEDIUM), ("long", LONG)] { let path = Path::new(s).unwrap(); @@ -109,7 +105,7 @@ fn decode() { let stream: Vec = paths .iter() .enumerate() - .map(|(i, path)| Announced::Start(path.clone(), hops(&[0x1111 + i as u64, 0x2222]))) + .map(|(i, path)| Announced::Start(path.clone(), vec![0x1111 + i as u64, 0x2222])) .collect(); for compress in [false, true] { let data = encode_announces(&stream, compress); diff --git a/rs/moq-net/benches/session/mod.rs b/rs/moq-net/benches/session/mod.rs index b4e37e67dbe..37d276eed3e 100644 --- a/rs/moq-net/benches/session/mod.rs +++ b/rs/moq-net/benches/session/mod.rs @@ -94,7 +94,7 @@ use criterion::{BenchmarkId, Criterion, Throughput}; pub(crate) use harness::MockConnectOptions; use harness::{MockPair, connect_mock}; use mock::{MockSession, MockStats}; -use moq_net::{Hop, Timestamp, Version, broadcast, cache, datagram, group, origin, track}; +use moq_net::{Timestamp, Version, broadcast, cache, datagram, group, origin, track}; /// A millisecond track: the frames written here carry timestamps. fn timed() -> track::Info { @@ -568,7 +568,7 @@ impl Drop for Pair { } fn make_origin(id: u64, capacity: Option) -> (origin::Producer, cache::Pool) { - let mut config = origin::Config::new(Hop::new(id).unwrap()); + let mut config = origin::Config::new(std::num::NonZeroU64::new(id).unwrap()); let profiling = std::env::var_os("SESSION_EXPIRY_ONLY").is_some(); let pool = cache::Pool::new(if capacity.is_none() || profiling { cache::Config::default().with_expiry(cache::DEFAULT_EXPIRY) @@ -1769,7 +1769,7 @@ struct IdleRoom { impl IdleRoom { async fn new(version: &str, sessions: usize, consumers: usize) -> Self { - let (relay, driver) = origin::Producer::new(origin::Config::new(Hop::new(1).unwrap())); + let (relay, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(1).unwrap())); harness::spawn(driver); let mut viewers = Vec::new(); for _ in 0..sessions { diff --git a/rs/moq-net/benches/synced.rs b/rs/moq-net/benches/synced.rs index e30640b2fa2..3fa53100e24 100644 --- a/rs/moq-net/benches/synced.rs +++ b/rs/moq-net/benches/synced.rs @@ -14,7 +14,7 @@ //! Run with `cargo bench -p moq-net --features fuzz --bench synced`. use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; -use moq_net::{Hop, Pattern, Patterns, fuzz, origin}; +use moq_net::{Pattern, Patterns, fuzz, origin}; /// `(streams, consumers)` shapes. const SHAPES: [(usize, usize); 4] = [(10, 10), (1_000, 10), (10, 1_000), (1_000, 1_000)]; @@ -29,7 +29,7 @@ struct Table { } fn table(streams: usize, consumers: usize) -> Table { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(1).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(1).unwrap())); let streams = (0..streams) .map(|i| fuzz::snapshot(&producer, &format!("room/{i}"))) .collect(); diff --git a/rs/moq-net/benches/viewers.rs b/rs/moq-net/benches/viewers.rs index 4dd7455486f..77d9ffde5bf 100644 --- a/rs/moq-net/benches/viewers.rs +++ b/rs/moq-net/benches/viewers.rs @@ -14,7 +14,7 @@ use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering}; use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; use futures::FutureExt; -use moq_net::{Hop, Timestamp, kio, origin}; +use moq_net::{Timestamp, kio, origin}; /// A millisecond track: the frames written here carry timestamps. fn timed() -> moq_net::track::Info { @@ -114,7 +114,8 @@ impl Room { /// Viewer `n` joins and reads the latest group of its broadcast. fn join(&mut self, n: usize) -> moq_net::track::Subscriber { - let session = moq_net::fuzz::excluding(self.producer.consume(), Hop::random()); + // Each viewer's own peer id, clear of the origin's random one below 2^53. + let session = moq_net::fuzz::excluding(self.producer.consume(), (1 << 60) + n as u64); let path = format!("room/{}", n % self.broadcasts); let resolved = self.drive(session.request(path, None)).unwrap(); let mut subscription = self.drive(resolved.track("video").unwrap().subscribe(None)).unwrap(); diff --git a/rs/moq-net/src/client.rs b/rs/moq-net/src/client.rs index 9f694213cf6..2edab8c1ca4 100644 --- a/rs/moq-net/src/client.rs +++ b/rs/moq-net/src/client.rs @@ -21,7 +21,7 @@ pub struct Client { url: Option, setup_token: Option, cost: Option, - peer_hop: Option, + peer_hop: Option, limits: crate::session::Limits, extensions: setup::Extensions, auth: Option, @@ -239,7 +239,7 @@ impl Client { self } - /// Assign the identity this peer's routes are attributed to, overriding the fresh + /// Assign the hop id this peer's routes are attributed to, overriding the fresh /// per-dial default. /// /// A dialed session whose peer declares no hop gets a random one for that @@ -255,7 +255,7 @@ impl Client { /// really are one peer reconnecting or running redundant links, and a bug /// otherwise. Derive it from the authenticated identity, never from something /// coarser like the remote address. - pub fn with_peer_hop(mut self, hop: crate::Hop) -> Self { + pub fn with_peer_hop(mut self, hop: std::num::NonZeroU64) -> Self { self.peer_hop = Some(hop); self } @@ -266,7 +266,7 @@ impl Client { /// connection gets a fresh one, matching the per-session default an accepted /// session already has. fn assigned_hop(&self) -> crate::Hop { - self.peer_hop.unwrap_or_else(crate::Hop::random) + self.peer_hop.map_or_else(crate::Hop::random, crate::Hop::from) } /// The new session's side of its auth handle: the one from [`with_auth`](Self::with_auth), @@ -448,7 +448,7 @@ impl Client { })?; tracing::debug!(version = ?v, "connected"); - return Ok(Connect::Started(Session::new( + return Ok(Connect::Started(Box::new(Session::new( runtime, session, v, @@ -466,7 +466,7 @@ impl Client { peer_implementation, datagrams_unrouted: None, }, - ))); + )))); } Some(alpn @ (ALPN_LITE_05 | ALPN_LITE_06 | ALPN_LITE_07_WIP)) => { let version = match alpn { @@ -477,7 +477,7 @@ impl Client { self.versions.select(Version::Lite(version)).ok_or(Error::Version)?; return self .start_lite(runtime, session, version, peer_hop) - .map(Connect::Started); + .map(|started| Connect::Started(Box::new(started))); } Some(ALPN_LITE_04) => { self.versions @@ -485,7 +485,7 @@ impl Client { .ok_or(Error::Version)?; return self .start_lite(runtime, session, lite::Version::Lite04, peer_hop) - .map(Connect::Started); + .map(|started| Connect::Started(Box::new(started))); } Some(ALPN_LITE_03) => { self.versions @@ -493,7 +493,7 @@ impl Client { .ok_or(Error::Version)?; return self .start_lite(runtime, session, lite::Version::Lite03, peer_hop) - .map(Connect::Started); + .map(|started| Connect::Started(Box::new(started))); } // No ALPN, or `moql`: negotiate moq-lite in a bidi SETUP. Some(ALPN_LITE) | None => self.versions.filter(&NEGOTIATED.into()).ok_or(Error::Version)?, @@ -588,8 +588,9 @@ struct Negotiation { enum Connect { /// Not polled yet: the transport's ALPN picks the path. Start { runtime: Deadlines, session: Transport }, - /// Started without waiting on the peer. - Started((Session, crate::Driver)), + /// Started without waiting on the peer. Boxed, being several times the size of the + /// handshake steps. + Started(Box<(Session, crate::Driver)>), /// Waiting its turn for credit to open the bidi stream the SETUP is negotiated on. Open { negotiation: Negotiation, @@ -634,7 +635,7 @@ impl Connect { let Self::Started(started) = std::mem::replace(self, Self::Done) else { unreachable!("matched above"); }; - return Poll::Ready(Ok(started)); + return Poll::Ready(Ok(*started)); } Self::Open { negotiation, open } => { // The SETUP keeps lite-01's framing whichever version it offers. @@ -1046,7 +1047,7 @@ mod tests { .with_protocol(crate::version::ALPN_LITE_05); // A subscribe origin is what makes the client open an announce stream at all. - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let client = Client::new() .with_versions([Version::Lite(lite::Version::Lite05)].into()) .with_subscriber(origin); diff --git a/rs/moq-net/src/fuzz.rs b/rs/moq-net/src/fuzz.rs index bc08a7261ef..2e175ed52bb 100644 --- a/rs/moq-net/src/fuzz.rs +++ b/rs/moq-net/src/fuzz.rs @@ -358,13 +358,18 @@ pub fn lite_wire(data: &[u8]) -> bool { } } +/// The hop chain a session would decode from `ids`; panics on one it would refuse. +fn hop_chain(ids: impl IntoIterator) -> Hops { + Hops::try_from(ids.into_iter().map(crate::Hop::from_wire).collect::>()).expect("a valid hop chain") +} + /// One announcement on an announce stream, resolved: what the application sees. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Announced { - /// ANNOUNCE_START: a route's suffix and wire hop chain, taking the next id. - Start(Path, Hops), - /// ANNOUNCE_UPDATE: a live id's new wire hop chain. - Update(u64, Hops), + /// ANNOUNCE_START: a route's suffix and wire hop ids, taking the next id. + Start(Path, Vec), + /// ANNOUNCE_UPDATE: a live id's new wire hop ids. + Update(u64, Vec), /// ANNOUNCE_END: a live id retired. End(u64), } @@ -397,7 +402,7 @@ impl AnnounceWriter { pub fn write(&mut self, announced: &Announced, data: &mut Vec) { let msg = match announced { Announced::Start(suffix, hops) => { - let (_, suffix, hops) = self.encoder.start(suffix.clone(), hops.clone()); + let (_, suffix, hops) = self.encoder.start(suffix.clone(), hop_chain(hops.iter().copied())); // A fixed instance, so the bytes stay pinned and match what `js/net` writes. lite::AnnounceBroadcast::Active { instance: self.version.has_instance().then(|| "a".parse().unwrap()), @@ -409,7 +414,7 @@ impl AnnounceWriter { } Announced::Update(id, hops) => lite::AnnounceBroadcast::Update { id: *id, - hops: self.encoder.update(*id, hops.clone()), + hops: self.encoder.update(*id, hop_chain(hops.iter().copied())), cost: Default::default(), }, Announced::End(id) => { @@ -428,15 +433,25 @@ pub fn received(track: &track::Producer) { track.received(); } -/// `origin` as a session connected to `peer` serves it, for the viewers bench. -pub fn excluding(origin: crate::origin::Consumer, peer: crate::Hop) -> crate::origin::Consumer { - origin.excluding(peer) +/// `origin` as a session connected to the peer with hop id `peer` serves it, for the +/// viewers bench. +pub fn excluding(origin: crate::origin::Consumer, peer: u64) -> crate::origin::Consumer { + origin.excluding(crate::Hop::from_wire(peer)) } -/// A peer's wire route: its hop chain, cost, and instance at an epoch, as a session +/// A peer's wire route: its hop ids, cost, and instance at an epoch, as a session /// decodes one, for benches and tests that land or update forwarded routes. -pub fn route_info(hops: crate::Hops, cost: u64, instance: Option<(crate::Instance, u64)>) -> crate::origin::RouteInfo { - let info = crate::origin::RouteInfo::default().with_hops(hops).with_cost(cost); +/// +/// Panics on a chain no session would decode: longer than 32, or naming a non-zero id +/// twice. +pub fn route_info( + hops: impl IntoIterator, + cost: u64, + instance: Option<(crate::Instance, u64)>, +) -> crate::origin::RouteInfo { + let info = crate::origin::RouteInfo::default() + .with_hops(hop_chain(hops)) + .with_cost(cost); match instance { Some((instance, epoch)) => info.with_instance(instance, epoch), None => info, @@ -576,10 +591,10 @@ pub fn decode_announces(data: &[u8], compress: bool) -> Vec { let announced = match msg { lite::AnnounceBroadcast::Active { suffix, hops, .. } => decoder .start(suffix, hops) - .map(|(suffix, hops)| Announced::Start(suffix, hops)), - lite::AnnounceBroadcast::Update { id, hops, .. } => { - decoder.update(id, hops).map(|(_, hops)| Announced::Update(id, hops)) - } + .map(|(suffix, hops)| Announced::Start(suffix, hops.into_ids())), + lite::AnnounceBroadcast::Update { id, hops, .. } => decoder + .update(id, hops) + .map(|(_, hops)| Announced::Update(id, hops.into_ids())), lite::AnnounceBroadcast::EndedId { id } => decoder.end(id).map(|_| Announced::End(id)), _ => continue, }; @@ -1484,14 +1499,11 @@ pub fn seeds() -> Vec { // Announce streams from our own encoder: routes sharing path heads and relay tails, // with retractions and updates moving the bases around. let mut announced = Vec::new(); - let hop = |id: u64| crate::Hop::new(id).expect("a valid hop"); for n in 0..12u64 { let suffix = Path::new(&format!("pid{}/private/channel_{}/health-{n}", n % 3, n % 2)).unwrap(); - let hops = Hops::try_from(vec![hop(100 + n % 3), hop(1 << 40), hop(1 << 41)]).expect("valid hops"); - announced.push(Announced::Start(suffix, hops)); + announced.push(Announced::Start(suffix, vec![100 + n % 3, 1 << 40, 1 << 41])); if n % 4 == 3 { - let hops = Hops::try_from(vec![hop(200), hop(1 << 41)]).expect("valid hops"); - announced.push(Announced::Update(n, hops)); + announced.push(Announced::Update(n, vec![200, 1 << 41])); } if n % 5 == 4 { announced.push(Announced::End(n)); diff --git a/rs/moq-net/src/ietf/publisher.rs b/rs/moq-net/src/ietf/publisher.rs index 4c17e30bbd6..7353f7bae9c 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -2724,7 +2724,7 @@ impl Publisher { withdrawal: Default::default(), runtime, session, - self_origin: origin.hop(), + self_origin: crate::Hop::from(origin.hop()), // Serving the peer is not a local reader asking to discover anything. origin: origin.serving(), control, @@ -9207,7 +9207,7 @@ mod serve_tests { /// The same, over `session`. fn serve_session(version: Version, info: crate::track::Info, session: ScriptedSession) -> Serve { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::default()).unwrap(); let track = broadcast.broadcast().create_track("video", info).unwrap(); @@ -11446,7 +11446,7 @@ mod serve_tests { #[kio::test] async fn track_status_narrowed_while_answering_is_reset() { for version in ALL_VERSIONS { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::default()).unwrap(); let _track = broadcast.broadcast().create_track("video", None).unwrap(); settle().await; @@ -12306,7 +12306,7 @@ mod serve_tests { }; for version in [Version::Draft18, Version::Draft20, Version::Draft22] { for (filter, history) in [(Filter::Unfiltered, 0), (zero, 1)] { - let upstream = crate::origin::Config::new(crate::Hop::new(2).unwrap()).produce(); + let upstream = crate::origin::Config::new(std::num::NonZeroU64::new(2).unwrap()).produce(); let broadcast = upstream.route("room", crate::origin::RouteOptions::default()).unwrap(); let track = broadcast .broadcast() @@ -13228,7 +13228,7 @@ mod serve_tests { #[kio::test] async fn a_kept_join_ends_with_its_token_while_publish_done_waits() { for version in JOINING_DRAFTS { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::default()).unwrap(); let track = broadcast .broadcast() @@ -14259,7 +14259,7 @@ mod serve_tests { /// The info a relay behind a moq-lite hop with the `ietf` extension learns of a track /// published with `info`. async fn across_a_hop(info: track::Info) -> track::Info { - let upstream = crate::origin::Config::new(crate::Hop::new(2).unwrap()).produce(); + let upstream = crate::origin::Config::new(std::num::NonZeroU64::new(2).unwrap()).produce(); let broadcast = upstream.route("room", crate::origin::RouteOptions::default()).unwrap(); let _track = broadcast.broadcast().create_track("video", info).unwrap(); let (downstream, _sessions) = crate::lite::ietf::test_hop(&upstream, "room", [true, true]).await; @@ -14893,7 +14893,7 @@ mod serve_tests { #[kio::test] async fn a_standalone_fetch_narrowed_while_responding_stops() { for version in FETCH_DRAFTS { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::default()).unwrap(); let track = broadcast .broadcast() @@ -14992,7 +14992,7 @@ mod serve_tests { group_id: 0, }, ] { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::default()).unwrap(); let track = broadcast .broadcast() @@ -15126,7 +15126,7 @@ mod serve_tests { .map(|end| (version, end)) }) { let token = end != JoinEnd::Ended; - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::default()).unwrap(); let track = broadcast .broadcast() @@ -15460,7 +15460,7 @@ mod serve_tests { } async fn revoked_while(version: Version, parked: Parked) { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let (claim, published) = match parked { Parked::Resolving => ( Some( @@ -15631,7 +15631,7 @@ mod serve_tests { } async fn withdrawn_during(version: Version, setup: Setup, kind: request::Kind) { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let session = ScriptedSession::new(Vec::new()); let peer_setup = peer::PeerSetup::default(); peer_setup.set(peer::Peer::default()); @@ -15784,7 +15784,7 @@ mod serve_tests { /// A `kind` request whose track the publisher refuses with `err`, as the REQUEST_ERROR it /// writes: (code, Retry Interval). async fn refused_track(version: Version, kind: request::Kind, err: Error) -> (u64, u64) { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let route = origin.route("room", crate::origin::RouteOptions::default()).unwrap(); let mut requests = route.broadcast().requests(); let peer_setup = peer::PeerSetup::default(); @@ -16271,7 +16271,7 @@ mod serve_tests { /// [`serve_with_auth`] over a given session, such as one that finishes the stream after /// its script. fn serve_on(version: Version, auth: crate::auth::Link, session: ScriptedSession) -> Serve { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::default()).unwrap(); let track = broadcast .broadcast() @@ -17884,7 +17884,7 @@ mod tests { /// the assertions. async fn echo_harness(assigned: crate::Hop) -> (Publisher, origin::Consumer, Vec) { let other = crate::Hop::new(778).unwrap(); - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let consumer = origin.consume(); let session = crate::lite::test_transport::SinkSession::new(Default::default()); @@ -17944,7 +17944,7 @@ mod tests { async fn anonymous_chain_is_forwarded_with_zero_and_not_echoed() { let assigned = crate::Hop::new(777).unwrap(); let r1 = crate::Hop::new(9).unwrap(); - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let consumer = origin.consume(); let publisher = Publisher::new( crate::time::sim(), @@ -18014,7 +18014,7 @@ mod tests { #[kio::test] async fn a_declared_zero_chain_is_not_advertised_back() { let assigned = crate::Hop::new(777).unwrap(); - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let consumer = origin.consume(); let publisher = Publisher::new( @@ -18051,7 +18051,7 @@ mod tests { /// leave the peer waiting on a message that never comes. #[kio::test] async fn the_ok_counts_only_what_is_advertised() { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let session = SinkSession::gated_bi(kio::Producer::new(true).consume()); let log = session.log.clone(); @@ -18131,7 +18131,7 @@ mod tests { async fn namespace_follows_route_eligibility_changes() { let assigned = crate::Hop::new(777).unwrap(); let clean_publisher = crate::Hop::new(778).unwrap(); - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let gate = kio::Producer::new(true); let session = SinkSession::gated_bi(gate.consume()); @@ -18238,7 +18238,7 @@ mod tests { async fn a_refusal_that_forbids_retrying_is_not_retried() { const VERSION: Version = Version::Draft18; - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let _cam = origin .announce("lonely-cam", crate::origin::RouteInfo::default()) .unwrap(); @@ -18312,7 +18312,7 @@ mod tests { async fn a_peer_that_declared_nothing_is_told_unsolicited() { const VERSION: Version = Version::Draft18; - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let _local = origin .announce("local-cam", crate::origin::RouteInfo::default()) .unwrap(); @@ -18358,7 +18358,7 @@ mod tests { #[kio::test] async fn publish_namespace_withdraws_by_reset() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let local = origin .announce("local-cam", crate::origin::RouteInfo::default()) .unwrap(); @@ -18424,7 +18424,7 @@ mod tests { async fn a_counted_publish_namespace_ok_is_a_violation() { const VERSION: Version = Version::Draft18; - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let _local = origin .announce("local-cam", crate::origin::RouteInfo::default()) .unwrap(); @@ -18517,7 +18517,7 @@ mod tests { hidden, scoped, } = case; - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let _cam = origin.announce("cam", crate::origin::RouteInfo::default()).unwrap(); let _stats = origin .announce(".stats/node", crate::origin::RouteInfo::default()) @@ -18666,7 +18666,7 @@ mod tests { #[kio::test] async fn a_non_solicit_subscribe_namespace_carries_namespace() { for version in [Version::Draft18] { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let early = origin .announce("early-cam", crate::origin::RouteInfo::default()) .unwrap(); @@ -18761,7 +18761,7 @@ mod tests { async fn a_parked_open_still_lets_a_namespace_be_withdrawn() { const VERSION: Version = Version::Draft18; - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let first = origin .announce("first-cam", crate::origin::RouteInfo::default()) .unwrap(); @@ -18846,7 +18846,7 @@ mod tests { async fn a_namespace_that_stops_being_advertisable_stops_being_deferred() { let assigned = crate::Hop::new(777).unwrap(); - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); // A route that already passed through us must never be forwarded: `select` // wants nothing, which is what the peer already holds. @@ -18888,7 +18888,7 @@ mod tests { async fn a_route_change_still_waits_out_a_refusal() { const VERSION: Version = Version::Draft18; - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); // One instance, so the second route re-prices the instance rather than restart it. let instance = crate::Instance::random(); let cam = origin @@ -18992,7 +18992,7 @@ mod tests { // Forward the update at once: the hold is not what this checks. let origin = crate::origin::Config { update_hold: Duration::ZERO, - ..crate::origin::Config::new(crate::Hop::new(1).unwrap()) + ..crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()) } .produce(); // One instance, so the warm route re-prices the instance rather than restart it. @@ -19074,7 +19074,7 @@ mod tests { async fn a_counted_update_ok_is_a_violation() { const VERSION: Version = Version::Draft18; - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let instance = crate::Instance::random(); let _cold = origin .announce( @@ -19159,7 +19159,7 @@ mod tests { // Forward the update at once: the hold is not what this checks. let origin = crate::origin::Config { update_hold: Duration::ZERO, - ..crate::origin::Config::new(crate::Hop::new(1).unwrap()) + ..crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()) } .produce(); let publisher_a = crate::Hops::try_from(vec![crate::Hop::new(7).unwrap()]).unwrap(); @@ -19272,7 +19272,7 @@ mod tests { fn unheld_origin() -> crate::origin::Producer { crate::origin::Config { update_hold: Duration::ZERO, - ..crate::origin::Config::new(crate::Hop::new(1).unwrap()) + ..crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()) } .produce() } @@ -19775,7 +19775,7 @@ mod tests { // Forward the restart at once: the hold is not what this checks. let origin = crate::origin::Config { update_hold: Duration::ZERO, - ..crate::origin::Config::new(crate::Hop::new(1).unwrap()) + ..crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()) } .produce(); let _old = origin @@ -19830,7 +19830,7 @@ mod tests { async fn a_refused_update_is_re_advertised_fresh() { const VERSION: Version = Version::Draft18; - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let instance = crate::Instance::random(); let _cold = origin .announce( @@ -19909,7 +19909,7 @@ mod tests { async fn a_silent_answer_still_lets_the_next_namespace_be_advertised() { const VERSION: Version = Version::Draft18; - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let _first = origin .announce("first-cam", crate::origin::RouteInfo::default()) .unwrap(); @@ -20112,7 +20112,7 @@ mod tests { #[kio::test] async fn an_advertisement_without_credit_is_retried_and_spends_no_id() { for version in [Version::Draft18] { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let _cam = origin .announce("lonely-cam", crate::origin::RouteInfo::default()) .unwrap(); @@ -20164,7 +20164,7 @@ mod tests { async fn an_advertisement_waiting_for_send_capacity_is_retried_on_its_own() { const VERSION: Version = Version::Draft18; - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let _cam = origin .announce("lonely-cam", crate::origin::RouteInfo::default()) .unwrap(); @@ -20231,7 +20231,7 @@ mod tests { } fn harness(version: Version) -> Harness { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let session = crate::lite::test_transport::ScriptedSession::per_stream(vec![Vec::new()]); let log = session.log.clone(); diff --git a/rs/moq-net/src/ietf/session.rs b/rs/moq-net/src/ietf/session.rs index f4026a20324..d06824d729b 100644 --- a/rs/moq-net/src/ietf/session.rs +++ b/rs/moq-net/src/ietf/session.rs @@ -339,12 +339,8 @@ impl Launch { // moq-transport threads concrete origins through the publisher/subscriber. // An unset half gets an empty origin: an empty publish origin announces // nothing, and an empty subscribe origin issues no SUBSCRIBE_NAMESPACE. - let publish = publish.unwrap_or_else(|| { - origin::Producer::empty(Hop::random()) - .consume() - .with_stats(stats.clone()) - }); - let subscribe = subscribe.unwrap_or_else(|| origin::Producer::empty(Hop::random()).with_stats(stats.clone())); + let publish = publish.unwrap_or_else(|| origin::Producer::empty().consume().with_stats(stats.clone())); + let subscribe = subscribe.unwrap_or_else(|| origin::Producer::empty().with_stats(stats.clone())); // Counted for the peak only: stream credit bounds them. let subscriptions = crate::session::Slots::default().with_stats(publish.stats(), crate::stats::Cap::Subscriptions); @@ -692,7 +688,7 @@ fn self_origin(publish: Option<&origin::Consumer>, subscribe: Option<&origin::Pr publish .map(|origin| origin.hop()) .or_else(|| subscribe.map(|origin| origin.hop())) - .unwrap_or_else(Hop::random) + .map_or_else(Hop::random, Hop::from) } /// Server: reads the peer's SETUP off its uni stream before starting the @@ -1931,7 +1927,7 @@ mod tests { #[kio::test] async fn announce_interest_waits_for_credit() { for version in [Version::Draft18] { - let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let _interest = origin.consume().routes(); let scripted = crate::lite::test_transport::ScriptedSession::new(Vec::new()).without_credit(); let log = scripted.log.clone(); @@ -2328,7 +2324,7 @@ mod tests { // A driver that swallows the violation parks forever instead of failing, so // bound it: paused time makes the deadline fire the moment nothing else can run. - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); // A client asks only about what is watched. let _watch = origin.consume().routes(); let session = crate::lite::test_transport::ScriptedSession::new(namespace_without_hop_path(VERSION).await); @@ -2386,7 +2382,7 @@ mod tests { /// called `run_subscribe_namespace` itself. #[kio::test] async fn every_permitted_prefix_gets_its_own_subscribe_namespace() { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let scope: crate::Patterns = ["cam", "mic"] .into_iter() .map(|prefix| crate::Pattern::subtree(prefix).unwrap()) @@ -2538,7 +2534,7 @@ mod tests { #[kio::test] async fn a_client_asks_only_about_what_is_watched() { for version in [Version::Draft18] { - let subscribe = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let subscribe = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let (log, _driver) = client(version, subscribe.clone(), Some(true)).await; let first = subscribe_namespace(version, "cam", RequestId(0)).await; assert!( @@ -2562,7 +2558,7 @@ mod tests { #[kio::test] async fn a_broader_watch_waits_for_the_narrower_to_leave_the_wire() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { - let subscribe = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let subscribe = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let _front = watch(&subscribe, "cam/front"); let (log, _driver) = client(version, subscribe.clone(), None).await; assert!(sent(&log, b"front").await, "{version:?}"); @@ -2587,7 +2583,7 @@ mod tests { #[kio::test] async fn a_request_ended_before_it_opened_does_not_block_the_broader_one() { for version in [Version::Draft22] { - let subscribe = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let subscribe = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let gate = kio::Producer::new(true); let credit = kio::Producer::new(true); let session = @@ -2617,7 +2613,7 @@ mod tests { #[kio::test] async fn a_broader_watch_keeps_the_narrower_open_at_our_peer() { for version in [Version::Draft18] { - let subscribe = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let subscribe = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let _front = watch(&subscribe, "cam/front"); let (log, _driver) = client(version, subscribe.clone(), Some(true)).await; let asked = subscribe_namespace(version, "cam/front", RequestId(0)).await; @@ -2645,7 +2641,7 @@ mod tests { /// The scripted peer answers nothing, so an advertisement parks after writing. That is /// enough: the question is only whether the bytes went out unasked. async fn announce_occurrences(peer_declared: Option) -> usize { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let _cam = origin .announce("solo-cam", crate::origin::RouteInfo::default()) .unwrap(); @@ -2752,7 +2748,7 @@ mod tests { } fn auth_session(auth: bool) -> AuthSession { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let cam = origin .announce("solo-cam", crate::origin::RouteInfo::default()) .unwrap(); @@ -3010,14 +3006,14 @@ mod tests { fn the_hop_id_comes_from_whichever_origin_the_caller_set() { let ours = crate::Hop::new(42).unwrap(); - let publish = crate::origin::Config::new(ours).produce(); + let publish = crate::origin::Config::from(ours).produce(); assert_eq!(self_origin(Some(&publish.consume()), None), ours, "the publish half"); - let subscribe = crate::origin::Config::new(ours).produce(); + let subscribe = crate::origin::Config::from(ours).produce(); assert_eq!(self_origin(None, Some(&subscribe)), ours, "the subscribe half alone"); // Neither half: nothing to route, so any id will do as long as it is ours. - let publish = crate::origin::Config::new(ours).produce(); + let publish = crate::origin::Config::from(ours).produce(); assert_eq!(self_origin(Some(&publish.consume()), Some(&subscribe)), ours); } @@ -3035,7 +3031,7 @@ mod tests { // A driver that survives parks forever, so bound it: paused time makes the // deadline fire the moment nothing else can run. - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let log = session.log.clone(); let (driver, _goaway, _) = start(Config { @@ -3200,7 +3196,7 @@ mod tests { accepted: Option, retired_alias: Option, ) -> (crate::lite::test_transport::Log, Option>) { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let log = session.log.clone(); let (tasks, _task_set) = TaskSet::new(); @@ -3265,7 +3261,7 @@ mod tests { let subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(local.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(true), None, peer_setup.clone(), @@ -3307,7 +3303,7 @@ mod tests { async fn a_flood_of_request_streams_yields() { const VERSION: Version = Version::Draft18; let (local, peer) = crate::transport::memory::pair(Default::default()); - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let (tasks, _task_set) = TaskSet::new(); let peer_setup = peer::PeerSetup::default(); peer_setup.set(peer::Peer::default()); @@ -3412,7 +3408,7 @@ mod tests { // Stall before the type, then after it while the body has not arrived. for stalled in [Vec::new(), vec![ietf::Subscribe::ID as u8]] { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::default()).unwrap(); let mut track = broadcast.broadcast().create_track("video", None).unwrap(); let session = crate::lite::test_transport::ScriptedSession::new(Vec::new()) @@ -3739,7 +3735,7 @@ mod tests { crate::lite::test_transport::ScriptedSession::new(Vec::new()).with_incoming_bidis(vec![payload]); let log = session.log.clone(); let session = crate::driver::Transport::new(session.clone()); - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let (driver, _goaway, _) = start(Config { runtime: crate::time::sim(), stats: Default::default(), @@ -4085,7 +4081,7 @@ mod tests { /// Read off the transport, since a request task closes the session itself and the /// scripted transport does not end the driver for it. async fn serve_bidis(version: Version, client: bool, payloads: Vec>) -> Option { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let session = crate::lite::test_transport::ScriptedSession::new(Vec::new()).with_incoming_bidis(payloads); // The peer FINs each stream after its script, so a message it cuts short is malformed. session.close(crate::lite::test_transport::Close::Fin); diff --git a/rs/moq-net/src/ietf/subscriber.rs b/rs/moq-net/src/ietf/subscriber.rs index 09063a00e51..f384780a246 100644 --- a/rs/moq-net/src/ietf/subscriber.rs +++ b/rs/moq-net/src/ietf/subscriber.rs @@ -8276,7 +8276,7 @@ mod tests { /// The same, for a subscriber whose own SETUP declared MoQ Solicit only if `ours`. fn unsolicited_is_a_violation_to(ours: bool, solicit: Option, version: Version) -> bool { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let session = crate::lite::test_transport::SinkSession::new(Default::default()); let peer_setup = peer::PeerSetup::default(); peer_setup.set(peer::Peer { @@ -8345,7 +8345,7 @@ mod tests { /// so sending it asks for a prefix that matches nothing there. #[kio::test] async fn a_rooted_subscriber_asks_for_its_scope_not_its_root() { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let scope = crate::Patterns::from(crate::Pattern::subtree("cam").unwrap()); let scoped = origin.scope("rootns", &scope).expect("scope the origin"); @@ -8404,7 +8404,7 @@ mod tests { let mut subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::declared(peer::Peer::default()), @@ -8485,7 +8485,7 @@ mod tests { async fn a_rooted_subscriber_mounts_a_reply_under_its_root_once() { const VERSION: Version = Version::Draft18; - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let consumer = origin.consume(); let scope = crate::Patterns::from(crate::Pattern::subtree("cam").unwrap()); let scoped = origin.scope("rootns", &scope).expect("scope the origin"); @@ -8583,7 +8583,7 @@ mod tests { } let script = log.writes.lock().unwrap().clone(); - let origin = crate::origin::Config::new(us).produce(); + let origin = crate::origin::Config::from(us).produce(); let session = crate::lite::test_transport::ScriptedSession::new(script); let (tasks, _task_set) = crate::util::TaskSet::new(); let peer_setup = peer::PeerSetup::default(); @@ -8655,7 +8655,7 @@ mod tests { .unwrap(); let response = log.writes.lock().unwrap().clone(); - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let session = crate::lite::test_transport::ScriptedSession::new(response); let (tasks, _task_set) = crate::util::TaskSet::new(); let peer_setup = peer::PeerSetup::default(); @@ -8740,7 +8740,7 @@ mod tests { active_count: bool, session: crate::lite::test_transport::ScriptedSession, ) -> (Subscriber, crate::origin::Consumer, crate::model::Snapshot) { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let consumer = origin.consume(); let snapshot = origin.snapshot(""); let (tasks, _task_set) = crate::util::TaskSet::new(); @@ -8932,7 +8932,7 @@ mod tests { let subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(crate::lite::test_transport::SinkSession::new(Default::default())), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::default(), @@ -9213,7 +9213,7 @@ mod tests { let mut subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::declared(peer::Peer::default()), @@ -9276,7 +9276,7 @@ mod tests { let subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::default(), @@ -9385,7 +9385,7 @@ mod tests { let mut subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::declared(peer::Peer::default()), @@ -9453,7 +9453,7 @@ mod tests { let mut subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::declared(peer::Peer::default()), @@ -9514,7 +9514,7 @@ mod tests { let mut subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::declared(peer::Peer::default()), @@ -9597,7 +9597,7 @@ mod tests { let mut subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), control.clone(), None, peer::PeerSetup::declared(peer::Peer::default()), @@ -9856,7 +9856,7 @@ mod tests { let mut subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::declared(peer::Peer::default()), @@ -9969,7 +9969,7 @@ mod tests { let mut subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::declared(peer::Peer::default()), @@ -10077,7 +10077,7 @@ mod tests { let mut subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::declared(peer::Peer::default()), @@ -10207,7 +10207,7 @@ mod tests { let mut subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(2).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(2).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::declared(peer::Peer::default()), @@ -10230,7 +10230,7 @@ mod tests { } for version in [Version::Draft18, Version::Draft20, Version::Draft22] { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let source = origin.route("broadcast", Default::default()).unwrap(); let resolved = origin.consume().request("broadcast", None).await.unwrap(); let peer = Arc::new(Peer { @@ -10273,7 +10273,7 @@ mod tests { let mut subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::declared(peer::Peer::default()), @@ -10360,7 +10360,7 @@ mod tests { let mut subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::declared(peer::Peer::default()), @@ -10453,7 +10453,7 @@ mod tests { let mut subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::declared(peer::Peer::default()), @@ -10557,7 +10557,7 @@ mod tests { async fn namespaces_past_the_cap_close_the_session() { let session = crate::lite::test_transport::SinkSession::new(Default::default()); let log = session.log.clone(); - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let (tasks, _task_set) = crate::util::TaskSet::new(); let mut subscriber = Subscriber::new( crate::time::sim(), @@ -10614,7 +10614,7 @@ mod tests { let session = crate::lite::test_transport::SinkSession::new(Default::default()); let assigned = crate::Hop::new(777).unwrap(); - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let consumer = origin.consume(); let (tasks, _task_set) = crate::util::TaskSet::new(); let mut subscriber = Subscriber::new( @@ -10658,7 +10658,7 @@ mod tests { let peer = crate::Hop::new(777).unwrap(); let self_origin = crate::Hop::new(1).unwrap(); - let origin = crate::origin::Config::new(self_origin).produce(); + let origin = crate::origin::Config::from(self_origin).produce(); let consumer = origin.consume(); let mut announced = consumer.routes(); @@ -10714,7 +10714,7 @@ mod tests { let peer = crate::Hop::new(777).unwrap(); let self_origin = crate::Hop::new(1).unwrap(); - let origin = crate::origin::Config::new(self_origin).produce(); + let origin = crate::origin::Config::from(self_origin).produce(); let consumer = origin.consume(); let mut announced = consumer.routes(); @@ -10764,7 +10764,7 @@ mod tests { fn cluster_subscriber(self_origin: crate::Hop) -> (Subscriber, crate::origin::Producer) { let session = crate::lite::test_transport::SinkSession::new(Default::default()); - let origin = crate::origin::Config::new(self_origin).produce(); + let origin = crate::origin::Config::from(self_origin).produce(); let (tasks, task_set) = crate::util::TaskSet::new(); // The set only drains announce-serving tasks; the tests here drive the model // directly, so leaking it keeps the handles alive without a spawner. @@ -10898,7 +10898,7 @@ mod tests { async fn a_lost_namespace_stream_closes_the_broadcast() { const VERSION: Version = Version::Draft18; - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let consumer = origin.consume(); // The peer answers, advertises one namespace, then the stream ends without ever @@ -10952,7 +10952,7 @@ mod tests { async fn a_re_sent_namespace_reprices_in_place() { const VERSION: Version = Version::Draft18; - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let consumer = origin.consume(); let script = { @@ -11063,7 +11063,7 @@ mod tests { async fn publish_namespace_requester_fin_keeps_the_route() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { for reset in [false, true] { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let consumer = origin.consume(); let session = if reset { crate::lite::test_transport::ScriptedSession::per_stream_reset(vec![vec![]]) @@ -11121,7 +11121,7 @@ mod tests { async fn a_broken_publish_namespace_stream_closes_the_broadcast() { const VERSION: Version = Version::Draft18; - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let consumer = origin.consume(); // The peer sends something that does not belong on this stream, ending it with an @@ -11522,7 +11522,7 @@ mod tests { const VERSION: Version = Version::Draft18; let session = crate::lite::test_transport::ScriptedSession::new(script); let log = session.log.clone(); - let (origin, driver) = crate::origin::Producer::new(crate::origin::Config::new(self_origin)); + let (origin, driver) = crate::origin::Producer::new(crate::origin::Config::from(self_origin)); let consumer = origin.consume(); let (tasks, task_set) = crate::util::TaskSet::new(); // The tests drive the loop directly, so nothing spawns; leaking keeps the @@ -11725,7 +11725,7 @@ mod tests { let script = publish_namespace_updates(&[looped, clean.clone()]).await; let session = crate::lite::test_transport::ScriptedSession::new(script); let log = session.log.clone(); - let (origin, driver) = crate::origin::Producer::new(crate::origin::Config::new(self_origin)); + let (origin, driver) = crate::origin::Producer::new(crate::origin::Config::from(self_origin)); std::mem::forget(driver); let consumer = origin.consume(); let (tasks, task_set) = crate::util::TaskSet::new(); @@ -12102,7 +12102,7 @@ mod tests { // An open gate, so the rejection actually reaches the wire. let gate = kio::Producer::new(true); let session = crate::lite::test_transport::SinkSession::gated_bi(gate.consume()); - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let consumer = origin.consume(); let (tasks, task_set) = crate::util::TaskSet::new(); std::mem::forget(task_set); @@ -12212,7 +12212,7 @@ mod tests { origin::Consumer, S, ) { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let consumer = origin.consume(); let (tasks, task_set) = crate::util::TaskSet::new(); std::mem::forget(task_set); @@ -13664,7 +13664,7 @@ mod tests { origin::Consumer, crate::lite::test_transport::ScriptedSession, ) { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let consumer = origin.consume(); let (tasks, task_set) = crate::util::TaskSet::new(); std::mem::forget(task_set); @@ -14584,7 +14584,7 @@ mod stitch_tests { /// track. fn with_timescale(fill: Fill, scripts: Vec>, timescale: Option) -> Self { let session = ScriptedSession::per_stream_eof(scripts); - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let tasks = TaskSet::new(); let subscriber = Subscriber::new( @@ -14959,7 +14959,7 @@ mod stitch_tests { hop: bool, ) -> (Vec, crate::lite::test_transport::Log) { use crate::lite::test_transport::Sent; - let origin = crate::origin::Config::new(crate::Hop::new(2).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(2).unwrap()).produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::default()).unwrap(); let track = broadcast .broadcast() @@ -17150,7 +17150,7 @@ mod stitch_tests { let subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::default(), @@ -17334,7 +17334,7 @@ mod joining_fetch_tests { let subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), control, None, peer::PeerSetup::declared(peer::Peer::default()), @@ -17405,7 +17405,7 @@ mod joining_fetch_tests { let subscriber = Subscriber::new( crate::time::sim(), session, - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::default(), @@ -17444,7 +17444,7 @@ mod joining_fetch_tests { let mut subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::declared(peer::Peer::default()), @@ -18232,7 +18232,7 @@ mod joining_fetch_tests { let mut subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::default(), @@ -18480,7 +18480,7 @@ mod joining_fetch_tests { let subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::default(), @@ -18544,7 +18544,7 @@ mod joining_fetch_tests { let subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::default(), @@ -18674,7 +18674,7 @@ mod joining_fetch_tests { let subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::default(), @@ -18800,7 +18800,7 @@ mod new_group_tests { let mut subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::declared(peer::Peer::default()), @@ -19338,7 +19338,7 @@ mod track_property_tests { let mut subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::declared(peer::Peer::default()), @@ -19532,7 +19532,7 @@ mod full_track_name_tests { let subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::declared(peer::Peer::default()), diff --git a/rs/moq-net/src/ietf/subscriber/tracks.rs b/rs/moq-net/src/ietf/subscriber/tracks.rs index fb8c8a0c701..e98ac98db9f 100644 --- a/rs/moq-net/src/ietf/subscriber/tracks.rs +++ b/rs/moq-net/src/ietf/subscriber/tracks.rs @@ -1842,7 +1842,7 @@ mod tests { let subscriber = Subscriber::new( crate::time::sim(), crate::driver::Transport::new(session.clone()), - crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), Control::new(false), None, peer::PeerSetup::declared(peer::Peer::default()), diff --git a/rs/moq-net/src/lite/compress.rs b/rs/moq-net/src/lite/compress.rs index 1ab2bfeb1ea..fd4ad5ce677 100644 --- a/rs/moq-net/src/lite/compress.rs +++ b/rs/moq-net/src/lite/compress.rs @@ -748,11 +748,11 @@ mod tests { fn golden() -> Vec { use crate::fuzz::Announced; vec![ - Announced::Start(Path::from_static("room/a/cam"), hops(&[0x1111, 0x2222])), - Announced::Start(Path::from_static("room/a/mic"), hops(&[0x3333, 0x2222])), - Announced::Update(0, hops(&[0x4444, 0x2222])), + Announced::Start(Path::from_static("room/a/cam"), vec![0x1111, 0x2222]), + Announced::Start(Path::from_static("room/a/mic"), vec![0x3333, 0x2222]), + Announced::Update(0, vec![0x4444, 0x2222]), Announced::End(1), - Announced::Start(Path::from_static("room/b"), hops(&[0x5555, 0x2222])), + Announced::Start(Path::from_static("room/b"), vec![0x5555, 0x2222]), ] } diff --git a/rs/moq-net/src/lite/ietf.rs b/rs/moq-net/src/lite/ietf.rs index c3ee0e632b5..b247d0e3559 100644 --- a/rs/moq-net/src/lite/ietf.rs +++ b/rs/moq-net/src/lite/ietf.rs @@ -735,7 +735,7 @@ pub(crate) async fn test_hop( ) -> (crate::origin::Producer, [crate::Session; 2]) { use crate::model::ProduceTest; let version = crate::Version::Lite(Version::Lite07); - let downstream = crate::origin::Config::new(crate::Hop::new(3).unwrap()).produce(); + let downstream = crate::origin::Config::new(std::num::NonZeroU64::new(3).unwrap()).produce(); let (client, server) = crate::transport::memory::pair(crate::transport::memory::Config { protocol: Some(version.alpn().to_string()), ..Default::default() @@ -874,7 +874,7 @@ mod hop_tests { async fn relayed_state_crosses_while_the_group_is_open() { for offer in [[true, true], [true, false], [false, true]] { let negotiated = offer == [true, true]; - let upstream = crate::origin::Config::new(crate::Hop::new(2).unwrap()).produce(); + let upstream = crate::origin::Config::new(std::num::NonZeroU64::new(2).unwrap()).produce(); let broadcast = upstream.route("room", crate::origin::RouteOptions::default()).unwrap(); let mut info = track::Info::timed().with_timescale(Timescale::MILLI); info.max_age = Some(Duration::from_secs(7)); @@ -981,7 +981,7 @@ mod hop_tests { /// Subscribe across a negotiated hop to a track with `info`. async fn subscribe_across_info(info: track::Info) -> Result<(), crate::Error> { - let upstream = crate::origin::Config::new(crate::Hop::new(2).unwrap()).produce(); + let upstream = crate::origin::Config::new(std::num::NonZeroU64::new(2).unwrap()).produce(); let broadcast = upstream.route("room", crate::origin::RouteOptions::default()).unwrap(); let _track = broadcast.broadcast().create_track("video", info).unwrap(); @@ -1090,7 +1090,7 @@ mod hop_tests { /// relay state appears on the way, nor a moq-transport draft. #[kio::test] async fn plain_media_crosses_unchanged() { - let upstream = crate::origin::Config::new(crate::Hop::new(2).unwrap()).produce(); + let upstream = crate::origin::Config::new(std::num::NonZeroU64::new(2).unwrap()).produce(); let broadcast = upstream.route("room", crate::origin::RouteOptions::default()).unwrap(); let track = broadcast .broadcast() @@ -1130,7 +1130,7 @@ mod hop_tests { async fn ietf_timestamps_keep_their_provenance_across_a_hop() { for offer in [[true, true], [true, false], [false, true]] { let negotiated = offer == [true, true]; - let upstream = crate::origin::Config::new(crate::Hop::new(2).unwrap()).produce(); + let upstream = crate::origin::Config::new(std::num::NonZeroU64::new(2).unwrap()).produce(); let broadcast = upstream.route("room", crate::origin::RouteOptions::default()).unwrap(); let info = track::Info { properties: draft22(Vec::new()), @@ -1198,7 +1198,7 @@ mod hop_tests { /// follows its Object Record. #[kio::test] async fn compressed_media_crosses_a_negotiated_hop() { - let upstream = crate::origin::Config::new(crate::Hop::new(2).unwrap()).produce(); + let upstream = crate::origin::Config::new(std::num::NonZeroU64::new(2).unwrap()).produce(); let broadcast = upstream.route("room", crate::origin::RouteOptions::default()).unwrap(); let info = track::Info::timed() .with_timescale(Timescale::MILLI) diff --git a/rs/moq-net/src/lite/publisher.rs b/rs/moq-net/src/lite/publisher.rs index 2d1bd4b46f1..faebe2cb4bb 100644 --- a/rs/moq-net/src/lite/publisher.rs +++ b/rs/moq-net/src/lite/publisher.rs @@ -236,7 +236,7 @@ impl Publisher { // Identity stamped onto outbound announce hops. Derived from the // origin we're consuming so it matches the local relay identity // across every session, required for cross-session loop detection. - let self_origin = config.origin.hop(); + let self_origin = crate::Hop::from(config.origin.hop()); let accept = config.session.clone(); let enforce = (config.client && config.version.has_auth()).then(Enforce::default); Self { @@ -3633,7 +3633,11 @@ mod announce_test { ), reader: Reader::new(crate::transport::boxed::RecvStream::new(PendingRecv), Version::Lite07), }; - let mut run = AnnounceRun::new(crate::Path::from_static(""), consumer.hop(), Version::Lite07); + let mut run = AnnounceRun::new( + crate::Path::from_static(""), + crate::Hop::from(consumer.hop()), + Version::Lite07, + ); let waiter = kio::Waiter::noop(); assert!(run.poll(&mut stream, &consumer, &mut announced, &waiter).is_pending()); drop(removed); @@ -3679,7 +3683,11 @@ mod announce_test { ), reader: Reader::new(crate::transport::boxed::RecvStream::new(PendingRecv), Version::Lite07), }; - let mut run = AnnounceRun::new(crate::Path::from_static(""), consumer.hop(), Version::Lite07); + let mut run = AnnounceRun::new( + crate::Path::from_static(""), + crate::Hop::from(consumer.hop()), + Version::Lite07, + ); let waiter = kio::Waiter::noop(); assert!(run.poll(&mut stream, &consumer, &mut announced, &waiter).is_pending()); let auth = crate::auth::Link::new(false); @@ -3721,7 +3729,11 @@ mod announce_test { ), reader: Reader::new(crate::transport::boxed::RecvStream::new(PendingRecv), Version::Lite07), }; - let mut run = AnnounceRun::new(crate::Path::from_static(""), consumer.hop(), Version::Lite07); + let mut run = AnnounceRun::new( + crate::Path::from_static(""), + crate::Hop::from(consumer.hop()), + Version::Lite07, + ); let waiter = kio::Waiter::noop(); assert!(run.poll(&mut stream, &consumer, &mut announced, &waiter).is_pending()); let auth = crate::auth::Link::new(false); @@ -3777,7 +3789,11 @@ mod announce_test { ), reader: Reader::new(crate::transport::boxed::RecvStream::new(PendingRecv), Version::Lite07), }; - let mut run = AnnounceRun::new(crate::Path::from_static(""), consumer.hop(), Version::Lite07); + let mut run = AnnounceRun::new( + crate::Path::from_static(""), + crate::Hop::from(consumer.hop()), + Version::Lite07, + ); let waiter = kio::Waiter::noop(); assert!(run.poll(&mut stream, &consumer, &mut announced, &waiter).is_pending()); drop(unseen); @@ -3817,7 +3833,11 @@ mod announce_test { ), reader: Reader::new(crate::transport::boxed::RecvStream::new(PendingRecv), Version::Lite07), }; - let mut run = AnnounceRun::new(crate::Path::from_static(""), consumer.hop(), Version::Lite07); + let mut run = AnnounceRun::new( + crate::Path::from_static(""), + crate::Hop::from(consumer.hop()), + Version::Lite07, + ); assert!( run.poll(&mut stream, &consumer, &mut announced, &kio::Waiter::noop()) .is_pending() @@ -3929,7 +3949,7 @@ mod announce_test { }; let _task = kio::clock::sim::spawn(async move { let mut announced = consumer.routes(); - let self_origin = consumer.hop(); + let self_origin = crate::Hop::from(consumer.hop()); TestPublisher::run_announce(&mut stream, &consumer, &mut announced, self_origin, VERSION, None).await }); settle().await; @@ -3962,7 +3982,7 @@ mod announce_test { }; let task = kio::clock::sim::spawn(async move { let mut announced = consumer.routes(); - let self_origin = consumer.hop(); + let self_origin = crate::Hop::from(consumer.hop()); TestPublisher::run_announce(&mut stream, &consumer, &mut announced, self_origin, version, auth).await }); settle().await; @@ -4223,7 +4243,7 @@ mod announce_test { }; let task = kio::clock::sim::spawn(async move { let mut announced = consumer.routes(); - let self_origin = consumer.hop(); + let self_origin = crate::Hop::from(consumer.hop()); TestPublisher::run_announce(&mut stream, &consumer, &mut announced, self_origin, VERSION, None).await }); settle().await; @@ -7849,7 +7869,7 @@ mod serve_group_test { } fn origin(hop: u64) -> origin::Producer { - let (origin, driver) = origin::Producer::new(origin::Config::new(crate::Hop::new(hop).unwrap())); + let (origin, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); drive(driver); origin } @@ -8672,7 +8692,7 @@ mod tests { async fn serving_origin_falls_back_to_the_assigned_identity() { let assigned = crate::Hop::new(777).unwrap(); let upstream = crate::Hop::new(778).unwrap(); - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let mut echoed_hops = Hops::new(); echoed_hops.push(crate::Hop::UNKNOWN).unwrap(); @@ -8733,7 +8753,7 @@ mod tests { let assigned = crate::Hop::new(777).unwrap(); let clean_publisher = crate::Hop::new(778).unwrap(); let self_origin = crate::Hop::new(1).unwrap(); - let origin = crate::origin::Config::new(self_origin).produce(); + let origin = crate::origin::Config::from(self_origin).produce(); let mut tainted_hops = Hops::new(); tainted_hops.push(crate::Hop::UNKNOWN).unwrap(); @@ -8787,7 +8807,7 @@ mod tests { #[kio::test] async fn announce_init_past_the_cap_fails() { let self_origin = crate::Hop::new(1).unwrap(); - let origin = crate::origin::Config::new(self_origin).produce(); + let origin = crate::origin::Config::from(self_origin).produce(); let max = ::MAX_SIZE; // Each suffix costs its length plus a varint prefix, so these overflow the cap. let name = "x".repeat(500); @@ -8824,7 +8844,7 @@ mod tests { #[kio::test] async fn announce_init_broadcast_ends() { let self_origin = crate::Hop::new(1).unwrap(); - let origin = crate::origin::Config::new(self_origin).produce(); + let origin = crate::origin::Config::from(self_origin).produce(); let cam = origin.announce("cam", crate::origin::RouteInfo::default()).unwrap(); let gate = kio::Producer::new(true); @@ -8860,7 +8880,7 @@ mod tests { #[kio::test] async fn withdraw_before_init_sends_the_initial_burst() { let self_origin = crate::Hop::new(1).unwrap(); - let origin = crate::origin::Config::new(self_origin).produce(); + let origin = crate::origin::Config::from(self_origin).produce(); let _cam = origin.announce("cam", crate::origin::RouteInfo::default()).unwrap(); let gate = kio::Producer::new(true); @@ -9258,7 +9278,7 @@ mod tests { /// requester close its send side. async fn leave_request(version: Version, request: &impl Encode, wait: Wait, close: Close) { let case = format!("{} over {version:?}, waiting on the {wait:?}, {close:?}", R::KIND); - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); // Held, never answered. let mut _route = None; let mut held = None; @@ -9398,7 +9418,7 @@ mod tests { #[kio::test] async fn a_broadcast_too_long_under_the_root_is_refused_per_request() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let root = "r".repeat(crate::Path::MAX_BYTES - 2); let scoped = origin .consume() @@ -9464,7 +9484,7 @@ mod tests { #[kio::test] async fn track_info_outranks_the_track_groups() { let version = Version::Lite07; - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::hidden()).unwrap(); let _track = broadcast .broadcast() @@ -9595,7 +9615,7 @@ mod tests { for version in [Version::Lite05, Version::Lite06] { for stream in [false, true] { let case = format!("{version:?}, stream track {stream}"); - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::hidden()).unwrap(); let mut datagrams = broadcast .broadcast() @@ -9636,7 +9656,7 @@ mod tests { #[kio::test] async fn a_waiting_subscribe_sends_the_datagrams_written_since_its_track_info() { for version in [Version::Lite05, Version::Lite06] { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::hidden()).unwrap(); let _relayed = crate::model::broadcast::SourceGuard::new(broadcast.broadcast().clone()); let mut datagrams = broadcast @@ -9665,7 +9685,7 @@ mod tests { #[kio::test] async fn a_subscribe_reads_from_the_oldest_hold() { for version in [Version::Lite05, Version::Lite06] { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::hidden()).unwrap(); let mut datagrams = broadcast .broadcast() @@ -9691,7 +9711,7 @@ mod tests { #[kio::test] async fn a_subscribe_reads_the_current_datagram_track_past_an_older_hold() { for version in [Version::Lite05, Version::Lite06] { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::hidden()).unwrap(); let mut first = broadcast .broadcast() @@ -9730,7 +9750,7 @@ mod tests { for close in [Close::Fin, Close::Reset] { for blocked in [false, true] { let case = format!("{version:?}, {close:?}, blocked {blocked}"); - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::hidden()).unwrap(); let track = broadcast .broadcast() @@ -9865,7 +9885,7 @@ mod tests { Answer::Empty, ] { for start in [None, Some(0)] { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::hidden()).unwrap(); let mut dynamic = broadcast.broadcast().requests(); broadcast.announce().unwrap(); @@ -10011,7 +10031,7 @@ mod tests { /// exists the same value asks for nothing more. #[kio::test] async fn a_subscribe_update_is_not_a_close() { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::hidden()).unwrap(); let mut dynamic = broadcast.broadcast().requests(); broadcast.announce().unwrap(); @@ -10140,7 +10160,7 @@ mod tests { } async fn running() -> Running { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::hidden()).unwrap(); let mut dynamic = broadcast.broadcast().requests(); broadcast.announce().unwrap(); @@ -10393,7 +10413,7 @@ mod tests { /// store an undecodable tail merely because that was the downstream reader's floor. #[kio::test] async fn a_cold_bounded_fetch_requests_the_prefix() { - let origin = crate::origin::Config::new(Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::hidden()).unwrap(); let track = broadcast .broadcast() @@ -10443,7 +10463,7 @@ mod tests { #[kio::test] async fn an_expired_fetch_resets_rather_than_finishing() { const VERSION: Version = Version::Lite07; - let origin = crate::origin::Config::new(Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::hidden()).unwrap(); let track = broadcast .broadcast() @@ -10589,7 +10609,7 @@ mod tests { async fn malformed_subscribe_update_closes_after_request_setup() { use kio::Task; for version in [Version::Lite05, Version::Lite06, Version::Lite07] { - let origin = crate::origin::Config::new(Hop::random()).produce(); + let origin = crate::origin::Config::default().produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::hidden()).unwrap(); let _dynamic = broadcast.broadcast().requests(); broadcast.announce().unwrap(); @@ -10648,7 +10668,7 @@ mod tests { async fn a_newer_listing_of_a_broadcast_replaces_the_older() { use kio::Task; let version = Version::Lite07; - let origin = crate::origin::Config::new(Hop::random()).produce(); + let origin = crate::origin::Config::default().produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::hidden()).unwrap(); broadcast.announce().unwrap(); let request = lite::Tracks { @@ -10701,7 +10721,7 @@ mod tests { async fn a_producer_decode_error_stays_on_its_request() { use kio::Task; for version in [Version::Lite05, Version::Lite06, Version::Lite07] { - let origin = crate::origin::Config::new(Hop::random()).produce(); + let origin = crate::origin::Config::default().produce(); let broadcast = origin.route("room", crate::origin::RouteOptions::hidden()).unwrap(); let mut dynamic = broadcast.broadcast().requests(); broadcast.announce().unwrap(); @@ -10887,7 +10907,7 @@ mod tests { /// publisher's track priority breaks a tie between two at one subscriber priority. #[kio::test] async fn send_group_ranks_by_the_subscriber_then_the_publisher() { - let origin = crate::origin::Config::new(Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let broadcast = origin.route("a", crate::origin::RouteOptions::hidden()).unwrap(); let mut dynamic = broadcast.broadcast().requests(); broadcast.announce().unwrap(); diff --git a/rs/moq-net/src/lite/session.rs b/rs/moq-net/src/lite/session.rs index 192568cffc8..f5171b1cc3e 100644 --- a/rs/moq-net/src/lite/session.rs +++ b/rs/moq-net/src/lite/session.rs @@ -263,7 +263,7 @@ pub fn start(config: Config) -> Result { .as_ref() .map(|origin| origin.hop()) .or_else(|| subscribe.as_ref().map(|origin| origin.hop())) - .filter(|hop| hop.id() != 0); + .map(Hop::from); } // Prove our origin's route key, bound to this session, so a peer that scopes us files @@ -296,12 +296,8 @@ pub fn start(config: Config) -> Result { // An unset half gets an empty origin: an empty publish origin announces nothing // (and answers the peer's announce-interest with an empty set), and an empty // subscribe origin issues no ANNOUNCE_PLEASE. - let publish = publish.unwrap_or_else(|| { - origin::Producer::empty(Hop::random()) - .consume() - .with_stats(stats.clone()) - }); - let subscribe = subscribe.unwrap_or_else(|| origin::Producer::empty(Hop::random()).with_stats(stats.clone())); + let publish = publish.unwrap_or_else(|| origin::Producer::empty().consume().with_stats(stats.clone())); + let subscribe = subscribe.unwrap_or_else(|| origin::Producer::empty().with_stats(stats.clone())); // Before lite-07 the peer can't ask for hidden routes, so a client publishes none of // them unless its publish half opted in, and a socket endpoint behind it is // unreachable. A server leaves it to the client, whose origin holds that endpoint. diff --git a/rs/moq-net/src/lite/setup.rs b/rs/moq-net/src/lite/setup.rs index 8ac3d5b27d8..3b1c92ff84d 100644 --- a/rs/moq-net/src/lite/setup.rs +++ b/rs/moq-net/src/lite/setup.rs @@ -332,7 +332,8 @@ impl<'a> Message<'a> for ReceivedSetup { // so it decodes as "not declared" rather than an error. let hop = params .get_varint(PARAM_HOP, version)? - .and_then(|id| crate::Hop::new(id).ok()); + .and_then(std::num::NonZeroU64::new) + .map(crate::Hop::from); let implementation = if version.has_implementation() { crate::setup::decode_implementation(params.get_bytes(PARAM_IMPLEMENTATION))? } else { diff --git a/rs/moq-net/src/lite/subscriber.rs b/rs/moq-net/src/lite/subscriber.rs index 2f9db70b5e2..fb28e93b130 100644 --- a/rs/moq-net/src/lite/subscriber.rs +++ b/rs/moq-net/src/lite/subscriber.rs @@ -423,7 +423,7 @@ impl Subscriber { // origin we publish into so it matches the relay identity across // every session sharing that origin, required for cross-session // loop detection. - let self_origin = config.origin.hop(); + let self_origin = crate::Hop::from(config.origin.hop()); Self { session: config.session, runtime: config.runtime, @@ -3946,7 +3946,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version, peer_setup: lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -4000,7 +4000,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(local.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version: Version::Lite07, peer_setup: lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -4033,7 +4033,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(local.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version: Version::Lite07, peer_setup: lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -4069,7 +4069,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(local), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version: Version::Lite07, peer_setup: lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -4131,7 +4131,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(local), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version: Version::Lite07, peer_setup: lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -4283,7 +4283,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version, peer_setup: peer_setup.clone(), @@ -4342,7 +4342,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version, peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -4438,7 +4438,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version, peer_setup, @@ -4620,7 +4620,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version, peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -4777,7 +4777,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: clock.clone(), session: crate::driver::Transport::new(session.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version, peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -4849,7 +4849,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version, peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -4912,7 +4912,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version, peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -5019,7 +5019,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version, peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -5091,7 +5091,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version, peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -5161,7 +5161,7 @@ mod tests { /// Drive the subscriber with a peer's response bytes followed by FIN. async fn check_subscription_fin(version: Version, responses: Vec, clean: bool) { let session = crate::lite::test_transport::ScriptedSession::eof(responses); - let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), @@ -5281,7 +5281,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version, peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -5353,7 +5353,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version, peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -5441,7 +5441,7 @@ mod tests { #[kio::test] async fn route_datagram_delivers_to_its_subscription() { for version in [Version::Lite05, Version::Lite06, Version::Lite07] { - let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(SinkSession::default()), @@ -5518,7 +5518,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(SinkSession::default()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version: VERSION, peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -5564,7 +5564,7 @@ mod tests { #[kio::test] async fn announce_interest_waits_for_credit() { for version in [Version::Lite04, Version::Lite07] { - let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let _interest = origin.consume().routes(); let session = crate::lite::test_transport::ScriptedSession::new(Vec::new()).without_credit(); let log = session.log.clone(); @@ -5601,7 +5601,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version, peer_setup: lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -5664,7 +5664,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version: VERSION, peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -5717,7 +5717,7 @@ mod tests { Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session, - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version, peer_setup, @@ -6054,7 +6054,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version: VERSION, peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -6109,7 +6109,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version: Version::Lite07, peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -6255,7 +6255,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(SinkSession::default()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version: VERSION, peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -6311,7 +6311,7 @@ mod tests { let gate = kio::Producer::new(false); let session = SinkSession::gated_bi(gate.consume()); - let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), @@ -6379,7 +6379,7 @@ mod tests { let session = SinkSession::gated_bi(gate.consume()); let auth = crate::auth::Link::new(false); - let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), @@ -6450,7 +6450,7 @@ mod tests { // what was true at the instant it would. let gate = kio::Producer::new(true); let session = SinkSession::gated_bi(gate.consume()); - let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), @@ -6535,7 +6535,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version, peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -6608,7 +6608,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version, peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -6680,7 +6680,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: Some(producer), version, peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Address::Setup), @@ -6745,7 +6745,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session.clone()), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: Some(producer), version, peer_setup, @@ -7087,7 +7087,7 @@ mod tests { #[kio::test] async fn a_double_announce_is_an_error_even_when_reflected() { let assigned = crate::Hop::new(777).unwrap(); - let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let mut subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(SinkSession::new(Default::default())), @@ -7180,7 +7180,7 @@ mod tests { /// every announced route there made each group cost the whole announce set. #[kio::test] async fn a_request_readies_only_its_route() { - let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let mut subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(SinkSession::new(Default::default())), @@ -7234,7 +7234,7 @@ mod tests { /// route afresh. Withdrawing the claim still closes a source in use at once. #[kio::test] async fn an_unheld_source_is_retired() { - let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let mut subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(SinkSession::new(Default::default())), @@ -7303,7 +7303,7 @@ mod tests { /// machine, rather than the front finding no handler and ending the track `NotFound`. #[kio::test] async fn a_track_read_before_its_source_is_served_queues() { - let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let mut subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(SinkSession::new(Default::default())), @@ -7359,7 +7359,7 @@ mod tests { #[kio::test] async fn every_declined_announce_is_recorded() { let assigned = crate::Hop::new(777).unwrap(); - let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let mut subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(SinkSession::new(Default::default())), @@ -7417,7 +7417,7 @@ mod tests { #[kio::test] async fn a_dropped_announce_still_holds_its_path() { let assigned = crate::Hop::new(777).unwrap(); - let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let consumer = origin.consume(); let mut subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), @@ -7476,7 +7476,7 @@ mod tests { async fn an_announce_reflected_by_its_sender_is_dropped() { let assigned = crate::Hop::new(777).unwrap(); - let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let consumer = origin.consume(); let mut subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), @@ -7520,7 +7520,7 @@ mod tests { #[kio::test] async fn a_reflected_announce_does_not_displace_the_local_front() { let relay = crate::Hop::new(1).unwrap(); - let origin = origin::Config::new(relay).produce(); + let origin = origin::Config::from(relay).produce(); let assigned = crate::Hop::new(777).unwrap(); let local = origin @@ -7608,7 +7608,7 @@ mod tests { let session = SinkSession::new(Default::default()); let assigned = crate::Hop::new(777).unwrap(); - let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let consumer = origin.consume(); let mut subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), @@ -7655,7 +7655,7 @@ mod tests { #[kio::test] async fn lite03_placeholders_stay_anonymous() { let assigned = crate::Hop::new(777).unwrap(); - let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let consumer = origin.consume(); let mut subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), @@ -7737,7 +7737,7 @@ mod tests { } fn restart_subscriber(session: SinkSession) -> (Subscriber, crate::origin::Consumer) { - let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let consumer = origin.consume(); let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), @@ -7893,7 +7893,7 @@ mod tests { /// to the session (outliving the stream) would leak the announcement instead. #[kio::test] async fn a_lost_announce_stream_retracts_the_route() { - let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let consumer = origin.consume(); let mut subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), @@ -7978,7 +7978,7 @@ mod tests { .encode(&mut crate::coding::Encoder::new(&mut script, VERSION.into()), VERSION) .unwrap(); - let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let consumer = origin.consume(); let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), @@ -8047,7 +8047,7 @@ mod tests { version: Version, session: crate::lite::test_transport::ScriptedSession, ) -> (AnnouncePrefix, origin::Consumer) { - let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let consumer = origin.consume(); let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), @@ -8298,7 +8298,7 @@ mod tests { .unwrap(); } - let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce(); + let origin = origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let session = crate::lite::test_transport::ScriptedSession::new(script); let mut subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), @@ -8340,7 +8340,7 @@ mod tests { let subscriber = Subscriber::new(SubscriberConfig { runtime: crate::time::sim(), session: crate::driver::Transport::new(session), - origin: origin::Config::new(crate::Hop::new(1).unwrap()).produce(), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), recv_bandwidth: None, version, peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Address::Setup), diff --git a/rs/moq-net/src/model/mod.rs b/rs/moq-net/src/model/mod.rs index b010421a7b5..5721fda7e90 100644 --- a/rs/moq-net/src/model/mod.rs +++ b/rs/moq-net/src/model/mod.rs @@ -62,7 +62,7 @@ pub mod origin { // private: capability gap pub(crate) use super::origin_impl::Lookup; pub use super::origin_impl::{ - Config, Consumer, Cost, Driver, HopLimit, Link, Preference, Producer, Request, Requesting, Route, RouteInfo, + Config, Consumer, Cost, Driver, Link, Preference, Producer, Request, Requesting, Route, RouteInfo, RouteOptions, Source, }; pub use crate::route::RouteKey; @@ -79,9 +79,13 @@ pub mod announce { pub use super::origin_impl::Announce; } -// Hop identity and the `Consume` conversion trait aren't part of a role -// module; keep them flat at the crate root. -pub use origin_impl::{Consume, Hop, Hops, InvalidHop}; +// The `Consume` conversion trait isn't part of a role module; keep it flat at the +// crate root. +pub use origin_impl::Consume; + +// Hop chains are transit facts the origin and sessions fill in; applications see +// plain ids. +pub(crate) use origin_impl::{Hop, Hops, InvalidHop}; // The announce-interest prefixes a scope needs on a prefix-shaped wire. #[cfg(feature = "async")] diff --git a/rs/moq-net/src/model/origin.rs b/rs/moq-net/src/model/origin.rs index de7f1b46528..7fdfde23d71 100644 --- a/rs/moq-net/src/model/origin.rs +++ b/rs/moq-net/src/model/origin.rs @@ -4,6 +4,7 @@ use std::{ cmp::Reverse, collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque}, fmt, + num::{NonZeroU64, NonZeroUsize}, sync::Arc, sync::atomic::{AtomicU64, AtomicUsize, Ordering}, task::{Context, Poll, Wake, Waker, ready}, @@ -32,11 +33,14 @@ use crate::{ /// origin, and this is the id it stamps into a route's hop chain as an announcement /// passes through, so a receiver can spot its own id and reject a loop. /// -/// Local hops are built with [`Hop::new`] or [`Hop::random`], both of which guarantee a -/// non-zero id so loop detection can work. Remote peers may still send `0`; it is legal -/// on the wire, names nobody, and marks the chain anonymous for route selection. +/// A transit fact the origin and the relays fill in: applications pass plain ids +/// ([`Config::hop`]) and read them back ([`RouteInfo::hops`]). +/// +/// Local hops come from a [`NonZeroU64`] or [`Hop::random`], so loop detection can work. +/// Remote peers may still send `0`; it is legal on the wire, names nobody, and marks the +/// chain anonymous for route selection. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct Hop { +pub(crate) struct Hop { id: u64, } @@ -49,31 +53,21 @@ impl Hop { /// holds one anywhere is anonymous for route selection. pub const UNKNOWN: Self = Self { id: 0 }; - /// Build a hop from a stable id. - /// - /// The id must be non-zero. Wire decode accepts remote id 0 - /// ([`Self::UNKNOWN`]), but a local hop should not use it because it cannot be - /// excluded for loop detection. - pub fn new(id: u64) -> Result { - if id == 0 { - return Err(InvalidHop::Range); - } - Ok(Self { id }) + /// A local hop from a stable id, or `None` for 0, which cannot be excluded for loop + /// detection. + #[cfg(any(test, feature = "fuzz"))] + pub(crate) fn new(id: u64) -> Option { + NonZeroU64::new(id).map(Self::from) } - /// Generate a fresh hop with a random non-zero id. Use this for any relay that - /// does not need a stable identity across restarts. - /// - /// Older `@moq/lite` clients decode the exclude hop as a JavaScript number - /// and reject values above 2^53-1. Keep generated IDs in that range while - /// [`Self::new`] accepts any non-zero 64-bit id. - pub fn random() -> Self { - let id = kio::clock::rng().random_range(1..(1u64 << 53)); - Self { id } + /// Generate a fresh hop with a random non-zero id; see [`random_id`]. + #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))] + pub(crate) fn random() -> Self { + Self::from(random_id()) } - /// Return the origin's wire id. - pub fn id(self) -> u64 { + /// Return the hop's wire id. + pub(crate) fn id(self) -> u64 { self.id } @@ -103,9 +97,9 @@ impl Hop { #[derive(Clone, Debug)] #[non_exhaustive] pub struct Config { - /// The origin's wire identity, appended to broadcast hop chains for loop - /// detection and shortest-path routing. - pub hop: Hop, + /// The origin's hop id, appended to broadcast hop chains for loop detection and + /// shortest-path routing. Random by default. + pub hop: NonZeroU64, /// The key this origin proves to every lite-07 peer, which files the routes it sends /// under it when its grant is scoped. Origins sharing a key fail over as one. `None` @@ -117,8 +111,9 @@ pub struct Config { /// Applies to moq-lite-03+ hop paths and the negotiated MoQ Cluster extension on /// moq-transport. A forwarded path counts this origin's own hop too, including /// when the receiving peer reconstructs that hop from the announce handshake. - /// Protocols without a hop path cannot reveal or bound the depth they hide. - pub max_hops: HopLimit, + /// Protocols without a hop path cannot reveal or bound the depth they hide. No wire + /// carries a path longer than 32, so a larger value acts as 32. + pub max_hops: NonZeroUsize, /// The cache pool broadcasts under this origin charge their groups into. It flows /// down the ownership chain (origin -> broadcast -> track -> group): a track opens @@ -167,9 +162,9 @@ impl Default for Config { fn default() -> Self { let pool = cache::Pool::new(cache::Config::default().with_expiry(cache::DEFAULT_EXPIRY)); Self { - hop: Hop::random(), + hop: random_id(), route_key: None, - max_hops: HopLimit::default(), + max_hops: MAX_HOP_LIMIT, pool, cache_duration: Duration::MAX, update_hold: DEFAULT_UPDATE_HOLD, @@ -178,24 +173,26 @@ impl Default for Config { } impl Config { - /// Config for the given origin id with no byte target and the default idle expiry. - pub fn new(hop: Hop) -> Self { + /// Config for the given origin hop id with no byte target and the default idle expiry. + pub fn new(hop: NonZeroU64) -> Self { Self { hop, ..Self::default() } } } -impl From for Config { - /// Config for the given origin id with the defaults of [`Config::new`]. - fn from(hop: Hop) -> Self { - Self::new(hop) - } +/// A fresh random hop id, for any origin or peer that needs no stable identity across +/// restarts. +/// +/// Older `@moq/lite` clients decode the exclude hop as a JavaScript number and reject +/// values above 2^53-1, so generated ids stay in that range while [`Config::hop`] accepts +/// any non-zero 64-bit id. +pub(crate) fn random_id() -> NonZeroU64 { + NonZeroU64::MIN.saturating_add(kio::clock::rng().random_range(0..(1u64 << 53) - 1)) } -impl TryFrom for Hop { - type Error = InvalidHop; - - fn try_from(id: u64) -> Result { - Self::new(id) +impl From for Hop { + /// A local hop: its non-zero id can be excluded for loop detection. + fn from(id: NonZeroU64) -> Self { + Self { id: id.get() } } } @@ -224,31 +221,8 @@ impl<'a, V> Decode<'a, V> for Hop { /// silently truncating. pub(super) const MAX_HOPS: usize = 32; -/// The longest advertised hop path an origin accepts or forwards, from 1 to 32. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct HopLimit(usize); - -impl HopLimit { - /// A hop-path cap from 1 to 32, or `None` outside that range. - pub const fn new(max: usize) -> Option { - if max == 0 || max > MAX_HOPS { - None - } else { - Some(Self(max)) - } - } - - /// The maximum number of hops in an advertised path. - pub const fn get(self) -> usize { - self.0 - } -} - -impl Default for HopLimit { - fn default() -> Self { - Self(MAX_HOPS) - } -} +/// The default and highest [`Config::max_hops`]. +const MAX_HOP_LIMIT: NonZeroUsize = NonZeroUsize::new(MAX_HOPS).unwrap(); /// Bounded, loop-free list of [`Hop`] entries: the hop chain of a broadcast. /// @@ -258,16 +232,11 @@ impl Default for HopLimit { /// Construct via [`Hops::new`] + [`Hops::push`], or fall back to the /// fallible [`TryFrom>`]. #[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct Hops(Vec); +pub(crate) struct Hops(Vec); -/// Why a [`Hop`] is not usable, on its own or as part of a [`Hops`] chain. +/// Why a [`Hop`] cannot join a [`Hops`] chain. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[non_exhaustive] -pub enum InvalidHop { - /// The id is zero, so it cannot identify a local hop. Only [`Hop::new`] returns - /// this; a chain may still hold the reserved [`Hop::UNKNOWN`]. - Range, - +pub(crate) enum InvalidHop { /// The list is already at its hop-count cap, which a real path never reaches and a /// loop does. TooMany, @@ -281,7 +250,6 @@ pub enum InvalidHop { impl fmt::Display for InvalidHop { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::Range => write!(f, "local hop id must be non-zero"), Self::TooMany => write!(f, "too many hops (max {MAX_HOPS})"), Self::Duplicate => write!(f, "hop already in the chain"), } @@ -294,7 +262,7 @@ impl From for DecodeError { fn from(err: InvalidHop) -> Self { match err { InvalidHop::TooMany => DecodeError::BoundsExceeded, - InvalidHop::Range | InvalidHop::Duplicate => DecodeError::InvalidValue, + InvalidHop::Duplicate => DecodeError::InvalidValue, } } } @@ -345,6 +313,17 @@ impl Hops { pub fn as_slice(&self) -> &[Hop] { &self.0 } + + /// The entries' ids, in hop order. + pub(crate) fn ids(&self) -> impl ExactSizeIterator + '_ { + self.0.iter().map(|hop| hop.id) + } + + /// The entries' ids, in hop order, reusing the list's allocation. + #[cfg(any(test, feature = "fuzz"))] + pub(crate) fn into_ids(self) -> Vec { + self.0.into_iter().map(|hop| hop.id).collect() + } } impl TryFrom> for Hops { @@ -543,9 +522,10 @@ pub enum Source { /// Announced on this origin: by an in-process producer or a client session. #[default] Local, - /// Learned from a cluster peer, named by the announcing session's declared or - /// assigned identity. - Peer(Hop), + /// Learned from a cluster peer, named by the hop id the announcing session declared + /// or was assigned. 0 when the announcing handle named none: a peer handle in-process, + /// or a session whose peer declared no hop and was assigned none. + Peer(u64), } impl RouteInfo { @@ -556,12 +536,12 @@ impl RouteInfo { self.instance.as_ref().expect("a delivered route has an instance") } - /// The chain of origins the route has traversed, oldest first. Each relay + /// The hop ids of the origins the route has traversed, oldest first. Each relay /// appends its own hop when forwarding; used for loop detection and as the /// selection tie-break. A 0 entry is the anonymous mark and travels unchanged; /// see [`Self::is_anonymous`]. A route announced on this origin has none. - pub fn hops(&self) -> &Hops { - &self.hops + pub fn hops(&self) -> impl ExactSizeIterator + '_ { + self.hops.ids() } /// What pulling content via this route costs, accumulated per link: lower wins @@ -1389,7 +1369,7 @@ impl RouteEntry { fn entered(&self) -> Source { match self.link { Link::Local => Source::Local, - Link::Peer | Link::Upstream => Source::Peer(self.via), + Link::Peer | Link::Upstream => Source::Peer(self.via.id()), } } @@ -1519,7 +1499,7 @@ struct Horizon { /// Hide the routes with no room for our hop under this cap, because this reader /// forwards them ([`Consumer::forwardable`]). Selection then falls back to a /// shorter route instead of withdrawing a prefix an in-cap path still reaches. - max_hops: Option, + max_hops: Option, } impl Horizon { @@ -2156,8 +2136,8 @@ pub struct Announce { pub struct Producer { // Identity for this origin. Appended to route hops when re-announcing so // downstream relays can detect loops and prefer the shortest path. - hop: Hop, - max_hops: HopLimit, + hop: NonZeroU64, + max_hops: NonZeroUsize, // The absolute patterns this handle may publish under. scope: OriginScope, @@ -2223,7 +2203,7 @@ impl Producer { let pool = config.pool.clone(); let producer = Self { hop: config.hop, - max_hops: config.max_hops, + max_hops: config.max_hops.min(MAX_HOP_LIMIT), scope: scope.clone(), root: Path::default(), shared: shared.clone(), @@ -2310,8 +2290,8 @@ impl Producer { } } - /// This origin's hop identity. - pub fn hop(&self) -> Hop { + /// This origin's hop id; see [`Config::hop`]. + pub fn hop(&self) -> NonZeroU64 { self.hop } @@ -2323,7 +2303,7 @@ impl Producer { // Sessions enforce the policy configured once on the origin. #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))] - pub(crate) fn max_hops(&self) -> HopLimit { + pub(crate) fn max_hops(&self) -> NonZeroUsize { self.max_hops } @@ -2332,14 +2312,14 @@ impl Producer { /// subscriber issues no ANNOUNCE_PLEASE). Used to fill an unset session half /// so both the publisher and subscriber loops still run. #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))] - pub(crate) fn empty(hop: Hop) -> Self { + pub(crate) fn empty() -> Self { // No allowed prefixes means no broadcast is ever created, so nothing will // ever be queued on the detached submission handle. let (tasks, _) = TaskSet::new(); Self { - hop, + hop: random_id(), scope: OriginScope::empty(), - max_hops: HopLimit::default(), + max_hops: MAX_HOP_LIMIT, root: Path::default(), shared: SendCell::new(kio::Shared::new(OriginState::new(DEFAULT_UPDATE_HOLD, None))), pool: cache::Pool::default(), @@ -2413,7 +2393,7 @@ impl Producer { // hidden from cursors and requests until it announces. The entry lives // as long as the route, or until the broadcast closes. let announcing = Announcing { - hop: self.hop, + hop: Hop::from(self.hop), shared: self.shared.clone(), requested: full.clone(), prefixes: vec![(full.clone(), claim)], @@ -2831,7 +2811,7 @@ impl Announcing { return Err(Error::Unauthorized); } Ok(Self { - hop: producer.hop, + hop: Hop::from(producer.hop), shared: producer.shared.clone(), requested: requested.clone(), prefixes: vec![(requested, claim)], @@ -6865,8 +6845,8 @@ impl Consume for track::Consumer { #[derive(Clone)] pub struct Consumer { // Identity of the origin this consumer was derived from. - hop: Hop, - max_hops: HopLimit, + hop: NonZeroU64, + max_hops: NonZeroUsize, scope: OriginScope, // A prefix that is automatically stripped from all paths. @@ -6937,8 +6917,8 @@ impl Consumer { } } - /// This origin's hop identity. - pub fn hop(&self) -> Hop { + /// This origin's hop id; see [`Config::hop`]. + pub fn hop(&self) -> NonZeroU64 { self.hop } @@ -8130,7 +8110,15 @@ impl ProduceTest for Config { #[cfg(test)] impl ProduceTest for Hop { fn produce(self) -> Producer { - Config::new(self).produce() + Config::from(self).produce() + } +} + +/// Test-only: an origin's config for a local hop. +#[cfg(test)] +impl From for Config { + fn from(hop: Hop) -> Self { + Self::new(NonZeroU64::new(hop.id).expect("a local hop is non-zero")) } } @@ -8186,22 +8174,21 @@ mod tests { use super::*; #[test] - fn hop_limit_refuses_values_outside_the_wire_bound() { - for invalid in [0, 33, usize::MAX] { - assert_eq!(HopLimit::new(invalid), None); - } - for valid in [1, 6, 32] { - assert_eq!(HopLimit::new(valid).unwrap().get(), valid); + fn max_hops_caps_at_the_wire_bound() { + assert_eq!(Config::default().max_hops.get(), MAX_HOPS); + for (max, effective) in [(1, 1), (6, 6), (32, 32), (33, 32), (usize::MAX, 32)] { + let config = Config { + max_hops: NonZeroUsize::new(max).unwrap(), + ..Default::default() + }; + let (producer, _driver) = Producer::new(config); + let scoped = producer.scope("room", &Patterns::from(Pattern::all())).unwrap(); + assert_eq!(scoped.config().max_hops.get(), effective); + assert_eq!( + scoped.consume().forwardable().horizon.max_hops.map(NonZeroUsize::get), + Some(effective) + ); } - assert_eq!(HopLimit::default().get(), 32); - let config = Config { - max_hops: HopLimit::new(6).unwrap(), - ..Default::default() - }; - let (producer, _driver) = Producer::new(config); - let scoped = producer.scope("room", &Patterns::from(Pattern::all())).unwrap(); - assert_eq!(scoped.config().max_hops.get(), 6); - assert_eq!(scoped.consume().forwardable().horizon.max_hops, HopLimit::new(6)); } #[cfg(feature = "async")] use crate::test_tracing::count_drop_warnings; @@ -8239,7 +8226,7 @@ mod tests { fn an_errored_copy_serves_history_before_its_outcome() { let now = Instant::ZERO; let waiter = kio::Waiter::noop(); - let (producer, mut driver) = Producer::new(Config::new(origin(1))); + let (producer, mut driver) = Producer::new(Config::from(origin(1))); let server = producer .forward("room", RouteInfo::default().with_hops(hops(&[10])), None) .unwrap(); @@ -8330,7 +8317,7 @@ mod tests { #[kio::test] async fn default_config_mints_a_real_hop() { let config = Config::default(); - assert_ne!(config.hop, Hop::UNKNOWN); + assert!(config.hop.get() < 1 << 53, "older JS clients decode it as a number"); let (producer, _driver) = Producer::new(config.clone()); assert_eq!(producer.hop(), config.hop); assert_eq!(producer.consume().hop(), config.hop); @@ -8946,7 +8933,7 @@ mod tests { /// A mount reaches only what the handle already reaches, and mounts never nest. #[kio::test] async fn mount_never_widens_a_scope() { - let (producer, _driver) = Producer::new(Config::new(origin(1))); + let (producer, _driver) = Producer::new(Config::from(origin(1))); let project = producer.scope("", &scopes(&["p1"])).unwrap(); assert!(matches!(project.mount("p1/.svc", ".svc/p1"), Err(Error::Unauthorized))); @@ -8974,7 +8961,7 @@ mod tests { /// A mount point no pattern can spell could never be announced or authorized. #[kio::test] async fn mount_refuses_a_wildcard_mount_point() { - let (producer, _driver) = Producer::new(Config::new(origin(1))); + let (producer, _driver) = Producer::new(Config::from(origin(1))); for at in ["*", "p1/*", "p1/**", "p1/a*"] { assert!( matches!(producer.mount(at, ".svc/p1"), Err(Error::InvalidPath(_))), @@ -9394,7 +9381,7 @@ mod tests { // Restarts are delivered at once: the hold is not what this checks. let producer = Config { update_hold: Duration::ZERO, - ..Config::new(origin(1)) + ..Config::from(origin(1)) } .produce(); let consumer = producer.consume(); @@ -9449,7 +9436,7 @@ mod tests { for (old_hop, new_hop) in [(11, 10), (10, 11)] { let producer = Config { update_hold: Duration::ZERO, - ..Config::new(origin(1)) + ..Config::from(origin(1)) } .produce(); let consumer = producer.consume(); @@ -9479,7 +9466,7 @@ mod tests { fn scoped_pool() -> (Producer, impl Fn(&str, &str, u64, u64) -> Route) { let producer = Config { update_hold: Duration::ZERO, - ..Config::new(origin(1)) + ..Config::from(origin(1)) } .produce(); let claims = producer.clone(); @@ -11559,7 +11546,7 @@ mod tests { assert_eq!(announced.expect_next_active("gateway").await.source(), Source::Local); assert_eq!( announced.expect_next_active("forwarded").await.source(), - Source::Peer(origin(7)) + Source::Peer(7) ); // The mark survives narrowing the handle. @@ -11567,10 +11554,7 @@ mod tests { let _nested = scoped .forward("x", RouteInfo::default().with_via(origin(8)), None) .unwrap(); - assert_eq!( - announced.expect_next_active("room/x").await.source(), - Source::Peer(origin(8)) - ); + assert_eq!(announced.expect_next_active("room/x").await.source(), Source::Peer(8)); } /// A caller that only polls with `try_next` still gets a held update once its @@ -11623,7 +11607,7 @@ mod tests { #[test] fn a_withdrawal_wave_costs_k_log_k_steps() { for k in [64usize, 256, 1024] { - let (producer, mut driver) = Producer::new(Config::new(origin(1))); + let (producer, mut driver) = Producer::new(Config::from(origin(1))); driver .poll(Instant::ZERO + Duration::from_secs(1), &kio::Waiter::noop()) .unwrap(); @@ -11876,10 +11860,7 @@ mod tests { .with_hops(hops(&[7])) .with_via(origin(7)); let _forwarded = peer.forward("room", route.clone(), None).unwrap(); - assert_eq!( - announced.expect_next_active("room").await.source(), - Source::Peer(origin(7)) - ); + assert_eq!(announced.expect_next_active("room").await.source(), Source::Peer(7)); // The newest identical route wins, so the local twin takes over. let local = producer.forward("room", route, None).unwrap(); @@ -11889,10 +11870,7 @@ mod tests { } drop(local); - assert_eq!( - announced.expect_next_active("room").await.source(), - Source::Peer(origin(7)) - ); + assert_eq!(announced.expect_next_active("room").await.source(), Source::Peer(7)); } #[kio::test] @@ -11972,10 +11950,7 @@ mod tests { None, ) .unwrap(); - assert_eq!( - everyone.expect_next_active("core").await.source(), - Source::Peer(origin(7)) - ); + assert_eq!(everyone.expect_next_active("core").await.source(), Source::Peer(7)); toward_core.assert_next_wait(); let _mesh = peer @@ -11985,10 +11960,7 @@ mod tests { None, ) .unwrap(); - assert_eq!( - toward_core.expect_next_active("mesh").await.source(), - Source::Peer(origin(8)) - ); + assert_eq!(toward_core.expect_next_active("mesh").await.source(), Source::Peer(8)); // A path both an upstream and a mesh peer reach: the upstream route is // cheaper, yet the upstream view selects the mesh peer's. @@ -12009,10 +11981,7 @@ mod tests { None, ) .unwrap(); - assert_eq!( - toward_core.expect_next_active("both").await.source(), - Source::Peer(origin(8)) - ); + assert_eq!(toward_core.expect_next_active("both").await.source(), Source::Peer(8)); drop(mesh); toward_core.expect_next_ended("both").await; @@ -12432,7 +12401,7 @@ mod tests { #[kio::test] #[cfg(feature = "async")] async fn follow_reports_teardown_as_closed() { - let (producer, driver) = Producer::new(Config::new(origin(1))); + let (producer, driver) = Producer::new(Config::from(origin(1))); let consumer = producer.consume(); let _server = producer.forward("room", RouteInfo::default(), None).unwrap(); @@ -12666,7 +12635,7 @@ mod tests { #[kio::test] #[cfg(feature = "async")] async fn teardown_ends_everything() { - let (producer, driver) = Producer::new(Config::new(origin(1))); + let (producer, driver) = Producer::new(Config::from(origin(1))); let consumer = producer.consume(); let _announcement = producer.announce("room", RouteInfo::default()).unwrap(); let mut announced = consumer.routes(); @@ -12708,7 +12677,7 @@ mod tests { #[test] #[cfg(feature = "async")] fn teardown_owes_what_a_snapshot_held() { - let (producer, driver) = Producer::new(Config::new(origin(1))); + let (producer, driver) = Producer::new(Config::from(origin(1))); let snapshot = producer.snapshot("room"); let mut announced = producer.consume().routes(); let _alice = producer.announce("room/alice", RouteInfo::default()).unwrap(); @@ -12722,7 +12691,7 @@ mod tests { #[test] fn internal_route_requests_are_closed_on_teardown() { - let (producer, mut driver) = Producer::new(Config::new(origin(1))); + let (producer, mut driver) = Producer::new(Config::from(origin(1))); let server = producer.forward("room", RouteInfo::default(), None).unwrap(); let _pending = producer.consume().request("room/alice", None); driver.poll(Instant::now(), &kio::Waiter::noop()).unwrap(); @@ -12750,7 +12719,7 @@ mod tests { } for teardown in [false, true] { - let (producer, mut driver) = Producer::new(Config::new(origin(1))); + let (producer, mut driver) = Producer::new(Config::from(origin(1))); let server = producer.forward("room", RouteInfo::default(), None).unwrap(); let _pending = producer.consume().request("room/alice", None); driver.poll(Instant::ZERO, &kio::Waiter::noop()).unwrap(); @@ -13383,7 +13352,7 @@ mod tests { #[kio::test] #[cfg(feature = "async")] async fn driver_resolves_with_live_consumers() { - let (producer, driver) = Producer::new(Config::new(origin(1))); + let (producer, driver) = Producer::new(Config::from(origin(1))); let consumer = producer.consume(); let run = crate::time::run(driver); drop(producer); @@ -14953,7 +14922,7 @@ mod tests { /// lives, and finish once the last one is gone. #[kio::test] async fn a_published_broadcast_keeps_the_driver_running() { - let (producer, mut driver) = Producer::new(Config::new(origin(1))); + let (producer, mut driver) = Producer::new(Config::from(origin(1))); let waiter = kio::Waiter::noop(); let broadcast = producer.route("room/a", RouteOptions::hidden()).unwrap(); drop(producer); @@ -14970,7 +14939,7 @@ mod tests { #[kio::test] #[cfg(feature = "async")] async fn a_dynamic_keeps_the_driver_running() { - let (producer, driver) = Producer::new(Config::new(origin(1))); + let (producer, driver) = Producer::new(Config::from(origin(1))); let run = kio::clock::sim::spawn(crate::time::run(driver)); let consumer = producer.consume(); let server = producer.forward("room", RouteInfo::default(), None).unwrap(); @@ -14997,7 +14966,7 @@ mod tests { #[kio::test] #[cfg(feature = "async")] async fn a_retracted_reader_never_holds_the_driver() { - let (producer, driver) = Producer::new(Config::new(origin(1))); + let (producer, driver) = Producer::new(Config::from(origin(1))); let run = kio::clock::sim::spawn(crate::time::run(driver)); let consumer = producer.consume(); let broadcast = producer.route("room/alice", RouteOptions::default()).unwrap(); @@ -15025,7 +14994,7 @@ mod tests { #[kio::test] #[cfg(feature = "async")] async fn an_orphaned_front_keeps_the_copy_for_a_pending_subscriber() { - let (producer, driver) = Producer::new(Config::new(origin(1))); + let (producer, driver) = Producer::new(Config::from(origin(1))); let run = kio::clock::sim::spawn(crate::time::run(driver)); let consumer = producer.consume(); let broadcast = producer.route("room/alice", RouteOptions::default()).unwrap(); @@ -15214,10 +15183,7 @@ mod tests { #[kio::test] async fn a_discarded_front_task_unregisters_its_watch() { - let (producer, _driver) = Producer::new(Config { - hop: origin(1), - ..Default::default() - }); + let (producer, _driver) = Producer::new(Config::from(origin(1))); let consumer = producer.consume(); let _served = producer.forward("room", RouteInfo::default(), None).unwrap(); // A consumer outlives its producer by design, so the task set can refuse diff --git a/rs/moq-net/src/model/resume_model.rs b/rs/moq-net/src/model/resume_model.rs index e4a280230bc..7236e9a7f3c 100644 --- a/rs/moq-net/src/model/resume_model.rs +++ b/rs/moq-net/src/model/resume_model.rs @@ -327,7 +327,7 @@ struct Model { impl Model { fn new() -> Self { let origin = origin::Config { - hop: Hop::new(1).unwrap(), + hop: std::num::NonZeroU64::MIN, update_hold: Duration::ZERO, ..Default::default() }; diff --git a/rs/moq-net/src/model/socket.rs b/rs/moq-net/src/model/socket.rs index e910eaef005..ba96ab1004a 100644 --- a/rs/moq-net/src/model/socket.rs +++ b/rs/moq-net/src/model/socket.rs @@ -1301,7 +1301,7 @@ mod tests { let (done, finished) = std::sync::mpsc::channel(); let thread = std::thread::spawn(move || { - let (origin, _driver) = origin::Producer::new(origin::Config::new(crate::Hop::new(1).unwrap())); + let (origin, _driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(1).unwrap())); let endpoint = Endpoint::new(&origin, "room", "bob").unwrap(); let noop = kio::Waiter::noop(); // Listening, so the dial queues for the handler. @@ -1340,7 +1340,7 @@ mod tests { /// its dialer gives up, so dialing and giving up again never piles up requests. #[test] fn abandoned_dials_leave_the_queue() { - let (origin, _driver) = origin::Producer::new(origin::Config::new(crate::Hop::new(1).unwrap())); + let (origin, _driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(1).unwrap())); let endpoint = Endpoint::new(&origin, "room", "bob").unwrap(); let noop = kio::Waiter::noop(); // Accepting both protocols, then only `tcp`. diff --git a/rs/moq-net/src/server.rs b/rs/moq-net/src/server.rs index fea9d832b0a..141c75e112c 100644 --- a/rs/moq-net/src/server.rs +++ b/rs/moq-net/src/server.rs @@ -974,8 +974,8 @@ impl Handshake { /// /// Self-declared, so treat it as a correlation hint rather than an /// authenticated identity: authorize on the token or client certificate. - pub fn peer_hop(&self) -> Option { - self.origin + pub fn peer_hop(&self) -> Option { + self.origin.and_then(|hop| std::num::NonZeroU64::new(hop.id())) } /// The implementation the client advertised in its SETUP, such as `moq-net-rs/0.3.10`. @@ -1032,7 +1032,7 @@ impl Handshake { self } - /// Assign the identity this peer's routes are attributed to, overriding the fresh + /// Assign the hop id this peer's routes are attributed to, overriding the fresh /// per-session default. /// /// Only for a peer whose identity the server has actually established, such as one @@ -1044,8 +1044,8 @@ impl Handshake { /// with the other's. That is the point when they really are one peer reconnecting or /// running redundant links, and a bug otherwise. Derive it from the authenticated /// identity, never from something coarser like the remote address. - pub fn with_peer_hop(mut self, hop: crate::Hop) -> Self { - self.assigned_hop = hop; + pub fn with_peer_hop(mut self, hop: std::num::NonZeroU64) -> Self { + self.assigned_hop = crate::Hop::from(hop); self } @@ -1942,13 +1942,13 @@ mod tests { let hop = Hop::new(42).unwrap(); let session = FakeSession::new(ALPN_LITE_05, [lite05_setup(None, None, Some(hop))]); let request = Server::new().accept_request(kio::clock::now(), session).await.unwrap(); - assert_eq!(request.peer_hop(), Some(hop)); + assert_eq!(request.peer_hop(), Some(std::num::NonZeroU64::new(42).unwrap())); } #[kio::test] async fn anonymous_peer_hop_filters_routes_from_server_session() { let other = Hop::new(778).unwrap(); - let origin = crate::origin::Config::new(Hop::new(1).unwrap()).produce(); + let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let gate = kio::Producer::new(true); let transport = crate::lite::test_transport::SinkSession::gated_bi(gate.consume()); diff --git a/rs/moq-net/tests/integration/announce_covering_route.rs b/rs/moq-net/tests/integration/announce_covering_route.rs index c7337a94d88..40c9a34c183 100644 --- a/rs/moq-net/tests/integration/announce_covering_route.rs +++ b/rs/moq-net/tests/integration/announce_covering_route.rs @@ -11,7 +11,7 @@ use crate::support; use std::time::Duration; -use moq_net::{Hop, Pattern, Patterns, Version, origin}; +use moq_net::{Pattern, Patterns, Version, origin}; use support::harness::{MockConnectOptions, connect_mock}; /// Long enough, in virtual time, for anything in flight to reach the far side. @@ -21,7 +21,7 @@ const SERVED: &str = ".dash"; const REQUESTED: &str = ".dash/nobody"; fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/announce_takeover.rs b/rs/moq-net/tests/integration/announce_takeover.rs index 90cdb661d58..b9fc5e10802 100644 --- a/rs/moq-net/tests/integration/announce_takeover.rs +++ b/rs/moq-net/tests/integration/announce_takeover.rs @@ -9,13 +9,13 @@ use crate::support; use std::{cell::RefCell, rc::Rc, time::Duration}; -use moq_net::{Hop, Timestamp, Version, origin, track}; +use moq_net::{Timestamp, Version, origin, track}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; const TEST_TIMEOUT: Duration = Duration::from_secs(600); fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/announce_to_serve.rs b/rs/moq-net/tests/integration/announce_to_serve.rs index c41ca7e1160..3d4c9e7a6a5 100644 --- a/rs/moq-net/tests/integration/announce_to_serve.rs +++ b/rs/moq-net/tests/integration/announce_to_serve.rs @@ -15,7 +15,7 @@ use crate::support; use std::time::Duration; use futures::{StreamExt, channel::mpsc}; -use moq_net::{Error, Hop, Timestamp, Version, origin}; +use moq_net::{Error, Timestamp, Version, origin}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; /// A millisecond track: the frames written here carry timestamps. @@ -29,7 +29,7 @@ const SETTLE: Duration = Duration::from_secs(1); const PATH: &str = "bcast"; fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/auth.rs b/rs/moq-net/tests/integration/auth.rs index 9540a755b62..2aed7b3c6eb 100644 --- a/rs/moq-net/tests/integration/auth.rs +++ b/rs/moq-net/tests/integration/auth.rs @@ -10,7 +10,7 @@ use std::time::Duration; use futures::StreamExt; use moq_net::{ - Client, Error, Hop, Pattern, Patterns, Server, Session, SessionError, StreamError, Version, + Client, Error, Pattern, Patterns, Server, Session, SessionError, StreamError, Version, auth::{self, Grant}, origin, }; @@ -364,7 +364,7 @@ async fn a_route_auth_renews_its_announce(version: &'static str) { /// Build an origin producer, spawning its driver on the ambient runtime. fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/broadcast_close.rs b/rs/moq-net/tests/integration/broadcast_close.rs index 2f44c6ae7c0..f98e5a12988 100644 --- a/rs/moq-net/tests/integration/broadcast_close.rs +++ b/rs/moq-net/tests/integration/broadcast_close.rs @@ -9,13 +9,14 @@ use crate::support; use std::time::Duration; -use moq_net::{Error, Hop, Version}; +use moq_net::{Error, Version}; use support::harness::{MockConnectOptions, connect_mock}; const TIMEOUT: Duration = Duration::from_secs(10); fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/catalog_acquisition.rs b/rs/moq-net/tests/integration/catalog_acquisition.rs index b8285e421ef..9019acb48cc 100644 --- a/rs/moq-net/tests/integration/catalog_acquisition.rs +++ b/rs/moq-net/tests/integration/catalog_acquisition.rs @@ -4,11 +4,11 @@ use crate::support; -use moq_net::{Error, Hop, Version, origin}; +use moq_net::{Error, Version, origin}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; fn origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/catalog_churn.rs b/rs/moq-net/tests/integration/catalog_churn.rs index 2e0f918e5b1..980ff19644f 100644 --- a/rs/moq-net/tests/integration/catalog_churn.rs +++ b/rs/moq-net/tests/integration/catalog_churn.rs @@ -14,7 +14,7 @@ use crate::support; use std::time::Duration; use futures::{StreamExt, channel::mpsc}; -use moq_net::{Error, Hop, Timestamp, Version, origin, track}; +use moq_net::{Error, Timestamp, Version, origin, track}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; const SEEDS: u64 = 32; @@ -27,7 +27,7 @@ const READ_TIMEOUT: Duration = Duration::from_secs(10); const STUCK_AFTER: Duration = Duration::from_secs(120); fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/catalog_handover.rs b/rs/moq-net/tests/integration/catalog_handover.rs index 0e9fd55c34f..91df5e6ae58 100644 --- a/rs/moq-net/tests/integration/catalog_handover.rs +++ b/rs/moq-net/tests/integration/catalog_handover.rs @@ -16,7 +16,7 @@ use crate::support; use std::time::Duration; use futures::{StreamExt, channel::mpsc}; -use moq_net::{Error, Hop, Timestamp, Version, origin, track}; +use moq_net::{Error, Timestamp, Version, origin, track}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; const TEST_TIMEOUT: Duration = Duration::from_secs(300); @@ -35,7 +35,7 @@ fn timed() -> track::Info { } fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/compress.rs b/rs/moq-net/tests/integration/compress.rs index d11d343b3c7..c33ca84e0df 100644 --- a/rs/moq-net/tests/integration/compress.rs +++ b/rs/moq-net/tests/integration/compress.rs @@ -9,7 +9,7 @@ use crate::support; use std::time::Duration; -use moq_net::{Hop, Timestamp, Version}; +use moq_net::{Timestamp, Version}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; const TIMEOUT: Duration = Duration::from_secs(10); @@ -30,7 +30,8 @@ fn compressed() -> moq_net::track::Info { } fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/datagram.rs b/rs/moq-net/tests/integration/datagram.rs index 40a6c6b269f..39612e17bac 100644 --- a/rs/moq-net/tests/integration/datagram.rs +++ b/rs/moq-net/tests/integration/datagram.rs @@ -14,7 +14,7 @@ use crate::support; use std::time::Duration; -use moq_net::{Error, Hop, StreamError, Timescale, Timestamp, Version, broadcast, datagram, origin}; +use moq_net::{Error, StreamError, Timescale, Timestamp, Version, broadcast, datagram, origin}; use support::datagram_priority; use support::harness::{MockPair, peer_with_latency}; @@ -23,7 +23,7 @@ const TIMEOUT: Duration = Duration::from_secs(10); const TRACK: &str = "audio"; fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/dial_split_horizon.rs b/rs/moq-net/tests/integration/dial_split_horizon.rs index 5e5383ba3a6..ef02f794539 100644 --- a/rs/moq-net/tests/integration/dial_split_horizon.rs +++ b/rs/moq-net/tests/integration/dial_split_horizon.rs @@ -11,7 +11,8 @@ use crate::support; use std::time::Duration; -use moq_net::{Client, Hop, Server, Session, Version, origin, stats}; +use moq_net::{Client, Server, Session, Version, origin, stats}; +use std::num::NonZeroU64; use support::{ harness::{now, spawn}, mock::create_mock_session_pair, @@ -20,7 +21,7 @@ use support::{ /// Long enough, in virtual time, for an announce or subscribe to cross the mock link. const SETTLE: Duration = Duration::from_secs(1); -fn produce(hop: Hop) -> origin::Producer { +fn produce(hop: NonZeroU64) -> origin::Producer { let (producer, driver) = origin::Producer::new(origin::Config::new(hop)); spawn(driver); producer @@ -93,7 +94,7 @@ fn traffic(registry: &stats::Registry, role: stats::Role) -> stats::Traffic { } /// The hop the dialer attributed `path` to, once that announce has arrived. -async fn learned_hop(dialer: &origin::Producer, path: &str) -> Hop { +async fn learned_hop(dialer: &origin::Producer, path: &str) -> u64 { let mut announced = dialer.consume().routes(); let event = kio::clock::timeout(SETTLE, async { loop { @@ -119,8 +120,8 @@ async fn learned_hop(dialer: &origin::Producer, path: &str) -> Hop { } } -fn hop(id: u64) -> Hop { - Hop::new(id).unwrap() +fn hop(id: u64) -> NonZeroU64 { + NonZeroU64::new(id).unwrap() } /// Edges that declare their own hop over the MoQ Cluster extension. @@ -139,7 +140,7 @@ async fn dialed_anonymous_session_does_not_echo_or_route_subscribe_back() { /// announced a namespace is not told about it, and the other edge is. A /// subscribe from that other edge is fetched from the announcer and is not /// sent back to the subscriber. -async fn split_horizon(version: &str, [publisher_hop, subscriber_hop]: [Hop; 2]) { +async fn split_horizon(version: &str, [publisher_hop, subscriber_hop]: [NonZeroU64; 2]) { let version: Version = version.parse().unwrap(); let dialer = produce(hop(1)); let publisher = produce(publisher_hop); @@ -155,8 +156,7 @@ async fn split_horizon(version: &str, [publisher_hop, subscriber_hop]: [Hop; 2]) let publisher_hop = learned_hop(&dialer, "room").await; assert_ne!( - publisher_hop, - Hop::UNKNOWN, + publisher_hop, 0, "an anonymous dial still needs a hop, or its routes echo" ); @@ -176,7 +176,7 @@ async fn split_horizon(version: &str, [publisher_hop, subscriber_hop]: [Hop; 2]) origin::Source::Local => panic!("the forwarded route looks local"), }; assert_ne!(subscriber_hop, publisher_hop, "each dial gets its own hop"); - assert_ne!(subscriber_hop, Hop::UNKNOWN); + assert_ne!(subscriber_hop, 0); kio::clock::sleep(SETTLE).await; diff --git a/rs/moq-net/tests/integration/drained_claim.rs b/rs/moq-net/tests/integration/drained_claim.rs index f87c986ebef..226aefd0a41 100644 --- a/rs/moq-net/tests/integration/drained_claim.rs +++ b/rs/moq-net/tests/integration/drained_claim.rs @@ -13,7 +13,7 @@ use crate::support; use std::{cell::RefCell, rc::Rc, time::Duration}; -use moq_net::{Hop, Timestamp, Version, goaway::Goaway, origin, track}; +use moq_net::{Timestamp, Version, goaway::Goaway, origin, track}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; /// A millisecond track: the frames written here carry timestamps. @@ -24,7 +24,7 @@ fn timed() -> moq_net::track::Info { const TEST_TIMEOUT: Duration = Duration::from_secs(600); fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/empty_group.rs b/rs/moq-net/tests/integration/empty_group.rs index 264bf9db448..0809356144d 100644 --- a/rs/moq-net/tests/integration/empty_group.rs +++ b/rs/moq-net/tests/integration/empty_group.rs @@ -6,7 +6,7 @@ use crate::support; use std::time::Duration; -use moq_net::{Hop, Timestamp, Version, origin}; +use moq_net::{Timestamp, Version, origin}; use support::harness::{peer, subscribed}; /// A millisecond track: the frames written here carry timestamps. @@ -19,7 +19,7 @@ const TIMEOUT: Duration = Duration::from_secs(10); const VERSIONS: &[&str] = &["moq-lite-06", "moq-transport-18", "moq-transport-22"]; fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/errored_end.rs b/rs/moq-net/tests/integration/errored_end.rs index f7adc0ae44b..6954413ec10 100644 --- a/rs/moq-net/tests/integration/errored_end.rs +++ b/rs/moq-net/tests/integration/errored_end.rs @@ -10,7 +10,7 @@ use moq_net::track::Delay; use std::time::Duration; use moq_net::track::{Position, Subscription}; -use moq_net::{Error, Hop, StreamError, Timestamp, Version}; +use moq_net::{Error, StreamError, Timestamp, Version}; use support::harness::{MockConnectOptions, connect_mock}; const TIMEOUT: Duration = Duration::from_secs(10); @@ -18,7 +18,8 @@ const GROUPS: u64 = 2; const FRAMES: [&[u8]; 2] = [b"first", b"second"]; fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/extensions.rs b/rs/moq-net/tests/integration/extensions.rs index 24d693f5d2f..937143e1102 100644 --- a/rs/moq-net/tests/integration/extensions.rs +++ b/rs/moq-net/tests/integration/extensions.rs @@ -9,7 +9,7 @@ use crate::support; use std::time::Duration; -use moq_net::{Hop, Version, origin, setup::Extensions}; +use moq_net::{Version, origin, setup::Extensions}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; /// Long enough, in virtual time, for anything in flight to reach the far side. @@ -22,7 +22,7 @@ const MOQT: [&str; 2] = ["moq-transport-18", "moq-transport-22"]; const AUTH: [&str; 2] = ["moq-transport-18", "moq-transport-22"]; fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/fastest_reader.rs b/rs/moq-net/tests/integration/fastest_reader.rs index 297638f8af6..249fdf2544b 100644 --- a/rs/moq-net/tests/integration/fastest_reader.rs +++ b/rs/moq-net/tests/integration/fastest_reader.rs @@ -8,7 +8,7 @@ use std::time::Duration; use bytes::Bytes; -use moq_net::{Hop, Timestamp, Version, origin, track, transport::ReceiveWindow}; +use moq_net::{Timestamp, Version, origin, track, transport::ReceiveWindow}; use crate::support::harness::{MockPair, peer, spawn}; @@ -24,7 +24,7 @@ fn uncapped() -> ReceiveWindow { } fn origin(hop: u64) -> origin::Producer { - let (origin, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (origin, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); spawn(driver); origin } diff --git a/rs/moq-net/tests/integration/fetch_cancel.rs b/rs/moq-net/tests/integration/fetch_cancel.rs index 3f444eb3f7f..7e52db166da 100644 --- a/rs/moq-net/tests/integration/fetch_cancel.rs +++ b/rs/moq-net/tests/integration/fetch_cancel.rs @@ -12,7 +12,7 @@ use crate::support; use std::time::Duration; use bytes::Bytes; -use moq_net::{Hop, Timestamp, Version, origin}; +use moq_net::{Timestamp, Version, origin}; use support::harness::peer; /// A millisecond track: the frames written here carry timestamps. @@ -21,7 +21,7 @@ fn timed() -> moq_net::track::Info { } fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/fetch_fanout.rs b/rs/moq-net/tests/integration/fetch_fanout.rs index 0caa3224edc..8dfeebaf340 100644 --- a/rs/moq-net/tests/integration/fetch_fanout.rs +++ b/rs/moq-net/tests/integration/fetch_fanout.rs @@ -4,12 +4,12 @@ //! viewers ask for it, and keeps serving the cached copy after a reader leaves. use crate::support; -use moq_net::{Hop, Version, origin, track}; +use moq_net::{Version, origin, track}; use std::time::Duration; use support::harness::{MockConnectOptions, connect_mock}; fn origin(hop: u64) -> origin::Producer { - let (origin, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (origin, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); origin } diff --git a/rs/moq-net/tests/integration/fetch_from_feed.rs b/rs/moq-net/tests/integration/fetch_from_feed.rs index d0ceba8d40f..e07fa0b2fe9 100644 --- a/rs/moq-net/tests/integration/fetch_from_feed.rs +++ b/rs/moq-net/tests/integration/fetch_from_feed.rs @@ -8,7 +8,7 @@ use crate::support; use std::time::Duration; -use moq_net::{Hop, Version}; +use moq_net::Version; use support::harness::{MockConnectOptions, connect_mock}; const TIMEOUT: Duration = Duration::from_secs(5); @@ -16,7 +16,8 @@ const TIMEOUT: Duration = Duration::from_secs(5); const VERSIONS: &[&str] = &["moq-lite-01", "moq-lite-02", "moq-lite-03", "moq-lite-04"]; fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/fetch_only.rs b/rs/moq-net/tests/integration/fetch_only.rs index 0b6a0e9933b..82abda3e4d2 100644 --- a/rs/moq-net/tests/integration/fetch_only.rs +++ b/rs/moq-net/tests/integration/fetch_only.rs @@ -12,7 +12,7 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; -use moq_net::{Hop, Timestamp, Version}; +use moq_net::{Timestamp, Version}; use support::harness::{MockConnectOptions, connect_mock}; /// A millisecond track with no publisher max age: the frames written here carry timestamps, @@ -26,7 +26,8 @@ fn timed() -> moq_net::track::Info { const TIMEOUT: Duration = Duration::from_secs(5); fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/fetch_pipeline.rs b/rs/moq-net/tests/integration/fetch_pipeline.rs index 75c681a6961..f4c70ad28e5 100644 --- a/rs/moq-net/tests/integration/fetch_pipeline.rs +++ b/rs/moq-net/tests/integration/fetch_pipeline.rs @@ -9,7 +9,7 @@ use crate::support; use std::time::Duration; -use moq_net::{Error, Hop, Timestamp, Version}; +use moq_net::{Error, Timestamp, Version}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; const TIMEOUT: Duration = Duration::from_secs(5); @@ -21,7 +21,8 @@ fn timed() -> moq_net::track::Info { } fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/finished_broadcast_mock.rs b/rs/moq-net/tests/integration/finished_broadcast_mock.rs index 931e2fa6c08..e5b8f5c0483 100644 --- a/rs/moq-net/tests/integration/finished_broadcast_mock.rs +++ b/rs/moq-net/tests/integration/finished_broadcast_mock.rs @@ -18,7 +18,7 @@ use crate::support; use std::time::Duration; -use moq_net::{Hop, Timestamp, Version}; +use moq_net::{Timestamp, Version}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; /// A millisecond track: the frames written here carry timestamps. @@ -30,7 +30,8 @@ const TIMEOUT: Duration = Duration::from_secs(10); const PAYLOAD: &[u8] = b"frame"; fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/finite_relay.rs b/rs/moq-net/tests/integration/finite_relay.rs index 25ccfd72434..efc76a9c313 100644 --- a/rs/moq-net/tests/integration/finite_relay.rs +++ b/rs/moq-net/tests/integration/finite_relay.rs @@ -17,7 +17,7 @@ use futures::channel::mpsc::TryRecvError; use futures::{SinkExt, StreamExt}; use moq_net::track::Subscription; -use moq_net::{Hop, Timestamp, Version}; +use moq_net::{Timestamp, Version}; use support::harness::{MockConnectOptions, connect_mock}; /// A millisecond track with no publisher max age: the frames written here carry timestamps, @@ -42,7 +42,8 @@ const VERSIONS: &[&str] = &[ ]; fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/flights.rs b/rs/moq-net/tests/integration/flights.rs index 846be1ee3a8..879907485ef 100644 --- a/rs/moq-net/tests/integration/flights.rs +++ b/rs/moq-net/tests/integration/flights.rs @@ -13,7 +13,7 @@ use std::task::Poll; use std::time::Duration; use bytes::Bytes; -use moq_net::{Hop, Version, cache, frame, group, origin, track}; +use moq_net::{Version, cache, frame, group, origin, track}; use crate::support::harness::{MockConnectOptions, connect_mock, spawn}; @@ -41,7 +41,7 @@ fn info(payload: &Bytes) -> frame::Info { } fn origin(hop: u64, pool: &cache::Pool) -> origin::Producer { - let mut config = origin::Config::new(Hop::new(hop).unwrap()); + let mut config = origin::Config::new(std::num::NonZeroU64::new(hop).unwrap()); config.pool = pool.clone(); let (origin, driver) = origin::Producer::new(config); spawn(driver); diff --git a/rs/moq-net/tests/integration/goaway.rs b/rs/moq-net/tests/integration/goaway.rs index a56fa1487bc..5ddaa428c03 100644 --- a/rs/moq-net/tests/integration/goaway.rs +++ b/rs/moq-net/tests/integration/goaway.rs @@ -10,7 +10,7 @@ use crate::support; use std::time::Duration; -use moq_net::{Hop, Version, goaway::Goaway}; +use moq_net::{Version, goaway::Goaway}; use support::Draining; use support::harness::{MockConnectOptions, MockPair, connect_mock}; use support::mock::create_mock_session_pair; @@ -21,8 +21,8 @@ fn timed() -> moq_net::track::Info { } /// Build an origin producer, spawning its driver on the ambient runtime. -fn produce_origin(hop: Hop) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(hop)); +fn produce_origin() -> moq_net::origin::Producer { + let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::default()); support::harness::spawn(driver); producer } @@ -368,7 +368,7 @@ async fn duplicate_goaway_keeps_first_payload_moq_lite_04() { async fn goaway_keeps_new_subscribes(version: Version) { kio::clock::timeout(TEST_TIMEOUT, async { // Server publishes a broadcast with one live track. - let pub_origin = produce_origin(Hop::random()); + let pub_origin = produce_origin(); let broadcast = pub_origin .route("test", moq_net::origin::RouteOptions::hidden()) .expect("create broadcast"); @@ -389,7 +389,7 @@ async fn goaway_keeps_new_subscribes(version: Version) { audio_group.finish().expect("finish group"); // Client consumes into its own origin. - let sub_origin = produce_origin(Hop::random()); + let sub_origin = produce_origin(); let mut opts = MockConnectOptions::new(version); opts.server_publish = Some(pub_origin.consume()); @@ -491,13 +491,13 @@ async fn goaway_keeps_new_subscribes_moq_transport_22() { /// draining peer has no reason to send. async fn goaway_drains_routes(version: Version) { kio::clock::timeout(TEST_TIMEOUT, async { - let pub_origin = produce_origin(Hop::random()); + let pub_origin = produce_origin(); let broadcast = pub_origin .route("test", moq_net::origin::RouteOptions::hidden()) .expect("create broadcast"); broadcast.announce().expect("announce"); - let sub_origin = produce_origin(Hop::random()); + let sub_origin = produce_origin(); let mut opts = MockConnectOptions::new(version); opts.server_publish = Some(pub_origin.consume()); diff --git a/rs/moq-net/tests/integration/group_order.rs b/rs/moq-net/tests/integration/group_order.rs index 370a0a58ba4..6771c2d77e4 100644 --- a/rs/moq-net/tests/integration/group_order.rs +++ b/rs/moq-net/tests/integration/group_order.rs @@ -13,7 +13,7 @@ use moq_net::track::Delay; use std::time::Duration; use moq_net::track::{Info, Order, Subscription}; -use moq_net::{Hop, Timescale, Timestamp, Version}; +use moq_net::{Timescale, Timestamp, Version}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; const TIMEOUT: Duration = Duration::from_secs(10); @@ -25,7 +25,8 @@ const FOREVER: Duration = Duration::from_millis((1 << 53) - 1); const BACKLOG: [u64; 4] = [0, 1, 2, 3]; fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/history_groups.rs b/rs/moq-net/tests/integration/history_groups.rs index 21c357a9353..816f6d4e8b0 100644 --- a/rs/moq-net/tests/integration/history_groups.rs +++ b/rs/moq-net/tests/integration/history_groups.rs @@ -14,7 +14,7 @@ use moq_net::track::Delay; use std::time::Duration; use moq_net::track::{Info, Subscription}; -use moq_net::{Hop, Timescale, Timestamp, Version}; +use moq_net::{Timescale, Timestamp, Version}; use support::harness::{MockConnectOptions, connect_mock}; const TIMEOUT: Duration = Duration::from_secs(10); @@ -31,7 +31,8 @@ const VERSIONS: &[&str] = &[ ]; fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/idle_cancel_refetch.rs b/rs/moq-net/tests/integration/idle_cancel_refetch.rs index a2cb27ea80b..5425cee0e5d 100644 --- a/rs/moq-net/tests/integration/idle_cancel_refetch.rs +++ b/rs/moq-net/tests/integration/idle_cancel_refetch.rs @@ -7,13 +7,14 @@ use crate::support; use std::time::Duration; -use moq_net::{Hop, Version}; +use moq_net::Version; use support::harness::{MockConnectOptions, connect_mock}; const TIMEOUT: Duration = Duration::from_secs(5); fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/idle_session.rs b/rs/moq-net/tests/integration/idle_session.rs index 4f1547f7c7a..701746fcd2b 100644 --- a/rs/moq-net/tests/integration/idle_session.rs +++ b/rs/moq-net/tests/integration/idle_session.rs @@ -14,7 +14,7 @@ use std::{ time::Duration, }; -use moq_net::{Hop, Version, bandwidth::Rate, origin}; +use moq_net::{Version, bandwidth::Rate, origin}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; use support::mock::MockStats; @@ -41,7 +41,7 @@ async fn viewer( options.server_publish = Some(origin.consume()); // Driven, so its readers' interests reach the session and the viewer asks for what // the server publishes. - let (subscribe, driver) = origin::Producer::new(origin::Config::new(Hop::new(2).unwrap())); + let (subscribe, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(2).unwrap())); support::harness::spawn(driver); options.client_subscribe = Some(subscribe); options.stats = STATS; @@ -55,7 +55,7 @@ async fn viewer( } fn origin() -> origin::Producer { - let (origin, driver) = origin::Producer::new(origin::Config::new(Hop::new(1).unwrap())); + let (origin, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(1).unwrap())); support::harness::spawn(driver); origin } diff --git a/rs/moq-net/tests/integration/instance.rs b/rs/moq-net/tests/integration/instance.rs index f48942da2c6..fb091f6cfa1 100644 --- a/rs/moq-net/tests/integration/instance.rs +++ b/rs/moq-net/tests/integration/instance.rs @@ -7,11 +7,11 @@ use crate::support; use std::time::Duration; -use moq_net::{Hop, Instance, Version, origin}; +use moq_net::{Instance, Version, origin}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/late_lower_group.rs b/rs/moq-net/tests/integration/late_lower_group.rs index b5882acac76..c78b779c143 100644 --- a/rs/moq-net/tests/integration/late_lower_group.rs +++ b/rs/moq-net/tests/integration/late_lower_group.rs @@ -38,7 +38,7 @@ fn floored(start: Option) -> Range { fn produce_origin(hop: u64) -> moq_net::origin::Producer { let (producer, driver) = - moq_net::origin::Producer::new(moq_net::origin::Config::new(moq_net::Hop::new(hop).unwrap())); + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/lazy_discovery.rs b/rs/moq-net/tests/integration/lazy_discovery.rs index 19cfee840d4..81022bdbd7e 100644 --- a/rs/moq-net/tests/integration/lazy_discovery.rs +++ b/rs/moq-net/tests/integration/lazy_discovery.rs @@ -6,7 +6,7 @@ use std::time::Duration; -use moq_net::{Error, Hop, Pattern, Patterns, Version, origin}; +use moq_net::{Error, Pattern, Patterns, Version, origin}; use crate::support; use support::harness::{MockConnectOptions, MockPair, connect_mock}; @@ -24,7 +24,7 @@ const LINGERED: Duration = Duration::from_secs(3); const ANNOUNCE: u8 = 1; fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/mesh_withdraw.rs b/rs/moq-net/tests/integration/mesh_withdraw.rs index 6151abcd41c..d6593d92333 100644 --- a/rs/moq-net/tests/integration/mesh_withdraw.rs +++ b/rs/moq-net/tests/integration/mesh_withdraw.rs @@ -13,7 +13,7 @@ use std::time::Duration; use futures::channel::mpsc; -use moq_net::{Hop, Version, cache, origin}; +use moq_net::{Version, cache, origin}; use support::harness::{MockConnectOptions, MockPair, connect_mock, peer, peer_with_latency}; use support::{Kind, drain, watch}; @@ -25,7 +25,7 @@ fn produce_origin(hop: u64) -> origin::Producer { /// groups: nothing here carries media, and the expiry sweep would keep a timer /// armed forever, so [`kio::clock::sim::idle`] could never see the mesh settle. fn produce(hop: u64, hold: Duration) -> origin::Producer { - let mut config = origin::Config::new(Hop::new(hop).unwrap()); + let mut config = origin::Config::new(std::num::NonZeroU64::new(hop).unwrap()); config.pool = cache::Pool::unbounded(); config.update_hold = hold; let (producer, driver) = origin::Producer::new(config); @@ -288,7 +288,7 @@ impl Cluster { let relays: Vec<_> = (1..=n as u64) .map(|id| { let mut config = config.clone(); - config.hop = Hop::new(id).unwrap(); + config.hop = std::num::NonZeroU64::new(id).unwrap(); let (origin, driver) = origin::Producer::new(config); support::harness::spawn(driver); origin @@ -536,7 +536,7 @@ async fn residual_late_better_path_restarts_on_lite06() { async fn assert_capped_withdrawal(edges: &[Link], publisher: usize, watcher: usize) { let mut config = origin::Config::default(); - config.max_hops = origin::HopLimit::new(diameter(edges) + 2).unwrap(); + config.max_hops = std::num::NonZeroUsize::new(diameter(edges) + 2).unwrap(); let mut cluster = Cluster::new("moq-lite-07-wip", edges, config, publisher, watcher).await; let (broadcast, _) = cluster.publish("room/a").await; let (client, relays) = cluster.close("room/a", broadcast).await; @@ -639,7 +639,7 @@ async fn withdrawal_counts(capped: bool) -> (usize, usize, usize) { let (edges, publisher) = random_mesh(seed); let mut config = origin::Config::default(); if capped { - config.max_hops = origin::HopLimit::new(diameter(&edges) + 2).unwrap(); + config.max_hops = std::num::NonZeroUsize::new(diameter(&edges) + 2).unwrap(); } let mut cluster = Cluster::new("moq-lite-07-wip", &edges, config, publisher, 0).await; let (broadcast, _) = cluster.publish("room/a").await; diff --git a/rs/moq-net/tests/integration/model.rs b/rs/moq-net/tests/integration/model.rs index 8c9b1786158..744f47f3f56 100644 --- a/rs/moq-net/tests/integration/model.rs +++ b/rs/moq-net/tests/integration/model.rs @@ -1,6 +1,6 @@ //! The explicit-time model works without async helpers or a runtime. -use moq_net::{Error, Hop, Timestamp, broadcast, frame, group, kio, origin, track}; +use moq_net::{Error, Timestamp, broadcast, frame, group, kio, origin, track}; use std::task::Poll; fn ready(value: Poll) -> T { @@ -14,7 +14,7 @@ fn ready(value: Poll) -> T { fn origin_front_serves_media_with_only_explicit_polls() { let now = moq_net::time::Instant::now(); let waiter = kio::Waiter::noop(); - let (origin, mut driver) = origin::Producer::new(origin::Config::new(Hop::new(1).unwrap())); + let (origin, mut driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(1).unwrap())); driver.poll(now, &waiter).unwrap(); let broadcast = origin .route("room/live", moq_net::origin::RouteOptions::hidden()) @@ -57,7 +57,7 @@ fn origin_front_serves_media_with_only_explicit_polls() { fn follow_resolves_with_only_explicit_polls() { let now = moq_net::time::Instant::now(); let waiter = kio::Waiter::noop(); - let (origin, mut driver) = origin::Producer::new(origin::Config::new(Hop::new(1).unwrap())); + let (origin, mut driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(1).unwrap())); driver.poll(now, &waiter).unwrap(); // Nothing covers the path yet: the follower waits for an announcement. diff --git a/rs/moq-net/tests/integration/multi_cdn.rs b/rs/moq-net/tests/integration/multi_cdn.rs index 7b659d373a3..0605a68b4c3 100644 --- a/rs/moq-net/tests/integration/multi_cdn.rs +++ b/rs/moq-net/tests/integration/multi_cdn.rs @@ -15,7 +15,7 @@ use crate::support; use std::time::Duration; use futures::{StreamExt, channel::mpsc}; -use moq_net::{Error, Hop, Timestamp, Version, origin, track}; +use moq_net::{Error, Timestamp, Version, origin, track}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; /// A millisecond track: the frames written here carry timestamps. @@ -32,7 +32,7 @@ const FRAMES: u64 = 4; const A: u64 = 2; fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } @@ -135,7 +135,7 @@ fn via_a(announce: &origin::RouteEvent) -> bool { | origin::RouteEvent::Takeover { announce: a, .. } => &a.route, origin::RouteEvent::End(_) => return false, }; - route.hops().iter().any(|hop| *hop == Hop::new(A).unwrap()) + route.hops().any(|hop| hop == A) } struct Topology { diff --git a/rs/moq-net/tests/integration/partial_group.rs b/rs/moq-net/tests/integration/partial_group.rs index 5dbc2ea8a3c..1f908a659c9 100644 --- a/rs/moq-net/tests/integration/partial_group.rs +++ b/rs/moq-net/tests/integration/partial_group.rs @@ -10,7 +10,7 @@ use moq_net::track::Delay; use std::time::Duration; use moq_net::track::{Info, Subscription}; -use moq_net::{Hop, Timescale, Timestamp, Version}; +use moq_net::{Timescale, Timestamp, Version}; use support::harness::{peer, subscribed}; const TIMEOUT: Duration = Duration::from_secs(10); @@ -21,7 +21,8 @@ const BUDGET: Duration = Duration::from_millis(500); const VERSIONS: &[&str] = &["moq-lite-06", "moq-lite-07-wip", "moq-transport-18", "moq-transport-22"]; fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/quiet_catalog.rs b/rs/moq-net/tests/integration/quiet_catalog.rs index e43b4def645..cc13fbebb2f 100644 --- a/rs/moq-net/tests/integration/quiet_catalog.rs +++ b/rs/moq-net/tests/integration/quiet_catalog.rs @@ -9,7 +9,7 @@ use crate::support; use std::{future::Future, time::Duration}; -use moq_net::{Error, Hop, Timestamp, Version, broadcast, origin, track}; +use moq_net::{Error, Timestamp, Version, broadcast, origin, track}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; /// A millisecond track: the frames written here carry timestamps. @@ -25,7 +25,7 @@ const VERSIONS: &[&str] = &["moq-lite-06", "moq-lite-07-wip", "moq-transport-22" const LITE: &[&str] = &["moq-lite-06", "moq-lite-07-wip"]; fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/range_anchors.rs b/rs/moq-net/tests/integration/range_anchors.rs index 99e7d98fd60..55b375988bf 100644 --- a/rs/moq-net/tests/integration/range_anchors.rs +++ b/rs/moq-net/tests/integration/range_anchors.rs @@ -12,7 +12,7 @@ use moq_net::track::Delay; use std::time::Duration; use moq_net::track::{Anchor, Info, Order, Range, Subscription}; -use moq_net::{Error, Hop, Timescale, Timestamp, Version}; +use moq_net::{Error, Timescale, Timestamp, Version}; use support::harness::peer; const TIMEOUT: Duration = Duration::from_secs(10); @@ -31,7 +31,8 @@ const VERSIONS: &[&str] = &[ ]; fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/range_fill.rs b/rs/moq-net/tests/integration/range_fill.rs index 340077a9619..3a035fcbb3d 100644 --- a/rs/moq-net/tests/integration/range_fill.rs +++ b/rs/moq-net/tests/integration/range_fill.rs @@ -10,7 +10,7 @@ use std::collections::BTreeSet; use std::time::Duration; use moq_net::track::{Delay, Info, Range, Subscription}; -use moq_net::{Hop, Timescale, Timestamp, Version, cache, kio}; +use moq_net::{Timescale, Timestamp, Version, cache, kio}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; const TIMEOUT: Duration = Duration::from_secs(10); @@ -20,7 +20,7 @@ const SUBSCRIBE: u8 = 2; const FETCH: u8 = 3; fn origin(hop: u64, pool: Option) -> moq_net::origin::Producer { - let mut config = moq_net::origin::Config::new(Hop::new(hop).unwrap()); + let mut config = moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap()); if let Some(pool) = pool { config.pool = pool; } diff --git a/rs/moq-net/tests/integration/range_read.rs b/rs/moq-net/tests/integration/range_read.rs index c07fe4bbaeb..21e09b5e680 100644 --- a/rs/moq-net/tests/integration/range_read.rs +++ b/rs/moq-net/tests/integration/range_read.rs @@ -9,13 +9,14 @@ use crate::support; use std::time::Duration; use moq_net::track::{Delay, Order, Subscription}; -use moq_net::{Hop, Timestamp, Version}; +use moq_net::{Timestamp, Version}; use support::harness::{MockConnectOptions, connect_mock}; const TIMEOUT: Duration = Duration::from_secs(5); fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/received_rewind.rs b/rs/moq-net/tests/integration/received_rewind.rs index 7866e2a18da..8dc91f60caa 100644 --- a/rs/moq-net/tests/integration/received_rewind.rs +++ b/rs/moq-net/tests/integration/received_rewind.rs @@ -31,7 +31,7 @@ const BUDGET: Duration = Duration::from_secs(60); fn produce_origin(hop: u64) -> moq_net::origin::Producer { let (producer, driver) = - moq_net::origin::Producer::new(moq_net::origin::Config::new(moq_net::Hop::new(hop).unwrap())); + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/rejoin.rs b/rs/moq-net/tests/integration/rejoin.rs index 7e84ee6b8dd..4f9954de887 100644 --- a/rs/moq-net/tests/integration/rejoin.rs +++ b/rs/moq-net/tests/integration/rejoin.rs @@ -6,7 +6,7 @@ use crate::support; use std::time::Duration; -use moq_net::{Hop, Timestamp, Version, group, origin, track}; +use moq_net::{Timestamp, Version, group, origin, track}; use support::harness::{MockConnectOptions, connect_mock}; /// A millisecond track with no publisher max age: the frames written here carry timestamps, @@ -22,7 +22,8 @@ const TEST_TIMEOUT: Duration = Duration::from_secs(10); /// Build an origin producer, spawning its driver on the ambient runtime. fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/relay_upstream_close.rs b/rs/moq-net/tests/integration/relay_upstream_close.rs index f2d903dc1a3..93e8e1e7d3f 100644 --- a/rs/moq-net/tests/integration/relay_upstream_close.rs +++ b/rs/moq-net/tests/integration/relay_upstream_close.rs @@ -19,7 +19,7 @@ use moq_net::track::Delay; use std::time::Duration; use moq_net::track::Subscription; -use moq_net::{Error, Hop, Timestamp, Version}; +use moq_net::{Error, Timestamp, Version}; use support::harness::{MockConnectOptions, connect_mock}; /// A millisecond track with no publisher max age: the frames written here carry timestamps, @@ -49,7 +49,8 @@ const VERSIONS: &[&str] = &[ ]; fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/replacement.rs b/rs/moq-net/tests/integration/replacement.rs index 23e13a99918..08aa479860b 100644 --- a/rs/moq-net/tests/integration/replacement.rs +++ b/rs/moq-net/tests/integration/replacement.rs @@ -14,7 +14,7 @@ use crate::support; use std::time::Duration; -use moq_net::{Error, Hop, Instance, Timestamp, Version, broadcast, origin, track}; +use moq_net::{Error, Instance, Timestamp, Version, broadcast, origin, track}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; /// A millisecond track: the frames written here carry timestamps. @@ -25,7 +25,7 @@ fn timed() -> moq_net::track::Info { const TEST_TIMEOUT: Duration = Duration::from_secs(60); fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/request_caps.rs b/rs/moq-net/tests/integration/request_caps.rs index 6e3928fc3fa..95c524ff29c 100644 --- a/rs/moq-net/tests/integration/request_caps.rs +++ b/rs/moq-net/tests/integration/request_caps.rs @@ -9,7 +9,7 @@ use crate::support; use std::time::Duration; -use moq_net::{Hop, Version, session::Limits}; +use moq_net::{Version, session::Limits}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; const TIMEOUT: Duration = Duration::from_secs(10); @@ -18,7 +18,8 @@ const TIMEOUT: Duration = Duration::from_secs(10); const VERSIONS: [&str; 2] = ["moq-transport-18", "moq-lite-06"]; fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/route_change.rs b/rs/moq-net/tests/integration/route_change.rs index ee1e11420e4..07816d42f30 100644 --- a/rs/moq-net/tests/integration/route_change.rs +++ b/rs/moq-net/tests/integration/route_change.rs @@ -22,7 +22,7 @@ use std::collections::BTreeMap; use std::time::Duration; use futures::{StreamExt, channel::mpsc}; -use moq_net::{Error, Hop, Timestamp, Version, origin, track}; +use moq_net::{Error, Timestamp, Version, origin, track}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; /// A millisecond track with no publisher max age: the frames written here carry timestamps, @@ -39,7 +39,7 @@ const TEST_TIMEOUT: Duration = Duration::from_secs(30); const FRAMES: u64 = 4; pub(super) fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/segmented_frame.rs b/rs/moq-net/tests/integration/segmented_frame.rs index fc8d33bbf54..c40d0e70128 100644 --- a/rs/moq-net/tests/integration/segmented_frame.rs +++ b/rs/moq-net/tests/integration/segmented_frame.rs @@ -6,7 +6,7 @@ use std::time::Duration; use bytes::Bytes; -use moq_net::{Hop, Timestamp, Version, frame, origin, track}; +use moq_net::{Timestamp, Version, frame, origin, track}; use crate::support::harness::{MockConnectOptions, connect_mock, spawn, subscribed}; @@ -18,7 +18,7 @@ const VERSIONS: &[&str] = &["moq-lite-06", "moq-lite-07-wip", "moq-transport-22" const SIZE: usize = 5 * 1024 * 1024 / 2; fn origin(hop: u64) -> origin::Producer { - let (origin, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (origin, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); spawn(driver); origin } diff --git a/rs/moq-net/tests/integration/session_close.rs b/rs/moq-net/tests/integration/session_close.rs index d65d5206a72..d2c85b6d3ca 100644 --- a/rs/moq-net/tests/integration/session_close.rs +++ b/rs/moq-net/tests/integration/session_close.rs @@ -9,7 +9,7 @@ use crate::support; use std::time::Duration; -use moq_net::{Error, Hop, Timestamp, Version}; +use moq_net::{Error, Timestamp, Version}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; /// A millisecond track: the frames written here carry timestamps. @@ -20,7 +20,8 @@ fn timed() -> moq_net::track::Info { const TIMEOUT: Duration = Duration::from_secs(10); fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/session_idle.rs b/rs/moq-net/tests/integration/session_idle.rs index 83fc89bb478..0888e3fc115 100644 --- a/rs/moq-net/tests/integration/session_idle.rs +++ b/rs/moq-net/tests/integration/session_idle.rs @@ -9,7 +9,7 @@ use crate::support; use std::time::Duration; -use moq_net::{Hop, Timestamp, Version, kio}; +use moq_net::{Timestamp, Version, kio}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; /// A millisecond track: the frames written here carry timestamps. @@ -20,7 +20,8 @@ fn timed() -> moq_net::track::Info { const TIMEOUT: Duration = Duration::from_secs(10); fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/session_panic.rs b/rs/moq-net/tests/integration/session_panic.rs index 08799c1b57e..cf9e40cb086 100644 --- a/rs/moq-net/tests/integration/session_panic.rs +++ b/rs/moq-net/tests/integration/session_panic.rs @@ -13,14 +13,14 @@ use crate::support; use std::time::Duration; -use moq_net::{Client, Hop, Server, Session, Version, origin}; +use moq_net::{Client, Server, Session, Version, origin}; use support::harness::{now, spawn}; use support::mock::{MockSession, create_mock_session_pair}; const TIMEOUT: Duration = Duration::from_secs(10); fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/settled_end_survives_abort.rs b/rs/moq-net/tests/integration/settled_end_survives_abort.rs index 6af9a412c46..28e1ebf1c41 100644 --- a/rs/moq-net/tests/integration/settled_end_survives_abort.rs +++ b/rs/moq-net/tests/integration/settled_end_survives_abort.rs @@ -7,7 +7,7 @@ use crate::support; -use moq_net::{Error, Hop, Timestamp}; +use moq_net::{Error, Timestamp}; /// A millisecond track with no publisher max age: the frames written here carry timestamps, /// and superseded groups stay readable. @@ -18,7 +18,8 @@ fn timed() -> moq_net::track::Info { } fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/slow_joiner.rs b/rs/moq-net/tests/integration/slow_joiner.rs index 39d068a918d..684702222c1 100644 --- a/rs/moq-net/tests/integration/slow_joiner.rs +++ b/rs/moq-net/tests/integration/slow_joiner.rs @@ -6,7 +6,7 @@ use std::collections::BTreeSet; use std::time::Duration; -use moq_net::{Hop, Timescale, Timestamp, Version, kio, origin, track}; +use moq_net::{Timescale, Timestamp, Version, kio, origin, track}; use crate::support::harness::{MockConnectOptions, connect_mock, spawn, subscribed}; @@ -19,7 +19,7 @@ const VERSIONS: [&str; 3] = ["moq-lite-06", "moq-lite-07-wip", "moq-transport-22 const GROUPS: u64 = 5; fn origin(hop: u64) -> origin::Producer { - let (origin, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (origin, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); spawn(driver); origin } diff --git a/rs/moq-net/tests/integration/socket.rs b/rs/moq-net/tests/integration/socket.rs index 03b6a92d353..82a8d4320a0 100644 --- a/rs/moq-net/tests/integration/socket.rs +++ b/rs/moq-net/tests/integration/socket.rs @@ -11,7 +11,7 @@ use std::time::Duration; use bytes::Bytes; use moq_net::broadcast::TracksEvent; use moq_net::socket::{Endpoint, TcpStream, TrackStream}; -use moq_net::{Error, Hop, Version, frame, group, origin, track}; +use moq_net::{Error, Version, frame, group, origin, track}; use crate::support::harness::{MockConnectOptions, MockPair, connect_mock, spawn}; @@ -24,7 +24,7 @@ const LITE: &str = "moq-lite-07-wip"; const IETF: &str = "moq-transport-18"; fn origin(hop: u64) -> origin::Producer { - let (origin, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (origin, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); spawn(driver); origin } diff --git a/rs/moq-net/tests/integration/source_errors.rs b/rs/moq-net/tests/integration/source_errors.rs index 426cdf5a2c3..d2bfdceb2f3 100644 --- a/rs/moq-net/tests/integration/source_errors.rs +++ b/rs/moq-net/tests/integration/source_errors.rs @@ -10,7 +10,7 @@ use crate::support; use std::time::Duration; -use moq_net::{Error, Hop, StreamError, Timestamp, Version}; +use moq_net::{Error, StreamError, Timestamp, Version}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; const VERSIONS: [&str; 3] = ["moq-lite-05", "moq-lite-06", "moq-lite-07-wip"]; @@ -22,7 +22,8 @@ fn timed() -> moq_net::track::Info { } fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/stream_credit.rs b/rs/moq-net/tests/integration/stream_credit.rs index 82e83f2d486..c175f374cc7 100644 --- a/rs/moq-net/tests/integration/stream_credit.rs +++ b/rs/moq-net/tests/integration/stream_credit.rs @@ -5,12 +5,12 @@ use std::time::Duration; -use moq_net::{Hop, Timestamp, Version, origin, track}; +use moq_net::{Timestamp, Version, origin, track}; use crate::support::harness::{MockConnectOptions, connect_mock, spawn}; fn origin(hop: u64) -> origin::Producer { - let (origin, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (origin, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); spawn(driver); origin } diff --git a/rs/moq-net/tests/integration/subscribe_priority.rs b/rs/moq-net/tests/integration/subscribe_priority.rs index 2f66d8f0428..4abf1a02f9e 100644 --- a/rs/moq-net/tests/integration/subscribe_priority.rs +++ b/rs/moq-net/tests/integration/subscribe_priority.rs @@ -8,7 +8,7 @@ use crate::support; use std::time::Duration; use moq_net::track::{Info, Subscription}; -use moq_net::{Hop, Timescale, Version, origin}; +use moq_net::{Timescale, Version, origin}; use support::harness::peer; const TIMEOUT: Duration = Duration::from_secs(10); @@ -19,7 +19,7 @@ const LOW: i8 = -100; const HIGH: i8 = 100; fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/subscribe_ranges.rs b/rs/moq-net/tests/integration/subscribe_ranges.rs index 021037d8204..9dc5994530f 100644 --- a/rs/moq-net/tests/integration/subscribe_ranges.rs +++ b/rs/moq-net/tests/integration/subscribe_ranges.rs @@ -20,7 +20,7 @@ const TRANSPORT: &[&str] = &["moq-transport-18", "moq-transport-22"]; fn produce_origin(hop: u64) -> moq_net::origin::Producer { let (producer, driver) = - moq_net::origin::Producer::new(moq_net::origin::Config::new(moq_net::Hop::new(hop).unwrap())); + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/subscribe_tracks.rs b/rs/moq-net/tests/integration/subscribe_tracks.rs index c0b02d2a8e9..78a7b53e8c3 100644 --- a/rs/moq-net/tests/integration/subscribe_tracks.rs +++ b/rs/moq-net/tests/integration/subscribe_tracks.rs @@ -11,7 +11,7 @@ use std::time::Duration; use futures::StreamExt; use moq_net::transport::poll::{RecvStream as _, SendStream as _, Session as _}; -use moq_net::{Hop, Timestamp, Version}; +use moq_net::{Timestamp, Version}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; /// A millisecond track: the frames written here carry timestamps. @@ -33,7 +33,8 @@ const SUBSCRIBE_TRACKS: &[u8] = &[ ]; fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/subscribe_with_track.rs b/rs/moq-net/tests/integration/subscribe_with_track.rs index 80517410d6b..e75a7a8e8dd 100644 --- a/rs/moq-net/tests/integration/subscribe_with_track.rs +++ b/rs/moq-net/tests/integration/subscribe_with_track.rs @@ -13,7 +13,7 @@ use crate::support; use std::time::Duration; -use moq_net::{Hop, Timestamp, Version, origin}; +use moq_net::{Timestamp, Version, origin}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; const TIMEOUT: Duration = Duration::from_secs(10); @@ -39,7 +39,7 @@ enum Arrival { } fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/subscriber_max_age.rs b/rs/moq-net/tests/integration/subscriber_max_age.rs index a8ae860d80a..ee006fdf82c 100644 --- a/rs/moq-net/tests/integration/subscriber_max_age.rs +++ b/rs/moq-net/tests/integration/subscriber_max_age.rs @@ -4,12 +4,12 @@ use std::time::Duration; -use moq_net::{Hop, Timestamp, Version, origin, track}; +use moq_net::{Timestamp, Version, origin, track}; use crate::support::harness::{peer, spawn}; fn origin(hop: u64) -> origin::Producer { - let (origin, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (origin, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); spawn(driver); origin } diff --git a/rs/moq-net/tests/integration/subscription_end_integrity.rs b/rs/moq-net/tests/integration/subscription_end_integrity.rs index ffca1a3130d..ffb13a87f1f 100644 --- a/rs/moq-net/tests/integration/subscription_end_integrity.rs +++ b/rs/moq-net/tests/integration/subscription_end_integrity.rs @@ -23,7 +23,7 @@ use crate::support; use std::time::Duration; -use moq_net::{Hop, Timestamp, Version}; +use moq_net::{Timestamp, Version}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; /// A millisecond track: the frames written here carry timestamps. @@ -36,7 +36,8 @@ const HEAD: [&[u8]; 2] = [b"head-a", b"head-b"]; const TAIL: [&[u8]; 2] = [b"tail-a", b"tail-b"]; fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/synced.rs b/rs/moq-net/tests/integration/synced.rs index 5deeaac65e3..0d043420e80 100644 --- a/rs/moq-net/tests/integration/synced.rs +++ b/rs/moq-net/tests/integration/synced.rs @@ -7,7 +7,7 @@ use std::collections::BTreeSet; use std::time::Duration; -use moq_net::{Hop, Version, origin}; +use moq_net::{Version, origin}; use crate::support; use support::harness::{MockConnectOptions, connect_mock}; @@ -16,7 +16,7 @@ use support::harness::{MockConnectOptions, connect_mock}; const SETTLE: Duration = Duration::from_secs(1); fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/track_abort_over_session.rs b/rs/moq-net/tests/integration/track_abort_over_session.rs index 5d3cb9750be..90b3d561b33 100644 --- a/rs/moq-net/tests/integration/track_abort_over_session.rs +++ b/rs/moq-net/tests/integration/track_abort_over_session.rs @@ -7,7 +7,7 @@ use crate::support; use std::time::Duration; -use moq_net::{Hop, Timestamp, Version}; +use moq_net::{Timestamp, Version}; use support::harness::{MockConnectOptions, connect_mock}; /// A millisecond track: the frames written here carry timestamps. @@ -16,7 +16,8 @@ fn timed() -> moq_net::track::Info { } fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/track_info_cancel.rs b/rs/moq-net/tests/integration/track_info_cancel.rs index e829eb814a1..3f7a405db97 100644 --- a/rs/moq-net/tests/integration/track_info_cancel.rs +++ b/rs/moq-net/tests/integration/track_info_cancel.rs @@ -12,11 +12,11 @@ use crate::support; use std::time::Duration; -use moq_net::{Hop, Version, origin}; +use moq_net::{Version, origin}; use support::harness::{MockConnectOptions, connect_mock, peer}; fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/track_stream_demand.rs b/rs/moq-net/tests/integration/track_stream_demand.rs index 6cec3a0fae2..9994bd8eb53 100644 --- a/rs/moq-net/tests/integration/track_stream_demand.rs +++ b/rs/moq-net/tests/integration/track_stream_demand.rs @@ -12,7 +12,7 @@ use crate::support; use std::{cell::RefCell, rc::Rc, time::Duration}; -use moq_net::{Hop, Timestamp, Version, origin}; +use moq_net::{Timestamp, Version, origin}; use support::{ harness::{MockConnectOptions, MockPair, connect_mock}, mock::MockSession, @@ -30,7 +30,7 @@ const VERSIONS: [&str; 3] = ["moq-lite-05", "moq-lite-06", "moq-lite-07-wip"]; const STARTUP: Duration = Duration::from_millis(5); fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/track_tail.rs b/rs/moq-net/tests/integration/track_tail.rs index a2a2eaba949..c40bf3916f7 100644 --- a/rs/moq-net/tests/integration/track_tail.rs +++ b/rs/moq-net/tests/integration/track_tail.rs @@ -15,7 +15,7 @@ use crate::support; use std::time::Duration; -use moq_net::{Hop, Timestamp, Version}; +use moq_net::{Timestamp, Version}; use support::harness::{MockConnectOptions, connect_mock}; /// A millisecond track with no publisher max age: the frames written here carry timestamps, @@ -57,7 +57,8 @@ enum Late { const DEATH: moq_net::SessionError = moq_net::SessionError::App(7); fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/tracks.rs b/rs/moq-net/tests/integration/tracks.rs index da61c174a17..41fc17741bb 100644 --- a/rs/moq-net/tests/integration/tracks.rs +++ b/rs/moq-net/tests/integration/tracks.rs @@ -8,13 +8,14 @@ use crate::support; use std::time::Duration; use moq_net::broadcast::TracksEvent; -use moq_net::{Hop, Version, session::Limits}; +use moq_net::{Version, session::Limits}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; const TIMEOUT: Duration = Duration::from_secs(10); fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/tracks_ietf.rs b/rs/moq-net/tests/integration/tracks_ietf.rs index 94e2fcc4145..cc78320d4fe 100644 --- a/rs/moq-net/tests/integration/tracks_ietf.rs +++ b/rs/moq-net/tests/integration/tracks_ietf.rs @@ -11,8 +11,8 @@ use crate::support; use std::time::Duration; +use moq_net::Version; use moq_net::broadcast::TracksEvent; -use moq_net::{Hop, Version}; use support::harness::{MockConnectOptions, MockPair, connect_mock}; const TIMEOUT: Duration = Duration::from_secs(10); @@ -27,7 +27,8 @@ const SUBSCRIBE: u8 = 0x03; const SUBSCRIBE_TRACKS: u8 = 0x51; fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/unannounce_release.rs b/rs/moq-net/tests/integration/unannounce_release.rs index 581a3d4fa42..0e6d6ba56ff 100644 --- a/rs/moq-net/tests/integration/unannounce_release.rs +++ b/rs/moq-net/tests/integration/unannounce_release.rs @@ -7,11 +7,12 @@ use crate::support; use std::time::Duration; -use moq_net::{Hop, Version}; +use moq_net::Version; use support::harness::{MockConnectOptions, connect_mock}; fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/untimed.rs b/rs/moq-net/tests/integration/untimed.rs index e5bd86b751a..2e2f8ae0543 100644 --- a/rs/moq-net/tests/integration/untimed.rs +++ b/rs/moq-net/tests/integration/untimed.rs @@ -12,7 +12,7 @@ use crate::support; use std::time::Duration; use bytes::Bytes; -use moq_net::{Hop, Timescale, Timestamp, Version, datagram, origin, track}; +use moq_net::{Timescale, Timestamp, Version, datagram, origin, track}; use support::harness::peer; /// A millisecond track: the frames written here carry timestamps. @@ -53,7 +53,7 @@ const VERSIONS: &[&str] = &[ ]; fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/warm_backfill.rs b/rs/moq-net/tests/integration/warm_backfill.rs index f9678db578a..78c06d0072f 100644 --- a/rs/moq-net/tests/integration/warm_backfill.rs +++ b/rs/moq-net/tests/integration/warm_backfill.rs @@ -14,7 +14,7 @@ use std::time::Duration; use moq_net::track::Delay; use moq_net::track::{Info, Subscription}; -use moq_net::{Hop, Timescale, Timestamp, Version, origin, track}; +use moq_net::{Timescale, Timestamp, Version, origin, track}; use crate::support::harness::{peer, spawn}; @@ -29,7 +29,7 @@ const BUDGET: Duration = Duration::from_secs(100); const VERSIONS: &[&str] = &["moq-lite-05", "moq-lite-06", "moq-lite-07-wip"]; fn origin(hop: u64) -> origin::Producer { - let (origin, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (origin, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); spawn(driver); origin } diff --git a/rs/moq-net/tests/integration/wide_hop.rs b/rs/moq-net/tests/integration/wide_hop.rs index d0f4854c536..7651f262d1d 100644 --- a/rs/moq-net/tests/integration/wide_hop.rs +++ b/rs/moq-net/tests/integration/wide_hop.rs @@ -5,11 +5,11 @@ use crate::support; -use moq_net::{Hop, Version, cache, origin}; +use moq_net::{Version, cache, origin}; use support::harness::peer; fn produce(hop: u64) -> origin::Producer { - let mut config = origin::Config::new(Hop::new(hop).unwrap()); + let mut config = origin::Config::new(std::num::NonZeroU64::new(hop).unwrap()); config.pool = cache::Pool::unbounded(); let (producer, driver) = origin::Producer::new(config); support::harness::spawn(driver); @@ -21,7 +21,7 @@ fn produce(hop: u64) -> origin::Producer { /// lite-06's QUIC varint, while the relay's own hop still follows it. #[kio::test] async fn widest_hop_crosses_each_varint_form() { - for (downstream, forwarded) in [("moq-lite-06", Hop::UNKNOWN.id()), ("moq-lite-07-wip", u64::MAX)] { + for (downstream, forwarded) in [("moq-lite-06", 0), ("moq-lite-07-wip", u64::MAX)] { let source = produce(u64::MAX); let relay = produce(2); let sink = produce(3); @@ -33,7 +33,7 @@ async fn widest_hop_crosses_each_varint_form() { .unwrap(); kio::clock::sim::idle().await; - let ids = |route: origin::RouteInfo| route.hops().iter().map(|hop| hop.id()).collect::>(); + let ids = |route: origin::RouteInfo| route.hops().collect::>(); let at_relay = crate::support::announced(&relay.consume(), "room").await; assert_eq!(ids(at_relay), [u64::MAX], "{downstream}"); let at_sink = crate::support::announced(&sink.consume(), "room").await; diff --git a/rs/moq-net/tests/integration/wide_sequence.rs b/rs/moq-net/tests/integration/wide_sequence.rs index 6584fa8b8a4..36d486eb278 100644 --- a/rs/moq-net/tests/integration/wide_sequence.rs +++ b/rs/moq-net/tests/integration/wide_sequence.rs @@ -6,7 +6,7 @@ use crate::support; use std::time::Duration; -use moq_net::{Hop, Timestamp, Version}; +use moq_net::{Timestamp, Version}; use support::harness::{MockConnectOptions, connect_mock}; /// Published QUIC-varint sequences keep all their bits on the live feed, directly @@ -74,7 +74,8 @@ fn timed() -> moq_net::track::Info { } fn produce_origin(hop: u64) -> moq_net::origin::Producer { - let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = + moq_net::origin::Producer::new(moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); support::harness::spawn(driver); producer } diff --git a/rs/moq-net/tests/integration/widened_max_age.rs b/rs/moq-net/tests/integration/widened_max_age.rs index 5d0403b9123..f3b147f4d6e 100644 --- a/rs/moq-net/tests/integration/widened_max_age.rs +++ b/rs/moq-net/tests/integration/widened_max_age.rs @@ -12,7 +12,7 @@ use std::time::Duration; use moq_net::track::Delay; use moq_net::track::{Info, Range, Subscription}; -use moq_net::{Hop, Timescale, Timestamp, Version, kio, origin, track}; +use moq_net::{Timescale, Timestamp, Version, kio, origin, track}; use crate::support::harness::{MockConnectOptions, MockPair, connect_mock, peer, spawn}; @@ -36,7 +36,7 @@ const VERSIONS: &[&str] = &["moq-lite-06", "moq-lite-07-wip"]; const VERSION: &str = "moq-lite-07-wip"; fn origin(hop: u64) -> origin::Producer { - let (origin, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (origin, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); spawn(driver); origin } diff --git a/rs/moq-net/tests/integration/zero_copy.rs b/rs/moq-net/tests/integration/zero_copy.rs index f8668ef9a56..dfab49eacab 100644 --- a/rs/moq-net/tests/integration/zero_copy.rs +++ b/rs/moq-net/tests/integration/zero_copy.rs @@ -10,7 +10,7 @@ use crate::support; use std::time::Duration; use bytes::Bytes; -use moq_net::{Client, Hop, Server, Timestamp, Version, origin, transport::memory}; +use moq_net::{Client, Server, Timestamp, Version, origin, transport::memory}; use support::harness::{now, spawn, subscribed}; const TIMEOUT: Duration = Duration::from_secs(10); @@ -18,7 +18,7 @@ const TIMEOUT: Duration = Duration::from_secs(10); const VERSIONS: &[&str] = &["moq-lite-03", "moq-lite-06", "moq-lite-07-wip", "moq-transport-22"]; fn produce_origin(hop: u64) -> origin::Producer { - let (producer, driver) = origin::Producer::new(origin::Config::new(Hop::new(hop).unwrap())); + let (producer, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); spawn(driver); producer } diff --git a/rs/moq-relay/src/cluster.rs b/rs/moq-relay/src/cluster.rs index 86edbb4178f..b1ddd7b6665 100644 --- a/rs/moq-relay/src/cluster.rs +++ b/rs/moq-relay/src/cluster.rs @@ -11,8 +11,9 @@ use std::{ use anyhow::Context; use futures::FutureExt as _; use moq_net::origin; -use moq_net::{Hop, Path, stats::Tier}; +use moq_net::{Path, stats::Tier}; use reqwest_middleware::ClientWithMiddleware; +use std::num::{NonZeroU64, NonZeroUsize}; use std::task::Poll; use crate::critical::Child; @@ -1361,7 +1362,7 @@ impl Cluster { /// The origin ID used by this relay on the wire. pub fn id(&self) -> u64 { - self.origin.hop().id() + self.origin.hop().get() } /// Creates a cluster with one origin, using [`Options`] for identity, cache, @@ -1390,10 +1391,10 @@ impl Cluster { peer, stats, } = options; - let id = match config.id { - Some(id) => Hop::new(id).context("--cluster-id must be non-zero")?, - None => Hop::random(), - }; + let id = config + .id + .map(|id| NonZeroU64::new(id).context("--cluster-id must be non-zero")) + .transpose()?; let deprecated = config.deprecated(); anyhow::ensure!(deprecated.is_empty(), "{deprecated}"); // Reject a repeated static identity with conflicting policy up front, @@ -1406,7 +1407,7 @@ impl Cluster { crate::configured_tier(config.tier.clone()).context("invalid --cluster-tier")?; peer.quic.validate()?; let mut work = kio::Tasks::new(); - let mut origin_config = origin::Config::new(id); + let mut origin_config = id.map(origin::Config::new).unwrap_or_default(); origin_config.route_key = Some(match &config.route_key { Some(path) => (&moq_crypto::sign::SecretKey::load_or_generate(path) .with_context(|| format!("--cluster-route-key {}", path.display()))?) @@ -1414,7 +1415,9 @@ impl Cluster { None => origin::RouteKey::generate(), }); if let Some(max) = config.max_hops { - origin_config.max_hops = origin::HopLimit::new(max).context("--cluster-max-hops must be from 1 to 32")?; + origin_config.max_hops = NonZeroUsize::new(max) + .filter(|max| max.get() <= 32) + .context("--cluster-max-hops must be from 1 to 32")?; } if let Some(cache) = cache { origin_config.pool = cache.pool; @@ -3364,7 +3367,7 @@ mod tests { ..Default::default() }) .expect("valid id"); - assert_eq!(cluster.origin.hop().id(), id); + assert_eq!(cluster.origin.hop().get(), id); } } @@ -3395,7 +3398,7 @@ mod tests { .expect("cluster"); let origin = cluster.origin.clone(); - assert_eq!(origin.hop().id(), 42); + assert_eq!(origin.hop().get(), 42); assert_eq!(origin.config().cache_duration, duration); assert_eq!(origin.config().pool.expiry(), Some(duration)); @@ -3921,7 +3924,7 @@ mod tests { .expect("origin closed"); assert_eq!(update.prefix.as_str(), "from-node"); // The dialer marks what the peer forwards: it entered at `node`, not here. - assert_eq!(update.route.source(), origin::Source::Peer(node.origin.hop())); + assert_eq!(update.route.source(), origin::Source::Peer(node.origin.hop().get())); let _from_fp = fingerprint .origin @@ -3935,7 +3938,10 @@ mod tests { .expect("origin closed"); if update.prefix.as_str() == "from-fingerprint" { // The acceptor marks a LAN peer the same way. - assert_eq!(update.route.source(), origin::Source::Peer(fingerprint.origin.hop())); + assert_eq!( + update.route.source(), + origin::Source::Peer(fingerprint.origin.hop().get()) + ); break; } } diff --git a/rs/moq-relay/tests/integration/embed.rs b/rs/moq-relay/tests/integration/embed.rs index 98580bc7f07..6c2c46b665f 100644 --- a/rs/moq-relay/tests/integration/embed.rs +++ b/rs/moq-relay/tests/integration/embed.rs @@ -172,7 +172,7 @@ async fn embed_and_stop(mut config: Config) { relay.config().quic.max_streams, Some(moq_tokio::quic::DEFAULT_MAX_STREAMS) ); - assert_eq!(relay.cluster().id(), relay.cluster().origin.hop().id()); + assert_eq!(relay.cluster().id(), relay.cluster().origin.hop().get()); // The application handles: in-process workers publish into the origin the // QUIC sessions see, and the trigger stops the owner from any task. Both diff --git a/rs/moq-relay/tests/integration/upstream_links.rs b/rs/moq-relay/tests/integration/upstream_links.rs index 71b97ec486a..8ecf07e5a35 100644 --- a/rs/moq-relay/tests/integration/upstream_links.rs +++ b/rs/moq-relay/tests/integration/upstream_links.rs @@ -211,7 +211,7 @@ fn routes(origin: &origin::Producer) -> BTreeMap> { let origin::RouteEvent::Start(announce) = event else { panic!("an initial set is only starts: got {event:?}"); }; - let hops = announce.route.hops().iter().map(|hop| hop.id()).collect(); + let hops = announce.route.hops().collect(); routes.insert(announce.prefix.as_str().to_string(), hops); } routes diff --git a/rs/moq-room/src/chat.rs b/rs/moq-room/src/chat.rs index 0c4244437da..0639bd8d5e1 100644 --- a/rs/moq-room/src/chat.rs +++ b/rs/moq-room/src/chat.rs @@ -226,7 +226,7 @@ mod tests { /// An origin at `hop`, its driver spawned. fn origin(hop: u64) -> moq_net::origin::Producer { - let config = moq_net::origin::Config::new(moq_net::Hop::new(hop).unwrap()); + let config = moq_net::origin::Config::new(std::num::NonZeroU64::new(hop).unwrap()); let (producer, driver) = moq_net::origin::Producer::new(config); tokio::spawn(moq_net::time::run(driver)); producer diff --git a/rs/moq-tokio/src/client.rs b/rs/moq-tokio/src/client.rs index b8925c4c73c..4a6b1daaa83 100644 --- a/rs/moq-tokio/src/client.rs +++ b/rs/moq-tokio/src/client.rs @@ -228,9 +228,9 @@ impl Client { self } - /// Pin the identity a dialed peer's routes are attributed to, for a peer whose + /// Pin the hop id a dialed peer's routes are attributed to, for a peer whose /// identity the caller has established; see [`moq_net::Client::with_peer_hop`]. - pub fn with_peer_hop(mut self, hop: moq_net::Hop) -> Self { + pub fn with_peer_hop(mut self, hop: std::num::NonZeroU64) -> Self { self.moq = self.moq.with_peer_hop(hop); self } diff --git a/rs/moq-tokio/src/server.rs b/rs/moq-tokio/src/server.rs index d15eb28f5c3..38a3ab18c01 100644 --- a/rs/moq-tokio/src/server.rs +++ b/rs/moq-tokio/src/server.rs @@ -1688,10 +1688,10 @@ impl Request { self } - /// Assign the identity this peer's routes are attributed to; see + /// Assign the hop id this peer's routes are attributed to; see /// [`moq_net::server::Handshake::with_peer_hop`]. Derive it from [`Self::peer_identity`], /// never from something coarser. - pub fn with_peer_hop(mut self, hop: moq_net::Hop) -> Self { + pub fn with_peer_hop(mut self, hop: std::num::NonZeroU64) -> Self { *self.handshake = (*self.handshake).with_peer_hop(hop); self } @@ -1896,7 +1896,7 @@ impl Request { /// /// Self-declared, so treat it as a correlation hint rather than an /// authenticated identity: authorize on the token or client certificate. - pub fn peer_hop(&self) -> Option { + pub fn peer_hop(&self) -> Option { self.handshake.peer_hop() } diff --git a/rs/moq-tokio/tests/integration/sim.rs b/rs/moq-tokio/tests/integration/sim.rs index 75f65309a4f..4d2989bce89 100644 --- a/rs/moq-tokio/tests/integration/sim.rs +++ b/rs/moq-tokio/tests/integration/sim.rs @@ -287,7 +287,7 @@ fn tls(version: Version) -> (driver::server::Config, driver::client::Config) { } fn origin_producer(hop: u64) -> origin::Producer { - let (origin, driver) = origin::Producer::new(origin::Config::new(moq_net::Hop::new(hop).unwrap())); + let (origin, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(hop).unwrap())); spawn(driver); origin }