From fe4d8d0f5107bea0cce5014c65e950f94d53ea9b Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:22:02 -0700 Subject: [PATCH 1/3] chore(quest): claim quest/m1/api-audit/auth-clock-names.md Quest-Claim: 1581661f17f06f4a From 94c22881ecc24e4100104f3d29ceef3a1a8b662c Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:36:26 -0700 Subject: [PATCH 2/3] refactor: distinct auth refusal names and mirrored clock names Rename moq_auth::serve::Refusal to serve::Denial and moq_net::stats::Refusal to stats::RefusalKind, so Refusal names only the shared 403 body. Rename moq_clock::anchor() to origin() to match @moq/clock, return an Installed handle from the JS Manual.install() like Rust's, and drop moq_net::time::now() in favor of Instant::now(). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EeyiEy5FWz3z44DYZVo7vU --- doc/lib/js/clock.md | 9 +- js/clock/MIGRATE.md | 17 +++ js/clock/README.md | 4 +- js/clock/bench/timers.ts | 4 +- js/clock/src/ambient.ts | 11 +- js/clock/src/index.test.ts | 13 +- js/clock/src/index.ts | 6 +- js/clock/src/manual.ts | 6 +- js/hang/src/container/consumer.holes.test.ts | 16 +- js/hang/src/container/consumer.test.ts | 4 +- js/net/bench/drift.ts | 4 +- js/net/bench/refresh.ts | 4 +- js/net/src/auth.test.ts | 4 +- js/net/src/broadcast.test.ts | 8 +- js/net/src/connection/close.test.ts | 8 +- js/net/src/connection/migrate.test.ts | 44 +++--- js/net/src/goaway-requests.test.ts | 2 +- js/net/src/ietf/aliases.test.ts | 2 +- js/net/src/ietf/publisher.test.ts | 7 +- js/net/src/ietf/subscribe_tracks.test.ts | 10 +- js/net/src/ietf/tail.test.ts | 2 +- js/net/src/lite/compression.test.ts | 4 +- js/net/src/lite/connection.test.ts | 12 +- js/net/src/lite/publisher.test.ts | 4 +- js/net/src/lite/refresh.test.ts | 4 +- js/net/src/lite/subscriber.test.ts | 4 +- js/net/src/parked-expiry.test.ts | 4 +- js/net/src/request-deadline.test.ts | 20 +-- js/net/src/resume.test.ts | 32 ++-- js/net/src/tail.test.ts | 8 +- js/net/src/track.test.ts | 66 ++++----- js/net/src/util/timeout.test.ts | 4 +- js/publish/bench/catalog.ts | 4 +- js/publish/src/broadcast.test.ts | 8 +- js/publish/src/catalog.test.ts | 16 +- js/publish/src/source/retry.test.ts | 3 +- js/publish/src/video/capture.test.ts | 4 +- js/publish/src/video/encoder-stall.test.ts | 4 +- js/publish/src/video/encoder.test.ts | 8 +- js/qmux/src/session.test.ts | 20 +-- js/room/src/chat.test.ts | 4 +- js/signals/src/index.test.ts | 32 ++-- js/watch/src/audio/decoder.test.ts | 5 +- js/watch/src/audio/replay.ts | 4 +- js/watch/src/sync.test.ts | 18 +-- js/watch/src/video/decoder.test.ts | 15 +- quest/m1/api-audit/README.md | 1 - quest/m1/api-audit/auth-clock-names.md | 23 --- quest/m1/time/wall.md | 4 +- rs/moq-audio/src/decode/consumer.rs | 4 +- rs/moq-audio/src/encode/producer.rs | 4 +- rs/moq-auth/MIGRATE.md | 5 + rs/moq-auth/src/serve.rs | 140 +++++++++--------- rs/moq-c/src/publish.rs | 2 +- rs/moq-c/src/video.rs | 2 +- rs/moq-cli/src/main.rs | 4 +- rs/moq-clock/MIGRATE.md | 4 + rs/moq-clock/src/installed.rs | 8 +- rs/moq-clock/src/lib.rs | 9 +- rs/moq-clock/src/runtime.rs | 10 +- rs/moq-e2ee/tests/support/harness.rs | 2 +- rs/moq-ffi/src/auth.rs | 2 +- rs/moq-gst/src/sink/imp.rs | 4 +- rs/moq-gst/src/sink/pad.rs | 46 +++--- rs/moq-hls/src/export/mod.rs | 14 +- rs/moq-mux/src/container/test_util.rs | 8 +- rs/moq-net/MIGRATE.md | 5 + rs/moq-net/src/model/clock.rs | 2 +- rs/moq-net/src/stats.rs | 8 +- rs/moq-net/src/stats/outcomes.rs | 32 ++-- rs/moq-net/src/time.rs | 2 +- rs/moq-relay/src/auth/refresh.rs | 4 +- rs/moq-relay/src/connection.rs | 12 +- rs/moq-relay/src/internal.rs | 12 +- rs/moq-relay/src/refusals.rs | 22 +-- rs/moq-relay/src/uring.rs | 4 +- rs/moq-relay/src/web.rs | 10 +- .../tests/integration/auth_lifetime.rs | 2 +- rs/moq-relay/tests/integration/drain.rs | 4 +- rs/moq-relay/tests/integration/memory.rs | 4 +- rs/moq-relay/tests/integration/refusals.rs | 4 +- rs/moq-room/src/chat.rs | 4 +- rs/moq-srt/src/server.rs | 10 +- rs/moq-srt/src/ts.rs | 4 +- rs/moq-stats/MIGRATE.md | 4 + rs/moq-stats/src/lib.rs | 2 +- rs/moq-tokio/src/client.rs | 2 +- rs/moq-tokio/src/connection/auth.rs | 2 +- rs/moq-tokio/src/server.rs | 10 +- rs/moq-transcode/src/catalog.rs | 4 +- rs/moq-uring/benches/session_lite.rs | 4 +- rs/moq-uring/src/worker.rs | 8 +- rs/moq-uring/tests/integration/session.rs | 8 +- rs/moq-uring/tests/integration/web.rs | 4 +- rs/moq-video/src/encode/producer.rs | 6 +- rs/moq-wasm/src/lib.rs | 5 +- 96 files changed, 516 insertions(+), 476 deletions(-) delete mode 100644 quest/m1/api-audit/auth-clock-names.md diff --git a/doc/lib/js/clock.md b/doc/lib/js/clock.md index a220b776e7c..4c4b225378f 100644 --- a/doc/lib/js/clock.md +++ b/doc/lib/js/clock.md @@ -17,7 +17,7 @@ bun add @moq/clock import { Manual, Milli, Nano, now, sleep } from "@moq/clock"; const clock = new Manual(); -const restore = clock.install(); +const installed = clock.install(); try { const start = now(); const pending = sleep(Nano.fromMilli(Milli(10))); @@ -25,7 +25,7 @@ try { await pending; console.log(now() - start); // 10,000,000 nanoseconds } finally { - restore(); + installed.close(); } ``` @@ -56,8 +56,9 @@ Timer callbacks may arm timers, but must leave driving that clock to their calle wall time without the jitter of subtracting two live reads. On the host it is the realm's performance time origin; on a `Manual` it follows `stepWall()`. -Installation is scoped to the current JS realm. Restore it in `finally` and -keep tests sharing that realm serial. Timers remain bound to the clock on +Installation is scoped to the current JS realm. Close the handle `install()` +returns in `finally`, or hold it with `using`, and keep tests sharing that +realm serial. Timers remain bound to the clock on which they were created, even after restoration. Host timers used by a test runner or RPC framework keep running in real time. diff --git a/js/clock/MIGRATE.md b/js/clock/MIGRATE.md index 0c1407fd44c..febbca4ce77 100644 --- a/js/clock/MIGRATE.md +++ b/js/clock/MIGRATE.md @@ -4,6 +4,23 @@ How to update your code for each breaking change, newest first. ## Unreleased +### `Manual.install()` returns an `Installed` handle (#6510) + +`install()` returns an `Installed` handle instead of a restore function, matching Rust's `Manual::install`. +Call `installed.close()` where you called `restore()`, or hold it with `using`: + +```ts +// Before +const restore = clock.install(); +restore(); + +// After +const installed = clock.install(); +installed.close(); +// or +using _installed = clock.install(); +``` + ### Manual time steps through timer deadlines Rename `await clock.advanceAsync(duration)` to `await clock.advance(duration)`. diff --git a/js/clock/README.md b/js/clock/README.md index dd6d30cfc72..561634a60f6 100644 --- a/js/clock/README.md +++ b/js/clock/README.md @@ -7,14 +7,14 @@ Use `Manual` to test time without replacing the host's timers. import { Manual, Milli, Nano, now, sleep } from "@moq/clock"; const clock = new Manual(); -const restore = clock.install(); +const installed = clock.install(); try { const pending = sleep(Nano.fromMilli(Milli(10))); await clock.advance(Nano.fromMilli(Milli(10))); await pending; console.log(now()); // 10,000,000 nanoseconds } finally { - restore(); + installed.close(); } ``` diff --git a/js/clock/bench/timers.ts b/js/clock/bench/timers.ts index c9db92bcc83..36ce4e7e18f 100644 --- a/js/clock/bench/timers.ts +++ b/js/clock/bench/timers.ts @@ -9,7 +9,7 @@ for (const mode of ["jump", "advance"]) { const samples: number[][] = [[], [], []]; for (let round = 0; round < 6; round++) { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const aborts = Array.from({ length: scope === "shared" ? 1 : armed }, () => new AbortController()); try { const start = performance.now(); @@ -31,7 +31,7 @@ for (const mode of ["jump", "advance"]) { samples[2].push((cancelledAt - advancedAt) * 1000); } } finally { - restore(); + installed.close(); } } console.log( diff --git a/js/clock/src/ambient.ts b/js/clock/src/ambient.ts index f26a62d844b..8d515da4b3b 100644 --- a/js/clock/src/ambient.ts +++ b/js/clock/src/ambient.ts @@ -3,16 +3,23 @@ import { host } from "./host.ts"; let current: { backend: Backend; previous?: typeof current; active: boolean } = { backend: host, active: true }; +/** A clock installed in the current realm; close it to restore the clock it replaced. */ +export interface Installed extends Disposable { + /** Restore the clock this one replaced. Idempotent, and safe out of order. */ + close(): void; +} + export function backend(): Backend { return current.backend; } -export function install(backend: Backend): () => void { +export function install(backend: Backend): Installed { const entry = { backend, previous: current, active: true }; current = entry; - return () => { + const close = () => { entry.active = false; // Out-of-order cleanup must not revive an already-restored outer clock. while (!current.active && current.previous) current = current.previous; }; + return { close, [Symbol.dispose]: close }; } diff --git a/js/clock/src/index.test.ts b/js/clock/src/index.test.ts index cce136fcca8..8adf5d0aa84 100644 --- a/js/clock/src/index.test.ts +++ b/js/clock/src/index.test.ts @@ -2,6 +2,7 @@ import { afterEach, expect, test } from "bun:test"; import { setTimeout as hostTimeout } from "node:timers/promises"; import { Elapsed, + type Installed, Instant, interval, Manual, @@ -19,13 +20,13 @@ import { wall, } from "./index.ts"; -const restores: (() => void)[] = []; +const installs: Installed[] = []; afterEach(() => { - for (const restore of restores.splice(0).reverse()) restore(); + for (const installed of installs.splice(0).reverse()) installed.close(); }); function manual(): Manual { const clock = new Manual(); - restores.push(clock.install()); + installs.push(clock.install()); return clock; } const ns = Nano.fromMilli; @@ -77,11 +78,11 @@ test("installation restores nested and out-of-order scopes without reviving them const inner = manual(); inner.jump(Nano(8)); expect(now()).toBe(8); - restores[0](); + installs[0].close(); expect(now()).toBe(8); - restores[1](); + installs[1].close(); const restored = now(); - restores[1](); + installs[1].close(); expect(now()).toBeGreaterThanOrEqual(restored); expect(now()).not.toBe(4); }); diff --git a/js/clock/src/index.ts b/js/clock/src/index.ts index 4a0d908b1a7..47f93c41334 100644 --- a/js/clock/src/index.ts +++ b/js/clock/src/index.ts @@ -8,6 +8,7 @@ import { backend } from "./ambient.ts"; import { Wall } from "./types.ts"; +export type { Installed } from "./ambient.ts"; export { Manual } from "./manual.ts"; export { Elapsed, Interval, interval, MissedTickBehavior, now, sleep, sleepUntil, timeout } from "./timer.ts"; export { Instant, Micro, Milli, Nano, Second, Wall } from "./types.ts"; @@ -17,7 +18,10 @@ export function wall(): Wall { return Wall(backend().wall()); } -/** Read the installed clock's wall time at instant zero, in Unix milliseconds. */ +/** + * Read the installed clock's wall time at instant zero, in Unix milliseconds. + * Rust's `moq_clock::origin()` pairs a nanosecond `Wall` with an instant instead. + */ export function origin(): Wall { return Wall(backend().origin()); } diff --git a/js/clock/src/manual.ts b/js/clock/src/manual.ts index 9440b9ee17e..544ed9e5f59 100644 --- a/js/clock/src/manual.ts +++ b/js/clock/src/manual.ts @@ -1,4 +1,4 @@ -import { install } from "./ambient.ts"; +import { type Installed, install } from "./ambient.ts"; import type { Backend } from "./backend.ts"; import { drain } from "./host.ts"; import { Instant, Nano, Wall } from "./types.ts"; @@ -40,8 +40,8 @@ export class Manual { }, }; - /** Install this clock in the current realm and return an idempotent restore function. */ - install(): () => void { + /** Install this clock in the current realm until the returned handle closes. */ + install(): Installed { return install(this.#backend); } diff --git a/js/hang/src/container/consumer.holes.test.ts b/js/hang/src/container/consumer.holes.test.ts index f2dda27df53..fe77724c73d 100644 --- a/js/hang/src/container/consumer.holes.test.ts +++ b/js/hang/src/container/consumer.holes.test.ts @@ -8,7 +8,7 @@ const flush = () => new Promise((resolve) => setImmediate(resolve)); test.each([0, 100])("a sequence hole before a paused data marker expires at %sms", async (budget) => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const track = new Track.Producer("data"); const consumer = new Consumer(track.subscribe({ maxDelay: Milli(30_000) }), { format: new Format("data"), @@ -48,13 +48,13 @@ test.each([0, 100])("a sequence hole before a paused data marker expires at %sms consumer.close(); track.close(); await reading; - restore(); + installed.close(); } }); test("a filled hole cancels its timer and the next hole gets a fresh budget", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const track = new Track.Producer("data"); const consumer = new Consumer(track.subscribe({ maxDelay: Milli(30_000) }), { format: new Format("data"), @@ -99,13 +99,13 @@ test("a filled hole cancels its timer and the next hole gets a fresh budget", as consumer.close(); track.close(); await reading; - restore(); + installed.close(); } }); test("the holes a stalled source left behind share one budget", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const track = new Track.Producer("data"); const consumer = new Consumer(track.subscribe({ maxDelay: Milli(30_000) }), { format: new Format("data"), @@ -140,13 +140,13 @@ test("the holes a stalled source left behind share one budget", async () => { consumer.close(); track.close(); await reading; - restore(); + installed.close(); } }); test("a hole is late from the earliest arrival past it", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const track = new Track.Producer("data"); const consumer = new Consumer(track.subscribe({ maxDelay: Milli(30_000) }), { format: new Format("data"), @@ -184,6 +184,6 @@ test("a hole is late from the earliest arrival past it", async () => { consumer.close(); track.close(); await reading; - restore(); + installed.close(); } }); diff --git a/js/hang/src/container/consumer.test.ts b/js/hang/src/container/consumer.test.ts index b4c1e38b25d..ad72af5c6fa 100644 --- a/js/hang/src/container/consumer.test.ts +++ b/js/hang/src/container/consumer.test.ts @@ -808,7 +808,7 @@ test("Consumer skips groups via PTS-span when over the max delay", async () => { test("Consumer measures arrivals as they land", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const track = new Track.Producer("test"); const consumer = new Consumer(track.subscribe(), { format: new LegacyFormat("audio"), @@ -840,7 +840,7 @@ test("Consumer measures arrivals as they land", async () => { track.close(); consumer.close(); next.close(); - restore(); + installed.close(); } }); diff --git a/js/net/bench/drift.ts b/js/net/bench/drift.ts index 814af40ddec..a4b74268e2e 100644 --- a/js/net/bench/drift.ts +++ b/js/net/bench/drift.ts @@ -5,7 +5,7 @@ import { type Group, Track } from "@moq/net"; /** Read live frames after a retained window, checking every delivered payload. */ export async function run(): Promise { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const payload = new Uint8Array([7]); try { console.log("retained,publishers,readers,ns_per_frame"); @@ -58,7 +58,7 @@ export async function run(): Promise { } } } finally { - restore(); + installed.close(); } } if (import.meta.main) await run(); diff --git a/js/net/bench/refresh.ts b/js/net/bench/refresh.ts index f477b5c50a9..106f3f3b89d 100644 --- a/js/net/bench/refresh.ts +++ b/js/net/bench/refresh.ts @@ -13,7 +13,7 @@ for (const retained of [1, 64, 1024]) for (const tracks of [1, 8, 32]) for (const joined of [1, 8, 32]) { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const source = new Producer(); const destination = new Producer(); const broadcast = source.createBroadcast(Path.from("room")); @@ -84,6 +84,6 @@ for (const retained of [1, 64, 1024]) source.close(); for (const peer of peers) peer.abort(); await clock.advance(Nano(0)); - restore(); + installed.close(); } } diff --git a/js/net/src/auth.test.ts b/js/net/src/auth.test.ts index ead76be878e..ed75310a155 100644 --- a/js/net/src/auth.test.ts +++ b/js/net/src/auth.test.ts @@ -289,7 +289,7 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_17, Ietf.ALPN.DRAFT_22])("%s", test("a request waits for its token and survives union renewal", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const logged = spyOn(console, "debug"); const origin = new OriginProducer(); const broadcast = origin.createBroadcast(Path.from("room/x")); @@ -344,7 +344,7 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_17, Ietf.ALPN.DRAFT_22])("%s", server.abort(); await adding.catch(() => void 0); logged.mockRestore(); - restore(); + installed.close(); } }); diff --git a/js/net/src/broadcast.test.ts b/js/net/src/broadcast.test.ts index 6251563cf24..3902fe761ab 100644 --- a/js/net/src/broadcast.test.ts +++ b/js/net/src/broadcast.test.ts @@ -965,7 +965,7 @@ function finishedTrack(broadcast: BroadcastProducer, name: string, maxAge?: numb // max-age add nothing to the wait. test("finish serves finished tracks until stale", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const origin = new OriginProducer(); try { const broadcast = origin.createBroadcast(Path.from("finish")); @@ -1005,7 +1005,7 @@ test("finish serves finished tracks until stale", async () => { live.close(); } finally { origin.close(); - restore(); + installed.close(); } }); @@ -1048,7 +1048,7 @@ test("a finished broadcast refuses changes", () => { // A close elsewhere ends the linger early. test("closing the broadcast elsewhere ends the linger", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); try { const broadcast = new BroadcastProducer(); finishedTrack(broadcast, "video", 30).close(); @@ -1059,6 +1059,6 @@ test("closing the broadcast elsewhere ends the linger", async () => { await wait; expect(Number(clock.now())).toBe(Nano.fromMilli(Milli(1_000))); } finally { - restore(); + installed.close(); } }); diff --git a/js/net/src/connection/close.test.ts b/js/net/src/connection/close.test.ts index e8f841f5e2b..1c87a1c2c9d 100644 --- a/js/net/src/connection/close.test.ts +++ b/js/net/src/connection/close.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Manual, Nano, Second } from "@moq/clock"; +import { type Installed, Manual, Nano, Second } from "@moq/clock"; import * as Ietf from "../ietf/index.ts"; import * as Lite from "../lite/index.ts"; import { createMockTransportPair, type MockTransport } from "../mock.ts"; @@ -65,7 +65,7 @@ for (const protocol of [Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_19]) { accept({ url, transport: pair.server, publish: source.consume() }), ]); const announced = destination.announced(); - let restore: (() => void) | undefined; + let installed: Installed | undefined; try { expect((await announced.next())?.kind).toBe("start"); fin.enable(); @@ -75,7 +75,7 @@ for (const protocol of [Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_19]) { }); // Only the close's own deadline is armed on the manual clock. const clock = new Manual(); - if (outcome === "timeout") restore = clock.install(); + if (outcome === "timeout") installed = clock.install(); const closing = server.close(); await fin.reached; expect(closed).toBe(false); @@ -92,7 +92,7 @@ for (const protocol of [Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_19]) { await pair.server.closed; expect(closed).toBe(true); } finally { - restore?.(); + installed?.close(); fin.release(); client.abort(); server.abort(); diff --git a/js/net/src/connection/migrate.test.ts b/js/net/src/connection/migrate.test.ts index ad0cb6aa458..c65b21b3d12 100644 --- a/js/net/src/connection/migrate.test.ts +++ b/js/net/src/connection/migrate.test.ts @@ -77,7 +77,7 @@ const handover = Milli(200); test("an empty GOAWAY migrates the announced request to the replacement session", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const { dials, origin } = fleet(); const broadcast = origin.createBroadcast(Path.from("cam")); broadcast.announce(); @@ -123,13 +123,13 @@ test("an empty GOAWAY migrates the announced request to the replacement session" reload.close(); consume.close(); broadcast.close(); - restore(); + installed.close(); } }); test("a GOAWAY without a timeout hands over at the configured cap", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const { dials } = fleet(); const reload = new Reload({ url, @@ -152,7 +152,7 @@ test("a GOAWAY without a timeout hands over at the configured cap", async () => expect(Nano.toMilli(Instant.durationSince(clock.now(), sent))).toBeGreaterThanOrEqual(handover); } finally { reload.close(); - restore(); + installed.close(); } }); @@ -160,7 +160,7 @@ test("a refused redirect ends the connection instead of reconnecting", async () const refused = ["https://other.example/", "not a url", "http://relay.example/", "https://127.0.0.1/"]; for (const uri of refused) { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const { dials } = fleet(); const reload = new Reload({ url, websocket: { enabled: false }, delay: { initial: Milli(1) } }); @@ -180,7 +180,7 @@ test("a refused redirect ends the connection instead of reconnecting", async () expect(dials.length, uri).toBe(1); } finally { reload.close(); - restore(); + installed.close(); } } }); @@ -211,7 +211,7 @@ const moved = new URL("https://relay.example:5443/room"); test("a redirect moves the pool key while the handle keeps its origin", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const { dials } = fleet(); const handle = new Connection({ url }); @@ -241,13 +241,13 @@ test("a redirect moves the pool key while the handle keeps its origin", async () fresh.close(); } finally { handle.close(); - restore(); + installed.close(); } }); test("a redirect onto an already pooled key leaves both entries to their handles", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const { dials } = fleet(); const redirected = new Connection({ url }); @@ -285,7 +285,7 @@ test("a redirect onto an already pooled key leaves both entries to their handles } finally { redirected.close(); resident.close(); - restore(); + installed.close(); } }); @@ -338,7 +338,7 @@ test.each([ [" even with fresh userinfo on every redirect", "userinfo"], ] as const)("two peers redirecting to each other escalate the backoff instead of cycling%s", async (_, rotate) => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const { dials } = fleet(); const reload = new Reload({ url, @@ -363,13 +363,13 @@ test.each([ expect(reload.error.peek()).toBeUndefined(); } finally { reload.close(); - restore(); + installed.close(); } }); test("redirect endpoint keys omit userinfo without changing the dial URL", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const { dials } = fleet(); const from = new URL("https://first:secret@relay.example/room?jwt=a#x"); const to = new URL("https://second:other@relay.example:5443/room?jwt=b#y"); @@ -393,13 +393,13 @@ test("redirect endpoint keys omit userinfo without changing the dial URL", async } finally { reload.close(); moves.mockRestore(); - restore(); + installed.close(); } }); test("a redirect loop stops at the retry window", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const { dials } = fleet(); const reload = new Reload({ url, @@ -418,13 +418,13 @@ test("a redirect loop stops at the retry window", async () => { expect(reload.error.peek()?.message).toContain("redirect loop"); } finally { reload.close(); - restore(); + installed.close(); } }); test("a loop no faster than the capped delay migrates without backing off", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const { dials } = fleet(); const reload = new Reload({ url, @@ -441,13 +441,13 @@ test("a loop no faster than the capped delay migrates without backing off", asyn } } finally { reload.close(); - restore(); + installed.close(); } }); test("a one-way rolling restart migrates without backing off", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const { dials } = fleet(); const reload = new Reload({ url, @@ -465,13 +465,13 @@ test("a one-way rolling restart migrates without backing off", async () => { expect(await elapse(clock, () => dials.length === 2)).toBe(Milli(0)); } finally { reload.close(); - restore(); + installed.close(); } }); test("repeated GOAWAYs back to the same place are restarts, not a loop", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const { dials } = fleet(); const reload = new Reload({ url, @@ -491,6 +491,6 @@ test("repeated GOAWAYs back to the same place are restarts, not a loop", async ( } } finally { reload.close(); - restore(); + installed.close(); } }); diff --git a/js/net/src/goaway-requests.test.ts b/js/net/src/goaway-requests.test.ts index a3501f392a9..33c59daffef 100644 --- a/js/net/src/goaway-requests.test.ts +++ b/js/net/src/goaway-requests.test.ts @@ -293,7 +293,7 @@ test("announcing and subscribing after GOAWAY still open streams, on the adapter */ async function routeDeath(kind: "lite" | "ietf", after: boolean): Promise { const clock = new Manual(); - using _clock = { [Symbol.dispose]: clock.install() }; + using _clock = clock.install(); const protocol = kind === "lite" ? ALPN_06 : ALPN.DRAFT_17; const pair = createMockTransportPair(protocol); const inject = kind === "ietf" ? captureFirstUni(pair.server) : undefined; diff --git a/js/net/src/ietf/aliases.test.ts b/js/net/src/ietf/aliases.test.ts index 2b85af09fad..8fa8c30f19e 100644 --- a/js/net/src/ietf/aliases.test.ts +++ b/js/net/src/ietf/aliases.test.ts @@ -107,7 +107,7 @@ test("a later subscribe reclaims a retired alias", async () => { // one entry per alias it ever used. test("retired aliases are capped", async () => { const clock = new Manual(); - using _clock = { [Symbol.dispose]: clock.install() }; + using _clock = clock.install(); const aliases = new TrackAliases(); for (let i = 0n; i < 74n; i++) { diff --git a/js/net/src/ietf/publisher.test.ts b/js/net/src/ietf/publisher.test.ts index f696e5e0bac..aa951caadbc 100644 --- a/js/net/src/ietf/publisher.test.ts +++ b/js/net/src/ietf/publisher.test.ts @@ -59,7 +59,8 @@ const STREAM_WAIT = 1000; /** A manual clock, installed until disposed. */ function manual(): Manual & Disposable { const clock = new Manual(); - return Object.assign(clock, { [Symbol.dispose]: clock.install() }); + const installed = clock.install(); + return Object.assign(clock, { [Symbol.dispose]: () => installed.close() }); } /** @@ -720,7 +721,7 @@ test("a blocked group header is reset when the group expires", async () => { // does not end the wait: PUBLISH_DONE waits on the stream, so the budget still judges it. test("a group stream whose FIN never completes is reset when the group expires", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const pair = createMockTransportPair(ALPN.DRAFT_19); let closing!: () => void; @@ -793,7 +794,7 @@ test("a group stream whose FIN never completes is reset when the group expires", client.close(); broadcast.close(); origin.close(); - restore(); + installed.close(); } }); diff --git a/js/net/src/ietf/subscribe_tracks.test.ts b/js/net/src/ietf/subscribe_tracks.test.ts index a51211dcfc2..a8752d48259 100644 --- a/js/net/src/ietf/subscribe_tracks.test.ts +++ b/js/net/src/ietf/subscribe_tracks.test.ts @@ -92,7 +92,7 @@ async function update(stream: Stream, version: IetfVersion, id: bigint, forward: for (const version of drafts) { test(`track listing pauses, resumes, survives listing cancellation and ends on withdrawal (${version})`, async () => { const clock = new Manual(); - using _installed = { [Symbol.dispose]: clock.install() }; + using _installed = clock.install(); const fx = fixture(version); const broadcast = fx.origin.createBroadcast(Path.from("room/live")); broadcast.announce(); @@ -203,7 +203,7 @@ test("draft-18 refuses SUBSCRIBE to a PUBLISHed track", async () => { test("a cancelled listing cannot release its replacement's prefix", async () => { const version = Version.DRAFT_22; const clock = new Manual(); - using _installed = { [Symbol.dispose]: clock.install() }; + using _installed = clock.install(); const fx = fixture(version); const broadcast = fx.origin.createBroadcast(Path.from("room/live")); broadcast.announce(); @@ -228,7 +228,7 @@ test("grants hide tracks, revoke PUBLISHes and relist when broadened", async () const empty = (): Grant => ({ publish: new Path.Patterns([]), subscribe: new Path.Patterns([]) }); const grant = new Signal(empty()); const clock = new Manual(); - using _installed = { [Symbol.dispose]: clock.install() }; + using _installed = clock.install(); const fx = fixture(version, 10, grant); const listing = await fx.list(); await ok(listing, version); @@ -292,7 +292,7 @@ test("paused updates keep one slot and release it when the PUBLISH ends", async const version = Version.DRAFT_22; const fx = fixture(version, 1); const clock = new Manual(); - using _installed = { [Symbol.dispose]: clock.install() }; + using _installed = clock.install(); const broadcast = fx.origin.createBroadcast(Path.from("room/live")); broadcast.announce(); broadcast.createTrack("video"); @@ -313,7 +313,7 @@ test("a failed PUBLISH stream open returns its subscription slot", async () => { const version = Version.DRAFT_22; const fx = fixture(version, 1); const clock = new Manual(); - using _installed = { [Symbol.dispose]: clock.install() }; + using _installed = clock.install(); const open = spyOn(fx.session, "openBi").mockRejectedValue(new StreamError(StreamCode.Cancel)); const broadcast = fx.origin.createBroadcast(Path.from("room/live")); broadcast.announce(); diff --git a/js/net/src/ietf/tail.test.ts b/js/net/src/ietf/tail.test.ts index c88ae61e1bf..08301d3c8dd 100644 --- a/js/net/src/ietf/tail.test.ts +++ b/js/net/src/ietf/tail.test.ts @@ -133,7 +133,7 @@ test("a group read across PUBLISH_DONE is delivered whole", async () => { test("a Stream Count of 0 is a hint, so a late stream within the grace is still delivered", async () => { const clock = new Manual(); - using _clock = { [Symbol.dispose]: clock.install() }; + using _clock = clock.install(); const { subscriber, reader, done } = await subscribed(); await done(TRACK_ENDED, 0n); diff --git a/js/net/src/lite/compression.test.ts b/js/net/src/lite/compression.test.ts index f0434e777d4..e24a9f0978a 100644 --- a/js/net/src/lite/compression.test.ts +++ b/js/net/src/lite/compression.test.ts @@ -10,7 +10,7 @@ import { ALPN_06, ALPN_07_WIP } from "./version.ts"; for (const downstream of [ALPN_06, ALPN_07_WIP]) { test(`compressed publishing on ${downstream}, FETCH and independent datagrams`, async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const source = new Producer(); const destination = new Producer(); const broadcast = source.createBroadcast(Path.from("compressed")); @@ -67,7 +67,7 @@ for (const downstream of [ALPN_06, ALPN_07_WIP]) { for (const origin of [source, destination]) origin.close(); for (const peer of peers) peer.abort(); await clock.advance(Nano.zero); - restore(); + installed.close(); } }); } diff --git a/js/net/src/lite/connection.test.ts b/js/net/src/lite/connection.test.ts index 45c2526f73b..e85e09a2f97 100644 --- a/js/net/src/lite/connection.test.ts +++ b/js/net/src/lite/connection.test.ts @@ -200,7 +200,7 @@ function mockDeadline() { const clock = new Manual(); return { expire: () => clock.advance(Nano.fromMilli(Milli(1000))), - restore: clock.install(), + installed: clock.install(), }; } @@ -327,7 +327,7 @@ test("a lite-07 subscriber withholding FIN holds close until the deadline", asyn expect(await failure).toHaveProperty("message", "session close timed out"); expect(served.closed()).toBe(true); } finally { - deadline.restore(); + deadline.installed.close(); served.cleanup(); } }); @@ -344,7 +344,7 @@ test("a lite-07 subscriber FIN releases close", async () => { await closing; expect(served.closed()).toBe(true); } finally { - deadline.restore(); + deadline.installed.close(); served.cleanup(); } }); @@ -361,7 +361,7 @@ test("abort during the close drain ends the session at once", async () => { await closing; expect(served.closed()).toBe(true); } finally { - deadline.restore(); + deadline.installed.close(); served.cleanup(); } }); @@ -408,7 +408,7 @@ test("close waits for a served FETCH to be acknowledged", async () => { await closing; expect(closed).toBe(true); } finally { - deadline.restore(); + deadline.installed.close(); fin.release(); server.abort(); broadcast.close(); @@ -471,7 +471,7 @@ test("close waits for a request served while withdrawals are in flight", async ( await closing; expect(closed).toBe(true); } finally { - deadline.restore(); + deadline.installed.close(); fin.release(); client.abort(); server.abort(); diff --git a/js/net/src/lite/publisher.test.ts b/js/net/src/lite/publisher.test.ts index 396eb9e461b..ed681269627 100644 --- a/js/net/src/lite/publisher.test.ts +++ b/js/net/src/lite/publisher.test.ts @@ -914,7 +914,7 @@ test("lite draft-06: a cut dropped then re-created is not served", async () => { // stream is reset with `Old` and the group dropped. test("lite draft-06: a group stream that never completes is reset once the group goes stale", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const budget = Milli(1_000); // The track's max age caps the subscription's budget. const sub = await servedSubscription({ version: Version.DRAFT_06, startGroup: 0, maxAge: budget }); @@ -945,7 +945,7 @@ test("lite draft-06: a group stream that never completes is reset once the group expect([resp.drop.start, resp.drop.end]).toEqual([1, 1]); } finally { await sub.close(); - restore(); + installed.close(); } }); diff --git a/js/net/src/lite/refresh.test.ts b/js/net/src/lite/refresh.test.ts index ba3e9fc68eb..64091a24c69 100644 --- a/js/net/src/lite/refresh.test.ts +++ b/js/net/src/lite/refresh.test.ts @@ -10,7 +10,7 @@ import { ALPN_06, ALPN_07_WIP } from "./version.ts"; test.each([ALPN_06, ALPN_07_WIP])("refresh joins reach a browser publisher on %s", async (alpn) => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const source = new Producer(); const b = new Producer(); const broadcast = source.createBroadcast(Path.from("room")); @@ -79,6 +79,6 @@ test.each([ALPN_06, ALPN_07_WIP])("refresh joins reach a browser publisher on %s for (const origin of [b, source]) origin.close(); for (const peer of peers) peer.abort(); await clock.advance(Nano(0)); - restore(); + installed.close(); } }); diff --git a/js/net/src/lite/subscriber.test.ts b/js/net/src/lite/subscriber.test.ts index c1e371da0e8..f49b06c9bbc 100644 --- a/js/net/src/lite/subscriber.test.ts +++ b/js/net/src/lite/subscriber.test.ts @@ -2196,7 +2196,7 @@ test("announce init is the initial set", async () => { test.each(["answer", "credit"] as const)("FETCH shares the TRACK deadline while waiting for %s", async (stage) => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const { quic, streams, opened } = fakeSession(stage === "credit" ? [1] : []); const subscriber = new Subscriber(quic, Version.DRAFT_07, HopSchema.parse(1n)); let failure: unknown; @@ -2223,6 +2223,6 @@ test.each(["answer", "credit"] as const)("FETCH shares the TRACK deadline while } } finally { subscriber.close(); - restore(); + installed.close(); } }); diff --git a/js/net/src/parked-expiry.test.ts b/js/net/src/parked-expiry.test.ts index a1ac89fc8d7..d9f5ed0eb75 100644 --- a/js/net/src/parked-expiry.test.ts +++ b/js/net/src/parked-expiry.test.ts @@ -28,7 +28,7 @@ for (const protocol of protocols) { `${protocol.alpn}: a parked group open ends when its group %s`, async (mode) => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const pair = createMockTransportPair(protocol.alpn); const origin = new Origin(); const broadcast = origin.createBroadcast(Path.from("parked")); @@ -142,7 +142,7 @@ for (const protocol of protocols) { await running; opening.mockRestore(); trying.mockRestore(); - restore(); + installed.close(); } }, ); diff --git a/js/net/src/request-deadline.test.ts b/js/net/src/request-deadline.test.ts index ad3b6f53aef..fdbd50301ed 100644 --- a/js/net/src/request-deadline.test.ts +++ b/js/net/src/request-deadline.test.ts @@ -55,7 +55,7 @@ for (const protocol of ["lite", "ietf-17"] as const) { for (const mode of ["refuse", "queue", "open"] as const) { test(`${protocol}: ${mode} has one fatal request deadline`, async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const transport = limited(mode); const subscriber = protocol === "lite" @@ -94,7 +94,7 @@ for (const protocol of ["lite", "ietf-17"] as const) { track.close(); broadcast.close(); subscriber.close(); - restore(); + installed.close(); } }); } @@ -104,7 +104,7 @@ for (const legacy of [false, true]) { for (const mode of ["refuse", "queue", "open"] as const) { test(`${legacy ? "solicited draft-15" : "unsolicited draft-17"} advertisement: ${mode} is terminal`, async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const transport = limited(mode); const version = legacy ? Ietf.DRAFT_15 : Ietf.DRAFT_17; const origin = new Origin(); @@ -155,7 +155,7 @@ for (const legacy of [false, true]) { origin.close(); await loop; publisher.close(); - restore(); + installed.close(); } }); } @@ -165,7 +165,7 @@ for (const operation of ["info", "fetch"] as const) { for (const mode of ["refuse", "queue", "open"] as const) { test(`lite standalone ${operation}: ${mode} has a fatal deadline`, async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const transport = limited(mode); const subscriber = new LiteSubscriber(transport.quic, Lite.DRAFT_07, HopSchema.parse(1n)); let failure: unknown; @@ -193,7 +193,7 @@ for (const operation of ["info", "fetch"] as const) { expect(transport.options).toEqual([{ sendOrder: undefined, waitUntilAvailable: false }]); } finally { subscriber.close(); - restore(); + installed.close(); } }); } @@ -203,7 +203,7 @@ for (const protocol of ["lite", "ietf-17"] as const) { for (const mode of ["refuse", "queue", "open"] as const) { test(`${protocol} discovery: ${mode} bounds only the create`, async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const transport = limited(mode); const subscriber = protocol === "lite" @@ -228,7 +228,7 @@ for (const protocol of ["lite", "ietf-17"] as const) { } finally { announced.close(); subscriber.close(); - restore(); + installed.close(); } }); } @@ -237,7 +237,7 @@ for (const protocol of ["lite", "ietf-17"] as const) { for (const protocol of ["lite", "ietf-17"] as const) { test(`${protocol}: credit granted in the deadline task cannot send a late request`, async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const transport = limited("queue"); const subscriber = protocol === "lite" @@ -257,7 +257,7 @@ for (const protocol of ["lite", "ietf-17"] as const) { track.close(); broadcast.close(); subscriber.close(); - restore(); + installed.close(); } }); } diff --git a/js/net/src/resume.test.ts b/js/net/src/resume.test.ts index dcec3a61e7c..9f59d299523 100644 --- a/js/net/src/resume.test.ts +++ b/js/net/src/resume.test.ts @@ -106,7 +106,7 @@ async function setup() { test("returning to a route reuses its subscription and held group", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const front = new Front(); const sources = [new BroadcastProducer(), new BroadcastProducer()]; const handles = sources.map((source) => source.consume()); @@ -142,13 +142,13 @@ test("returning to a route reuses its subscription and held group", async () => front.consumer.close(); for (const handle of handles) handle.close(); for (const source of sources) source.close(); - restore(); + installed.close(); } }); test("a returning route resumes where a fresh copy would", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const front = new Front(); const sources = [new BroadcastProducer(), new BroadcastProducer()]; const handles = sources.map((source) => source.consume()); @@ -181,7 +181,7 @@ test("a returning route resumes where a fresh copy would", async () => { front.consumer.close(); for (const handle of handles) handle.close(); for (const source of sources) source.close(); - restore(); + installed.close(); } }); @@ -329,7 +329,7 @@ test("a resumed fork shares an on-demand track request", async () => { }); test("a lagging same-epoch replica resumes from one publisher's bytes exactly once", async () => { - const { clock, restore } = manual(); + const { clock, installed } = manual(); const publisher = new Producer(); const original = publisher.createBroadcast(path); original.announce({ epoch: EPOCH }); @@ -462,7 +462,7 @@ test("a lagging same-epoch replica resumes from one publisher's bytes exactly on publisher.close(); origin.close(); const outcomes = await Promise.all([a.done, b.done]); - restore(); + installed.close(); expect(outcomes).toEqual([undefined, undefined]); } }); @@ -710,7 +710,7 @@ test("datagrams a new copy replays are handed out once", async () => { test("a replacement delivers unseen datagrams below the newest sequence", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); try { const { a, b, swap, active, close } = await setup(); const ta = copy(a); @@ -728,13 +728,13 @@ test("a replacement delivers unseen datagrams below the newest sequence", async sub.close(); close(); } finally { - restore(); + installed.close(); } }); test.each([0, 100])("datagram identities stay within the reader's %p ms budget", async (budget) => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); try { const front = new Front(); const a = new BroadcastProducer(); @@ -762,7 +762,7 @@ test.each([0, 100])("datagram identities stay within the reader's %p ms budget", front.consumer.close(); a.close(); } finally { - restore(); + installed.close(); } }); @@ -1720,10 +1720,10 @@ test("the largest follows the serving copy across a swap without moving back, an b.close(); }); -/** A manual clock, installed until `restore`. */ +/** A manual clock, installed until `installed` closes. */ function manual() { const clock = new Manual(); - return { clock, restore: clock.install() }; + return { clock, installed: clock.install() }; } const SECOND = Milli(1000); @@ -1731,7 +1731,7 @@ const SECOND = Milli(1000); test.each(["lands", "dropped", "expired"])( "an arrival reader gets a group still in flight on the replaced route (%s)", async (outcome) => { - const { clock, restore } = manual(); + const { clock, installed } = manual(); const front = new Front(); const a = new BroadcastProducer(); const b = new BroadcastProducer(); @@ -1765,7 +1765,7 @@ test.each(["lands", "dropped", "expired"])( front.consumer.close(); a.close(); b.close(); - restore(); + installed.close(); } }, ); @@ -2168,7 +2168,7 @@ test("closing with an abort settles a recovery in flight with it", async () => { test.each(["lands", "expired"])( "the serving copy closing cleanly settles closed once a group the replaced copy may carry is in (%s)", async (outcome) => { - const { clock, restore } = manual(); + const { clock, installed } = manual(); const front = new Front(); const a = new BroadcastProducer(); const b = new BroadcastProducer(); @@ -2202,7 +2202,7 @@ test.each(["lands", "expired"])( front.consumer.close(); a.close(); b.close(); - restore(); + installed.close(); } }, ); diff --git a/js/net/src/tail.test.ts b/js/net/src/tail.test.ts index 53e32f1ca7d..c83f05f1372 100644 --- a/js/net/src/tail.test.ts +++ b/js/net/src/tail.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, test } from "bun:test"; -import { Manual, Milli, Nano } from "@moq/clock"; +import { type Installed, Manual, Milli, Nano } from "@moq/clock"; import { Once } from "@moq/signals"; import { accept, connect } from "./connection/index.ts"; import * as Ietf from "./ietf/index.ts"; @@ -110,13 +110,13 @@ test.each([Ietf.ALPN.DRAFT_16, Ietf.ALPN.DRAFT_17, Ietf.ALPN.DRAFT_20])( describe("Tail", () => { const GRACE = Milli(1000); - let restore: (() => void) | undefined; - afterEach(() => restore?.()); + let installed: Installed | undefined; + afterEach(() => installed?.close()); // A tail on a manual clock, with `at(ms)` moving the clock to an absolute time. function tail(grace = GRACE) { const clock = new Manual(); - restore = clock.install(); + installed = clock.install(); const at = (ms: number) => clock.jump(Nano(Nano.fromMilli(Milli(ms)) - clock.now())); return { at, clock, tail: new Tail({ grace: () => grace }) }; } diff --git a/js/net/src/track.test.ts b/js/net/src/track.test.ts index 2c961e466d1..7463b7f3a5f 100644 --- a/js/net/src/track.test.ts +++ b/js/net/src/track.test.ts @@ -25,13 +25,13 @@ function settle(): Promise { // what came due; `advance` also drains what those timers schedule. function manualTime(initial: number) { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const to = (ms: number) => Nano(Nano.fromMilli(Milli(ms)) - clock.now()); clock.jump(to(initial)); return { set: (ms: number) => clock.jump(to(ms)), advance: (ms: number) => clock.advance(to(ms)), - restore, + installed, }; } @@ -751,7 +751,7 @@ test("zero latency takes the latest group when ages are equal", async () => { expect((await track.recvGroup())?.sequence).toBe(1); } finally { - clock.restore(); + clock.installed.close(); } }); @@ -874,7 +874,7 @@ test("a stamped successor expires a group stalled before its first frame", async expect((await track.recvGroup())?.sequence).toBe(1); expect(track.recvGroup()).resolves.toBeUndefined(); } finally { - clock.restore(); + clock.installed.close(); } }); @@ -984,7 +984,7 @@ test("a handed-out group still expires while its first frame is stalled", async await expect(pending).rejects.toMatchObject({ code: StreamCode.Old }); expect(await closed).toMatchObject({ code: StreamCode.Old }); } finally { - clock.restore(); + clock.installed.close(); } }); @@ -1120,7 +1120,7 @@ test("a stalled track keeps only its newest group", () => { expect(drain(producer.subscribe({ maxDelay: Milli(1000) }))).toEqual([2]); } finally { producer.close(); - clock.restore(); + clock.installed.close(); } }); @@ -1145,7 +1145,7 @@ test("frozen timestamps still age out by wall clock", () => { expect(drain(producer.subscribe({ maxDelay: Milli(1000) }))).toEqual([2]); } finally { producer.close(); - clock.restore(); + clock.installed.close(); } }); @@ -1169,7 +1169,7 @@ test("a group shared by two tracks ages each from its own arrival", () => { } finally { first.close(); second.close(); - clock.restore(); + clock.installed.close(); } }); @@ -1187,7 +1187,7 @@ test("a startup burst ages out by media time", () => { expect(drain(producer.subscribe({ maxDelay: Milli(1500) }))).toEqual([2, 3, 4]); } finally { producer.close(); - clock.restore(); + clock.installed.close(); } }); @@ -1223,7 +1223,7 @@ test("a parked read wakes at its wall deadline", async () => { expect(await read).toMatchObject({ code: StreamCode.Old }); } finally { producer.close(); - clock.restore(); + clock.installed.close(); } } }); @@ -1250,7 +1250,7 @@ test("a run of empty groups ages out by wall clock", () => { expect(drain(producer.subscribe({ maxDelay: Milli(1000) }))).toEqual([RUN + 1]); } finally { producer.close(); - clock.restore(); + clock.installed.close(); } }); @@ -1272,7 +1272,7 @@ test("a live track retains its newest closed group through idle expiry", async ( replay.close(); } finally { producer.close(); - clock.restore(); + clock.installed.close(); } }); @@ -1299,7 +1299,7 @@ test("retention eviction surfaces as a gap for a handed-out group", async () => await expect(group.readFrame()).rejects.toThrow(TooFarBehind); } finally { - clock.restore(); + clock.installed.close(); } }); @@ -1323,7 +1323,7 @@ test("idle expiry reclaims an ended track's held mirror", async () => { await expect(group.readFrame()).rejects.toBeInstanceOf(TooFarBehind); } finally { - clock.restore(); + clock.installed.close(); } }); @@ -1348,7 +1348,7 @@ test("retention reclaims a group the publisher abandoned open", async () => { // A gap, not a clean finish: the publisher never ended this group. await expect(group.readFrame()).rejects.toBeInstanceOf(TooFarBehind); } finally { - clock.restore(); + clock.installed.close(); } }); @@ -1378,7 +1378,7 @@ test("an idle live edge ages out once a newer group arrives", async () => { ); expect(await Promise.race([read, settle().then(() => "still parked")])).toBeInstanceOf(TooFarBehind); } finally { - clock.restore(); + clock.installed.close(); } }); @@ -1400,7 +1400,7 @@ test("an abandoned open group ages out with no further write", async () => { expect(await read).toBeInstanceOf(TooFarBehind); } finally { producer.close(); - clock.restore(); + clock.installed.close(); } }); @@ -1420,7 +1420,7 @@ test("publisher maxAge does not change the idle cache deadline", async () => { expect(idle.closed.peek()).toBeInstanceOf(TooFarBehind); } finally { producer.close(); - clock.restore(); + clock.installed.close(); } } }); @@ -1446,7 +1446,7 @@ test("retention pruning preserves clean EOF for a drained mirror", async () => { expect(await group.readFrame()).toBeUndefined(); expect(await group.closed).toBeNull(); } finally { - clock.restore(); + clock.installed.close(); } }); @@ -1465,7 +1465,7 @@ test("system clock changes do not affect the latency budget", async () => { expect((await track.recvGroup())?.sequence).toBe(1); } finally { setSystemTime(); - clock.restore(); + clock.installed.close(); } }); @@ -2347,7 +2347,7 @@ test("an omitted publisher limit still ages idle groups out", async () => { after.close(); } finally { producer.close(); - clock.restore(); + clock.installed.close(); } }); @@ -2368,7 +2368,7 @@ test("a live track does not pin an aborted newest group", () => { late.close(); } finally { producer.close(); - clock.restore(); + clock.installed.close(); } }); @@ -2393,7 +2393,7 @@ test("closing a track keeps an idle newest group for subscribers to drain", asyn expect(late.tryRecvGroup()).toBeUndefined(); late.close(); } finally { - clock.restore(); + clock.installed.close(); } }); @@ -2431,7 +2431,7 @@ test("a late subscriber to a closed unlimited track is released once the cache a producer.subscribe().close(); expect(added.filter(([map, key]) => map.has(key)).length).toBe(0); } finally { - clock.restore(); + clock.installed.close(); } }); @@ -2503,7 +2503,7 @@ test("an ended track's buffered groups age out for a stale subscriber", async () else expect(stale.tryRecvGroup()).toBeUndefined(); } finally { producer.close(); - clock.restore(); + clock.installed.close(); } } }); @@ -2615,7 +2615,7 @@ test("unknown track metadata keeps presentation-time expiry until accepted", () expect(drain(producer.subscribe({ maxDelay: Milli(500) }))).toEqual([2, 3]); } finally { producer.close(); - clock.restore(); + clock.installed.close(); } }); @@ -2644,7 +2644,7 @@ test("an untimed subscriber starts at the oldest fresh group", () => { expect(drain(live)).toEqual([5]); } finally { producer.close(); - clock.restore(); + clock.installed.close(); } }); @@ -2850,7 +2850,7 @@ test("a mid-group end survives eviction and a filtered late reader", async () => reader.close(); } finally { producer.close(); - clock.restore(); + clock.installed.close(); } }); @@ -2968,7 +2968,7 @@ test("a gap is forgotten once a group above it is past the budget", () => { expect(hooks.deliveredRuns(subscriber)).toBe(1); } } finally { - time.restore(); + time.installed.close(); } }); @@ -2992,7 +2992,7 @@ test("an endless track with gaps remembers only those within the budget", () => stampGroup(producer, 2995, 2995); expect(drainGroups(subscriber)).toEqual([2995]); } finally { - time.restore(); + time.installed.close(); } }); @@ -3109,7 +3109,7 @@ test("an evicted group still bounds, and a late group below it is unverified", a expect(timestamps.has(1)).toBe(true); expect(timestamps.get(1)).toBeUndefined(); } finally { - clock.restore(); + clock.installed.close(); } }); @@ -3310,7 +3310,7 @@ for (const [waited, clean] of [ if (clean) expect(await next).toBeUndefined(); else await expect(next).rejects.toThrow("dropped"); } finally { - clock.restore(); + clock.installed.close(); } }); } @@ -3332,7 +3332,7 @@ test("an evicted group still fills a pending tail", async () => { expect(await reader.recvGroup()).toBeUndefined(); producer.close(); } finally { - clock.restore(); + clock.installed.close(); } }); diff --git a/js/net/src/util/timeout.test.ts b/js/net/src/util/timeout.test.ts index 2a278332dba..a204222eed2 100644 --- a/js/net/src/util/timeout.test.ts +++ b/js/net/src/util/timeout.test.ts @@ -12,7 +12,7 @@ test("withTimeout: rejects with TimeoutError after deadline", async () => { // never settles }); const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); try { const timed = withTimeout(pending, Nano(10), "timed out").catch((err: unknown) => err); await clock.advance(Nano(9)); @@ -20,7 +20,7 @@ test("withTimeout: rejects with TimeoutError after deadline", async () => { await clock.advance(Nano(1)); expect(await timed).toBeInstanceOf(TimeoutError); } finally { - restore(); + installed.close(); } }); diff --git a/js/publish/bench/catalog.ts b/js/publish/bench/catalog.ts index 87b7921bd10..9025987c649 100644 --- a/js/publish/bench/catalog.ts +++ b/js/publish/bench/catalog.ts @@ -91,11 +91,11 @@ console.log("tracks,viewers,catalog_publishes,subscribe_updates,unlimited_subscr for (const tracks of [1, 4, 16]) { for (const viewers of [1, 4, 16]) { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); try { await measure(tracks, viewers, clock); } finally { - restore(); + installed.close(); } } } diff --git a/js/publish/src/broadcast.test.ts b/js/publish/src/broadcast.test.ts index 4525bc96e62..e1b885461ea 100644 --- a/js/publish/src/broadcast.test.ts +++ b/js/publish/src/broadcast.test.ts @@ -232,7 +232,7 @@ test("serves no catalog until announced, so the first snapshot is the one at ann // while its media is fresh, so a viewer still catching up drains the tail, then it closes. test("stopping the announce with linger serves the finished broadcast until its media is stale", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const origin = new Origin.Producer(); try { const announce = new Signal(true); @@ -283,7 +283,7 @@ test("stopping the announce with linger serves the finished broadcast until its broadcast.close(); } finally { origin.close(); - restore(); + installed.close(); } }); @@ -568,7 +568,7 @@ test("changing maxAge publishes a new network broadcast", async () => { test("keeps the current catalog snapshot for a reconnecting viewer", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); try { const broadcast = new Broadcast({ @@ -595,7 +595,7 @@ test("keeps the current catalog snapshot for a reconnecting viewer", async () => broadcast.close(); } finally { - restore(); + installed.close(); } }); diff --git a/js/publish/src/catalog.test.ts b/js/publish/src/catalog.test.ts index 768b8caa76a..36d7c432f85 100644 --- a/js/publish/src/catalog.test.ts +++ b/js/publish/src/catalog.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, test } from "bun:test"; -import { Manual, Milli, Nano, Wall } from "@moq/clock"; +import { type Installed, Manual, Milli, Nano, Wall } from "@moq/clock"; import * as Catalog from "@moq/hang/catalog"; import * as Json from "@moq/json"; import { Track } from "@moq/net"; @@ -110,7 +110,7 @@ test("catalog producer publishes every update as a snapshot group", async () => test("catalog producer advertises the page clock from the first snapshot", async () => { const clock = new Manual(); clock.jump(Nano.fromMilli(Milli(5000))); - const restore = clock.install(); + const installed = clock.install(); const catalog = new CatalogProducer(); const effect = new Effect(); @@ -138,14 +138,14 @@ test("catalog producer advertises the page clock from the first snapshot", async expect(second.clock).toEqual(first.clock); effect.close(); - restore(); + installed.close(); }); test("catalog producer omits the clock when the page's wall clock is unset", async () => { // A device booted before it synced its clock: the page began in 1970. const clock = new Manual(); clock.stepWall(Wall(86_400_000)); - const restore = clock.install(); + const installed = clock.install(); try { const catalog = new CatalogProducer(); catalog.mutate((c) => { @@ -160,7 +160,7 @@ test("catalog producer omits the clock when the page's wall clock is unset", asy expect(await group?.readJson()).toEqual({ video: { renditions: {} } }); effect.close(); } finally { - restore(); + installed.close(); } }); @@ -334,16 +334,16 @@ for (const section of ["json", "binary"] as const) { describe("estimate publication window", () => { let clock = new Manual(); - let restore: (() => void) | undefined; + let installed: Installed | undefined; const scopes: Effect[] = []; const advance = (ms: number) => clock.advance(Nano.fromMilli(Milli(ms))); afterEach(() => { for (const scope of scopes.splice(0)) scope.close(); - restore?.(); + installed?.close(); }); function fixture() { clock = new Manual(); - restore = clock.install(); + installed = clock.install(); const producer = new CatalogProducer(); producer.mutate((catalog) => { catalog.video = { renditions: { v: { codec: "avc1.640028", container: { kind: "legacy" } } } }; diff --git a/js/publish/src/source/retry.test.ts b/js/publish/src/source/retry.test.ts index 69f04185018..f2487d61b4d 100644 --- a/js/publish/src/source/retry.test.ts +++ b/js/publish/src/source/retry.test.ts @@ -178,7 +178,8 @@ function published(media: Media | undefined): unknown { function fakeTime(): Manual & Disposable { const clock = new Manual(); - return Object.assign(clock, { [Symbol.dispose]: clock.install() }); + const installed = clock.install(); + return Object.assign(clock, { [Symbol.dispose]: () => installed.close() }); } for (const [kind, create] of [ diff --git a/js/publish/src/video/capture.test.ts b/js/publish/src/video/capture.test.ts index f5ef717ff36..014e613229d 100644 --- a/js/publish/src/video/capture.test.ts +++ b/js/publish/src/video/capture.test.ts @@ -297,7 +297,7 @@ test("a reader attaching to a frame held late still starts at now", async () => test("a replay never starts below an earlier replay", async () => { using input = frameSource(); const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const advance = (ms: number) => clock.jump(Nano.fromMilli(Milli(ms))); const capture = new Capture({ source: input.source }); const watch = new Effect(); @@ -336,7 +336,7 @@ test("a replay never starts below an earlier replay", async () => { watch.close(); second.close(); capture.close(); - restore(); + installed.close(); } expect(open()).toEqual([]); diff --git a/js/publish/src/video/encoder-stall.test.ts b/js/publish/src/video/encoder-stall.test.ts index cc31119b82f..323cbfa23e3 100644 --- a/js/publish/src/video/encoder-stall.test.ts +++ b/js/publish/src/video/encoder-stall.test.ts @@ -95,7 +95,7 @@ test("a slower-than-realtime encoder drops input instead of ratcheting catalog l SlowEncoder.instances = []; Input.all = []; const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); let controller!: ReadableStreamDefaultController; const fanout = new Fanout( new ReadableStream({ @@ -164,7 +164,7 @@ test("a slower-than-realtime encoder drops input instead of ratcheting catalog l fanout.close(); track.close(); await clock.advance(Nano.zero); - restore(); + installed.close(); for (const [index, name] of ["VideoEncoder", "VideoFrame"].entries()) { const original = originals[index]; if (original) Object.defineProperty(globalThis, name, original); diff --git a/js/publish/src/video/encoder.test.ts b/js/publish/src/video/encoder.test.ts index 67217c74fea..40321b6a9e4 100644 --- a/js/publish/src/video/encoder.test.ts +++ b/js/publish/src/video/encoder.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; -import { Manual, Milli, Nano, sleep } from "@moq/clock"; +import { type Installed, Manual, Milli, Nano, sleep } from "@moq/clock"; import * as Catalog from "@moq/hang/catalog"; import * as Container from "@moq/hang/container"; import * as Json from "@moq/json"; @@ -13,12 +13,12 @@ import { Encoder } from "./encoder"; const PROBE = Nano.fromMilli(Milli(5)); let clock = new Manual(); -let restore = () => {}; +let installed: Installed | undefined; beforeEach(() => { clock = new Manual(); - restore = clock.install(); + installed = clock.install(); }); -afterEach(() => restore()); +afterEach(() => installed?.close()); class FakeVideoEncoder { static instances: FakeVideoEncoder[] = []; diff --git a/js/qmux/src/session.test.ts b/js/qmux/src/session.test.ts index d65845af301..7d6112c10dc 100644 --- a/js/qmux/src/session.test.ts +++ b/js/qmux/src/session.test.ts @@ -702,7 +702,7 @@ describe("Session integration (scripted peer)", () => { test("keep-alives don't pile up behind a wedged socket", async () => { const clock = new Manual(); - const uninstall = clock.install(); + const installed = clock.install(); try { const { session, peer } = connect({ maxIdleTimeout: 300n }); await session.ready; @@ -726,7 +726,7 @@ describe("Session integration (scripted peer)", () => { expect(peer.has("connection_close")).toBe(false); session.close(); } finally { - uninstall(); + installed.close(); } }); @@ -985,7 +985,7 @@ describe("Session integration (scripted peer)", () => { // with { closeCode: 0, reason: "" }. A dead peer and a clean shutdown differed // only by a free-text string. const clock = new Manual(); - const uninstall = clock.install(); + const installed = clock.install(); try { const { session, peer } = connect({ maxIdleTimeout: 150n }); await session.ready; @@ -1016,13 +1016,13 @@ describe("Session integration (scripted peer)", () => { expect(err.message).toContain("idle timeout"); peer.unblockWrites(); } finally { - uninstall(); + installed.close(); } }); test("a peer that never sends its parameters still idles out", async () => { const clock = new Manual(); - const uninstall = clock.install(); + const installed = clock.install(); try { const { session, peer } = connect({ maxIdleTimeout: 150n }); await session.ready; @@ -1033,13 +1033,13 @@ describe("Session integration (scripted peer)", () => { expect(err.message).toContain("idle timeout"); expect(peer.has("ping_request")).toBe(false); } finally { - uninstall(); + installed.close(); } }); test("outbound frame activity resets the idle timeout", async () => { const clock = new Manual(); - const uninstall = clock.install(); + const installed = clock.install(); try { const { session, peer } = connect({ maxIdleTimeout: 120n }); await session.ready; @@ -1063,7 +1063,7 @@ describe("Session integration (scripted peer)", () => { session.close(); expect(await session.closed).toEqual({ closeCode: 0, reason: "" }); } finally { - uninstall(); + installed.close(); } }); @@ -1073,7 +1073,7 @@ describe("Session integration (scripted peer)", () => { // clock, so counting every send as activity left the deadline permanently // in the future and the session never closed. const clock = new Manual(); - const uninstall = clock.install(); + const installed = clock.install(); try { const { session, peer } = connect({ maxIdleTimeout: 120n }); await session.ready; @@ -1094,7 +1094,7 @@ describe("Session integration (scripted peer)", () => { const err = await expectSessionFailure(session); expect(err.message).toContain("idle timeout"); } finally { - uninstall(); + installed.close(); } }); diff --git a/js/room/src/chat.test.ts b/js/room/src/chat.test.ts index ef8b3210b92..4b342004491 100644 --- a/js/room/src/chat.test.ts +++ b/js/room/src/chat.test.ts @@ -5,7 +5,7 @@ import { HISTORY, info, Publisher, Subscriber, TRACK } from "./chat.ts"; test("chat expires ten-second history and late readers only see retained messages", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const broadcast = new Broadcast.Producer(); const publisher = Publisher.create(broadcast); const subscriber = Subscriber.subscribe(broadcast.consume()); @@ -31,7 +31,7 @@ test("chat expires ten-second history and late readers only see retained message publisher.finish(); subscriber.close(); broadcast.close(); - restore(); + installed.close(); } }); diff --git a/js/signals/src/index.test.ts b/js/signals/src/index.test.ts index 76a38cc05cc..d6fdeff3b5a 100644 --- a/js/signals/src/index.test.ts +++ b/js/signals/src/index.test.ts @@ -1,5 +1,5 @@ import { describe, expect, spyOn, test } from "bun:test"; -import { Manual, Milli, Nano, now, Second } from "@moq/clock"; +import { type Installed, Manual, Milli, Nano, now, Second } from "@moq/clock"; import { Computed, type Dispose, Effect, type GetPromise, Once, race, Signal } from "./index.ts"; const NO_SUBSCRIPTION_WARNING = "Effect did not subscribe to any signals; it will never rerun."; @@ -554,7 +554,7 @@ describe("Effect", () => { let immediate: boolean | undefined; const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const warn = spyOn(console, "warn").mockImplementation(() => {}); const effect = new Effect((e) => { @@ -601,7 +601,7 @@ describe("Effect", () => { expect(runs).toBe(2); } finally { effect.close(); - restore(); + installed.close(); warn.mockRestore(); } }); @@ -615,7 +615,7 @@ describe("Effect", () => { const never = Promise.withResolvers(); // deliberately never resolved const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const warn = spyOn(console, "warn").mockImplementation(() => {}); const effect = new Effect((e) => { @@ -639,7 +639,7 @@ describe("Effect", () => { expect(warned).toBe(false); } finally { effect.close(); - restore(); + installed.close(); warn.mockRestore(); } }); @@ -856,7 +856,7 @@ describe("Effect", () => { test("timer, timeout, and interval run on the installed clock until cleanup", async () => { const ms = (value: number) => Nano.fromMilli(Milli(value)); const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const fired: string[] = []; const effect = new Effect(); try { @@ -880,7 +880,7 @@ describe("Effect", () => { expect(fired).toEqual(["tick", "timeout", "tick", "timer"]); } finally { effect.close(); - restore(); + installed.close(); } }); }); @@ -1417,7 +1417,7 @@ test("races from another package copy release their source listeners", async () test("an effect interval arms its first period synchronously and steps subsequent periods", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const effect = new Effect(); const at: number[] = []; try { @@ -1429,7 +1429,7 @@ test("an effect interval arms its first period synchronously and steps subsequen expect(at).toEqual([10, 20, 30, 40]); } finally { effect.close(); - restore(); + installed.close(); } }); @@ -1444,7 +1444,7 @@ test("an effect interval refuses a zero period synchronously", () => { test("an effect interval delays a full period after a stalled event loop", async () => { const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const effect = new Effect(); const at: number[] = []; try { @@ -1458,22 +1458,22 @@ test("an effect interval delays a full period after a stalled event loop", async expect(at).toEqual([35, 45]); } finally { effect.close(); - restore(); + installed.close(); } }); test("an effect interval starts its next period on a newly installed clock's origin", async () => { const first = new Manual(); first.jump(Nano(1000)); - const restoreFirst = first.install(); + const installedFirst = first.install(); const second = new Manual(); - let restoreSecond: (() => void) | undefined; + let installedSecond: Installed | undefined; const effect = new Effect(); const at: number[] = []; try { effect.interval(() => { at.push(now()); - if (at.length === 1) restoreSecond = second.install(); + if (at.length === 1) installedSecond = second.install(); }, Nano(10)); await first.advance(Nano(10)); expect(at).toEqual([1010]); @@ -1481,7 +1481,7 @@ test("an effect interval starts its next period on a newly installed clock's ori expect(at).toEqual([1010, 10]); } finally { effect.close(); - restoreSecond?.(); - restoreFirst(); + installedSecond?.close(); + installedFirst.close(); } }); diff --git a/js/watch/src/audio/decoder.test.ts b/js/watch/src/audio/decoder.test.ts index 9426b55a095..1d12628401c 100644 --- a/js/watch/src/audio/decoder.test.ts +++ b/js/watch/src/audio/decoder.test.ts @@ -672,8 +672,7 @@ describe("fatal decoder errors", () => { function manualAt(ms: number) { const clock = new Manual(); clock.jump(Nano.fromMilli(Milli(ms))); - const restore = clock.install(); - return { advance: (by: number) => clock.advance(Nano.fromMilli(Milli(by))), restore }; + return { advance: (by: number) => clock.advance(Nano.fromMilli(Milli(by))), installed: clock.install() }; } // A legacy container frame: the media timestamp, then one payload byte. @@ -783,7 +782,7 @@ async function livePlayback(burst: number) { media.peek().close(); producer.close(); await microtasks(); - clock.restore(); + clock.installed.close(); }, }; } diff --git a/js/watch/src/audio/replay.ts b/js/watch/src/audio/replay.ts index 41a61ab4261..113dc621835 100644 --- a/js/watch/src/audio/replay.ts +++ b/js/watch/src/audio/replay.ts @@ -243,7 +243,7 @@ export async function* replay(trace: Arrival[], options: Options): AsyncGenerato const moveTo = (ms: number) => manual.jump(Nano(Nano.fromMilli(Milli(ms)) - manual.now())); let clock = first.at; moveTo(clock); - const restore = manual.install(); + const installed = manual.install(); try { for (let n = 1; first.at + (n - 1) * step <= end; n++) { @@ -311,6 +311,6 @@ export async function* replay(trace: Arrival[], options: Options): AsyncGenerato await decode; signals.close(); sync.close(); - restore(); + installed.close(); } } diff --git a/js/watch/src/sync.test.ts b/js/watch/src/sync.test.ts index 8e7a53b30c9..4ab26c5f098 100644 --- a/js/watch/src/sync.test.ts +++ b/js/watch/src/sync.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it } from "bun:test"; -import { Manual, Milli, Nano, now } from "@moq/clock"; +import { type Installed, Manual, Milli, Nano, now } from "@moq/clock"; import { Signal } from "@moq/signals"; import { type Delay, Sync } from "./sync"; @@ -123,13 +123,13 @@ describe("auto delay", () => { describe("wait", () => { // Sleeps run on a manual clock, so a parked wait only wakes on what the test changes. - let restore: () => void; + let installed: Installed; beforeEach(() => { const clock = new Manual(); clock.jump(Nano.fromMilli(Milli(1000))); - restore = clock.install(); + installed = clock.install(); }); - afterEach(() => restore()); + afterEach(() => installed.close()); const nowMs = () => Nano.toMilli(Nano(now())); it("returns at once when constructed instant, before effects flush", async () => { @@ -214,7 +214,7 @@ describe("recorded ingress", () => { it("anchors and classifies using arrival rather than delayed delivery", async () => { const clock = new Manual(); clock.jump(Nano.fromMilli(Milli(10_000))); - const restore = clock.install(); + const installed = clock.install(); const sync = new Sync({ delay: Milli(100) }); try { for (let i = 0; i < 20; i++) await Promise.resolve(); @@ -223,7 +223,7 @@ describe("recorded ingress", () => { expect(sync.received(Milli(20), "audio", Milli(1020))).toBe(false); expect(sync.received(Milli(40), "audio", Milli(1200))).toBe(true); } finally { - restore(); + installed.close(); sync.close(); } }); @@ -232,13 +232,13 @@ describe("recorded ingress", () => { describe("skip floor", () => { // Arrivals are on the local clock, pinned here so a skip's playhead does not depend on wall time. let clock: Manual; - let restore: () => void; + let installed: Installed; beforeEach(() => { clock = new Manual(); clock.jump(Nano.fromMilli(Milli(5000))); - restore = clock.install(); + installed = clock.install(); }); - afterEach(() => restore()); + afterEach(() => installed.close()); it("a skip passes over only frames behind the playhead it jumped to", async () => { const sync = new Sync({ delay: Milli(100) }); diff --git a/js/watch/src/video/decoder.test.ts b/js/watch/src/video/decoder.test.ts index 9e66ac0a2b3..1ffbce29bf2 100644 --- a/js/watch/src/video/decoder.test.ts +++ b/js/watch/src/video/decoder.test.ts @@ -182,8 +182,7 @@ type Read = Container.Read; function manualAt(ms: number) { const clock = new Manual(); clock.jump(Nano.fromMilli(Milli(ms))); - const restore = clock.install(); - return { advance: (by: number) => clock.advance(Nano.fromMilli(Milli(by))), restore }; + return { advance: (by: number) => clock.advance(Nano.fromMilli(Milli(by))), installed: clock.install() }; } function sample(group: number, timestamp: number, keyframe = true): Read { return { @@ -500,7 +499,7 @@ for (const kind of ["legacy", "cmaf"] as const) { } finally { playback.close(); await microtasks(); - clock.restore(); + clock.installed.close(); } } @@ -730,7 +729,7 @@ it("a shared audio clock reset cannot present a parked video frame", async () => } finally { playback.close(); await microtasks(); - clock.restore(); + clock.installed.close(); } }); @@ -764,7 +763,7 @@ it("closing the track releases a video wait parked across a reset", async () => wait.mockRestore(); playback.close(); await microtasks(); - clock.restore(); + clock.installed.close(); } }); @@ -790,7 +789,7 @@ it("a reset drops a parked video frame even when the next anchor restores the re } finally { playback.close(); await microtasks(); - clock.restore(); + clock.installed.close(); } }); @@ -933,7 +932,7 @@ it("a renamed video track keeps the delay, so audio neither skips nor goes silen follow.close(); playback.close(); await microtasks(); - clock.restore(); + clock.installed.close(); } }); @@ -965,6 +964,6 @@ it("a video track read from another path does not inherit the outgoing delay", a } finally { playback.close(); await microtasks(); - clock.restore(); + clock.installed.close(); } }); diff --git a/quest/m1/api-audit/README.md b/quest/m1/api-audit/README.md index a223e5ad187..347a7cbfb09 100644 --- a/quest/m1/api-audit/README.md +++ b/quest/m1/api-audit/README.md @@ -94,7 +94,6 @@ Rejected in planning: - [qmux shape](/quest/m1/api-audit/qmux-shape.md) - qmux binds framing at connect, shares flow-control names with moq-tokio, and JS drops the legacy wire - [Transport config](/quest/m1/api-audit/transport-config.md) - moq-tokio and moq-quic configs have one meaning for unset, enums for modes, no order-dependent setters, and no leftover features - [Relay config](/quest/m1/api-audit/relay-config.md) - moq-relay and its embedders load config through one path that refuses old spellings, under names that do not collide -- [Auth and clock names](/quest/m1/api-audit/auth-clock-names.md) - refusal and reason types have distinct names, and the Rust and JS clocks mirror each other ## Related diff --git a/quest/m1/api-audit/auth-clock-names.md b/quest/m1/api-audit/auth-clock-names.md deleted file mode 100644 index 67761ba24bd..00000000000 --- a/quest/m1/api-audit/auth-clock-names.md +++ /dev/null @@ -1,23 +0,0 @@ -# [S] Auth and clock names - -## Goal - -Refusal and reason types have distinct names across moq-auth and moq-net, -and moq-clock and `@moq/clock` mirror each other's names and shapes. - -## Plan - -Decided 2026-10-22 (API audit): - -- "Refusal" names three things (`moq_auth::Refusal`, the policy enum - `moq_auth::serve::Refusal`, `moq_net::stats::Refusal`) and "Reason" two - (`refusal::Reason`, `lease::Reason`). Rename the policy enum - `serve::Denial` and the stats one `RefusalKind`, or similar. -- Rust `moq_clock::anchor() -> (Instant, Wall)` (ns) versus JS - `origin(): Wall` (ms): name both `origin()` and document the unit split. - Rust `Manual::install` returns a handle while JS returns a closure: match. -- moq-net exposes both `time::now()` and `Instant::now()`; keep one. -- moq-auth's public times (`Claims`, `Grant::expires`) are `SystemTime`; - add them to [wall time](/quest/m1/time/wall.md). - -Public API: moq-auth, moq-net, moq-clock, `@moq/clock` renames. Wire: none. diff --git a/quest/m1/time/wall.md b/quest/m1/time/wall.md index 8e0ba847691..c3dcfa5ef43 100644 --- a/quest/m1/time/wall.md +++ b/quest/m1/time/wall.md @@ -21,6 +21,8 @@ The remaining public `SystemTime`s, as of - moq-quic: `TimeSource::now` and the token log's issue times. - moq-relay: the session's `started`. - moq-tokio: the certificate `expiry`. +- moq-auth: `Claims::{expires, issued, not_before}` with their `with_*` + setters, and `Grant::expires`. - moq-cli and moq-bench: private wall times, which can move freely. `Wall` covers 1970 to 2554, so a catalog wall past that range is an error, as @@ -39,7 +41,7 @@ representation limit into a validity rule for valid identities. Presentation walls (catalogs, timelines, HLS) still refuse, since their value is shown or used for arithmetic, not only compared. -Public API: breaking in hang, moq-mux, moq-hls, moq-quic, moq-relay, and +Public API: breaking in hang, moq-mux, moq-hls, moq-quic, moq-relay, moq-auth, and moq-tokio, each with a `MIGRATE.md` entry. Wire: none. ## Related diff --git a/rs/moq-audio/src/decode/consumer.rs b/rs/moq-audio/src/decode/consumer.rs index c39554a5641..d0a0e9040e5 100644 --- a/rs/moq-audio/src/decode/consumer.rs +++ b/rs/moq-audio/src/decode/consumer.rs @@ -782,7 +782,7 @@ mod tests { tokio::join!( async { let (session, driver) = client - .connect_lite(moq_net::time::now(), client_transport) + .connect_lite(moq_net::time::Instant::now(), client_transport) .await .unwrap(); tokio::spawn(moq_net::time::run(driver)); @@ -790,7 +790,7 @@ mod tests { }, async { let (session, driver) = server - .accept_lite(moq_net::time::now(), server_transport) + .accept_lite(moq_net::time::Instant::now(), server_transport) .await .unwrap(); tokio::spawn(moq_net::time::run(driver)); diff --git a/rs/moq-audio/src/encode/producer.rs b/rs/moq-audio/src/encode/producer.rs index 5968c94baa6..f9f36aad667 100644 --- a/rs/moq-audio/src/encode/producer.rs +++ b/rs/moq-audio/src/encode/producer.rs @@ -440,7 +440,7 @@ impl Producer { if self.grouped >= self.group_samples { self.track.cut(None)?; } - self.track.flush(timestamp, moq_net::time::now())?; + self.track.flush(timestamp, moq_net::time::Instant::now())?; Ok(()) } @@ -466,7 +466,7 @@ impl Producer { keyframe: false, duration: None, })?; - track.flush(timestamp, moq_net::time::now())?; + track.flush(timestamp, moq_net::time::Instant::now())?; } track.cut(Some(terminal.end))?; diff --git a/rs/moq-auth/MIGRATE.md b/rs/moq-auth/MIGRATE.md index e2d2074bd04..3a6c165cdf4 100644 --- a/rs/moq-auth/MIGRATE.md +++ b/rs/moq-auth/MIGRATE.md @@ -4,6 +4,11 @@ How to update your code for each breaking change, newest first. ## Unreleased +### `serve::Refusal` is `serve::Denial` (#6510) + +The reference server's policy failure is `serve::Denial`, so `Refusal` names only the shared 403 body, `moq_auth::Refusal`. +Rename `serve::Refusal` to `serve::Denial`; its variants are unchanged, and `Policy::decide` and `Server::answer` return it. + ### `Client::connect` has no timeout of its own (#5765) `Client::connect` waits on the auth server for as long as its caller does, and dropping the future drops the request. diff --git a/rs/moq-auth/src/serve.rs b/rs/moq-auth/src/serve.rs index ac40d8399a6..ca5fbf4b746 100644 --- a/rs/moq-auth/src/serve.rs +++ b/rs/moq-auth/src/serve.rs @@ -101,10 +101,10 @@ pub struct Policy { pub limits: Limits, } -/// The policy failure mapped to the typed refusal in the 403 body. +/// Why the policy denied a session, mapped to the typed [`Refusal`](crate::Refusal) in the 403 body. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] #[non_exhaustive] -pub enum Refusal { +pub enum Denial { /// No keys are configured, so no token can be verified. #[error("no keys are configured, so a token cannot be verified")] NoKeys, @@ -174,7 +174,7 @@ pub enum Refusal { }, } -impl Refusal { +impl Denial { /// The shared refusal contract, with attribution only from a verified token. fn body(&self, tier: Option) -> crate::Refusal { use crate::refusal::Reason; @@ -194,37 +194,37 @@ impl Refusal { impl Policy { /// Decide `request` by the policy alone, ignoring session limits. - pub async fn decide(&self, request: &Request) -> Result { + pub async fn decide(&self, request: &Request) -> Result { Ok(self.decide_root(request).await?.0) } - async fn decide_root(&self, request: &Request) -> Result<(Grant, Option), Refusal> { + async fn decide_root(&self, request: &Request) -> Result<(Grant, Option), Denial> { let jwt = jwt(request)?; if jwt.is_some() && request.tls.is_some() { - return Err(Refusal::TokenAndCertificate); + return Err(Denial::TokenAndCertificate); } let (permissions, expires, certificate, root) = if let Some(jwt) = jwt { let claims = self.verify(&jwt).await?; let permissions = claims.authorize(&request.path).map_err(|err| match err { - crate::Error::RootMismatch(path) => Refusal::RootMismatch { + crate::Error::RootMismatch(path) => Denial::RootMismatch { root: claims.root.clone(), path, }, - crate::Error::NoAccess(path) => Refusal::NoAccess { + crate::Error::NoAccess(path) => Denial::NoAccess { path, root: Some(claims.root.clone()), }, - other => Refusal::InvalidToken(other.to_string()), + other => Denial::InvalidToken(other.to_string()), })?; (permissions, claims.expires, false, Some(claims.root)) } else if let Some(peer) = &request.tls { if self.mtls.is_empty() { - return Err(Refusal::NoMtlsGrant); + return Err(Denial::NoMtlsGrant); } (authorize(&self.mtls, &request.path)?, peer.expires, true, None) } else { if self.public.is_empty() { - return Err(Refusal::NoPublicGrant); + return Err(Denial::NoPublicGrant); } (authorize(&self.public, &request.path)?, None, false, None) }; @@ -235,7 +235,7 @@ impl Policy { (None, Some(bound)) => Some( SystemTime::from(moq_clock::wall()) .checked_add(bound) - .ok_or(Refusal::ExpiresOutOfRange)?, + .ok_or(Denial::ExpiresOutOfRange)?, ), (None, None) => None, }; @@ -246,40 +246,40 @@ impl Policy { Ok((grant, root)) } - async fn verify(&self, jwt: &str) -> Result { - let keys = self.keys.as_ref().ok_or(Refusal::NoKeys)?; + async fn verify(&self, jwt: &str) -> Result { + let keys = self.keys.as_ref().ok_or(Denial::NoKeys)?; let claims = match keys { Keys::File(path) => Key::from_file_async(path) .await - .map_err(|_| Refusal::UnknownKey)? + .map_err(|_| Denial::UnknownKey)? .verify_claims(jwt), Keys::Dir(dir) => { - let header = jsonwebtoken::decode_header(jwt).map_err(|err| Refusal::InvalidToken(err.to_string()))?; - let kid = header.kid.ok_or(Refusal::MissingKeyId)?; - let kid = KeyId::decode(&kid).map_err(|_| Refusal::UnknownKey)?; + let header = jsonwebtoken::decode_header(jwt).map_err(|err| Denial::InvalidToken(err.to_string()))?; + let kid = header.kid.ok_or(Denial::MissingKeyId)?; + let kid = KeyId::decode(&kid).map_err(|_| Denial::UnknownKey)?; Key::from_file_async(dir.join(format!("{kid}.jwk"))) .await - .map_err(|_| Refusal::UnknownKey)? + .map_err(|_| Denial::UnknownKey)? .verify_claims(jwt) } Keys::Set(path) => { - let json = tokio::fs::read_to_string(path).await.map_err(|_| Refusal::UnknownKey)?; + let json = tokio::fs::read_to_string(path).await.map_err(|_| Denial::UnknownKey)?; KeySet::from_str(&json) - .map_err(|err| Refusal::InvalidToken(err.to_string()))? + .map_err(|err| Denial::InvalidToken(err.to_string()))? .key(jwt) .and_then(|key| key.verify_claims(jwt)) } }; let claims = claims.map_err(|err| match err { - crate::Error::Key(crate::KeyError::MissingKid) => Refusal::MissingKeyId, - crate::Error::Key(crate::KeyError::KeyNotFound(_)) => Refusal::UnknownKey, - other => Refusal::InvalidToken(other.to_string()), + crate::Error::Key(crate::KeyError::MissingKid) => Denial::MissingKeyId, + crate::Error::Key(crate::KeyError::KeyNotFound(_)) => Denial::UnknownKey, + other => Denial::InvalidToken(other.to_string()), })?; crate::key::validate_times(&claims, SystemTime::from(moq_clock::wall())).map_err(|err| match err { - crate::Error::TokenExpired => Refusal::Expired { + crate::Error::TokenExpired => Denial::Expired { root: claims.root.clone(), }, - other => Refusal::InvalidToken(other.to_string()), + other => Denial::InvalidToken(other.to_string()), })?; Ok(claims) } @@ -287,14 +287,14 @@ impl Policy { /// Authorize rules rooted at `/` at the dialed `path`, exactly as a token with an /// empty root would be. -fn authorize(rules: &Permissions, path: &str) -> Result { +fn authorize(rules: &Permissions, path: &str) -> Result { let claims = crate::Claims { publish: rules.publish.clone(), subscribe: rules.subscribe.clone(), ..Default::default() }; // An empty root overlaps every path, so the only refusal is reaching nothing. - claims.authorize(path).map_err(|_| Refusal::NoAccess { + claims.authorize(path).map_err(|_| Denial::NoAccess { path: crate::path::normalize(path), root: None, }) @@ -302,16 +302,16 @@ fn authorize(rules: &Permissions, path: &str) -> Result { /// The JWT the request presents: its SETUP token, or else its `jwt` query parameter. /// Both at once count as one only when they are the same JWT. -fn jwt(request: &Request) -> Result>, Refusal> { +fn jwt(request: &Request) -> Result>, Denial> { match (&request.token, query_jwt(request)?) { // A client that offers a version without in-band auth copies its SETUP token // into the URL too, so the same JWT arrives twice. (Some(token), Some(jwt)) if token.kind == Token::OUT_OF_BAND && token.value == jwt.as_bytes() => Ok(Some(jwt)), - (Some(_), Some(_)) => Err(Refusal::TwoTokens), + (Some(_), Some(_)) => Err(Denial::TwoTokens), (Some(token), None) if token.kind == Token::OUT_OF_BAND => std::str::from_utf8(&token.value) .map(|jwt| Some(jwt.into())) - .map_err(|_| Refusal::InvalidToken("the SETUP token is not UTF-8".into())), - (Some(token), None) => Err(Refusal::UnsupportedToken(token.kind)), + .map_err(|_| Denial::InvalidToken("the SETUP token is not UTF-8".into())), + (Some(token), None) => Err(Denial::UnsupportedToken(token.kind)), (None, jwt) => Ok(jwt), } } @@ -319,11 +319,11 @@ fn jwt(request: &Request) -> Result>, Refusal> { /// The `jwt` query parameter, percent-decoded, when the request carries a non-empty /// one. A second `jwt` key, even an empty or escaped one, is refused rather than /// picking a winner. Decoding is a no-op on a well-formed JWT, which is base64url and dots. -fn query_jwt(request: &Request) -> Result>, Refusal> { +fn query_jwt(request: &Request) -> Result>, Denial> { let mut jwt = None; for (key, value) in url::form_urlencoded::parse(request.query.as_deref().unwrap_or_default().as_bytes()) { if key == "jwt" && jwt.replace(value).is_some() { - return Err(Refusal::DuplicateJwt); + return Err(Denial::DuplicateJwt); } } Ok(jwt.filter(|jwt| !jwt.is_empty())) @@ -359,7 +359,7 @@ impl Sessions { /// Admit a `connect`, refusing over the cap. A known id is the same session /// attaching another credential: it holds no new remote slot, but a JWT new to /// it counts against that JWT's cap until the session ends. - fn connect(&mut self, request: &Request, limits: Limits, root: Option) -> Result<(), Refusal> { + fn connect(&mut self, request: &Request, limits: Limits, root: Option) -> Result<(), Denial> { // Decided before counting, so the credential is already known to be one JWT. let token = jwt(request).ok().flatten().as_deref().map(hash); let known = self.slots.get(&request.id); @@ -367,7 +367,7 @@ impl Sessions { if let (Some(cap), Some(token)) = (limits.token, new_token) && self.slots.values().filter(|slot| slot.tokens.contains(&token)).count() >= cap { - return Err(Refusal::TokenLimit { root }); + return Err(Denial::TokenLimit { root }); } if let Some(slot) = self.slots.get_mut(&request.id) { slot.tokens.extend(new_token); @@ -378,7 +378,7 @@ impl Sessions { if let (Some(cap), Some(remote)) = (limits.remote, remote) && self.slots.values().filter(|slot| slot.remote == Some(remote)).count() >= cap { - return Err(Refusal::RemoteLimit { root }); + return Err(Denial::RemoteLimit { root }); } self.slots.insert( request.id.clone(), @@ -465,7 +465,7 @@ impl Server { } /// Answer one event: the grant, or why the session is refused. - pub async fn answer(&self, request: &Request) -> Result, Refusal> { + pub async fn answer(&self, request: &Request) -> Result, Denial> { match request.event { Event::Connect => { let (grant, root) = self.policy.decide_root(request).await?; @@ -515,9 +515,9 @@ async fn handle(State(server): State, Json(request): Json) -> R Ok(None) => StatusCode::NO_CONTENT.into_response(), // The reason rides in the body, so an operator reading the relay's log knows // which rule refused without the server saying anything to the client. - Err(refusal) => { - tracing::debug!(id = %request.id, path = %request.path, %refusal, "refused"); - (StatusCode::FORBIDDEN, Json(refusal.body(server.policy.tier.clone()))).into_response() + Err(denial) => { + tracing::debug!(id = %request.id, path = %request.path, %denial, "refused"); + (StatusCode::FORBIDDEN, Json(denial.body(server.policy.tier.clone()))).into_response() } } } @@ -670,11 +670,11 @@ mod tests { assert_eq!(grant.subscribe, patterns(&["**"]).into()); let err = policy.decide(&with_token(request("/other"), &jwt)).await.unwrap_err(); - assert!(matches!(err, Refusal::RootMismatch { .. }), "{err}"); + assert!(matches!(err, Denial::RootMismatch { .. }), "{err}"); let jwt = sign(&key, "", &[], &["demo/**"], None); let err = policy.decide(&with_token(request("/other"), &jwt)).await.unwrap_err(); - assert!(matches!(err, Refusal::NoAccess { .. }), "{err}"); + assert!(matches!(err, Denial::NoAccess { .. }), "{err}"); } #[tokio::test] @@ -695,38 +695,38 @@ mod tests { Some(SystemTime::now() - Duration::from_secs(1)), ); let err = policy.decide(&with_token(request("/demo"), &jwt)).await.unwrap_err(); - assert!(matches!(err, Refusal::Expired { .. }), "{err}"); + assert!(matches!(err, Denial::Expired { .. }), "{err}"); // Signed by a stranger. let stranger = Key::generate(Algorithm::HS256, Some(KeyId::decode("kid1").unwrap())).unwrap(); let jwt = sign(&stranger, "demo", &["**"], &[], None); let err = policy.decide(&with_token(request("/demo"), &jwt)).await.unwrap_err(); - assert!(matches!(err, Refusal::InvalidToken(_)), "{err}"); + assert!(matches!(err, Denial::InvalidToken(_)), "{err}"); // Unknown kid, and no kid at all. let other = Key::generate(Algorithm::HS256, Some(KeyId::decode("kid2").unwrap())).unwrap(); let jwt = sign(&other, "demo", &["**"], &[], None); assert_eq!( policy.decide(&with_token(request("/demo"), &jwt)).await.unwrap_err(), - Refusal::UnknownKey + Denial::UnknownKey ); let bare = Key::generate(Algorithm::HS256, None).unwrap(); let jwt = sign(&bare, "demo", &["**"], &[], None); assert_eq!( policy.decide(&with_token(request("/demo"), &jwt)).await.unwrap_err(), - Refusal::MissingKeyId + Denial::MissingKeyId ); // Garbage, and a token with no keys configured at all. let err = policy.decide(&with_token(request("/demo"), "nope")).await.unwrap_err(); - assert!(matches!(err, Refusal::InvalidToken(_)), "{err}"); + assert!(matches!(err, Denial::InvalidToken(_)), "{err}"); let keyless = Policy { public: rules(&["**"], &["**"]), ..Default::default() }; assert_eq!( keyless.decide(&with_token(request("/demo"), &jwt)).await.unwrap_err(), - Refusal::NoKeys + Denial::NoKeys ); // The same request with no token is admitted by the public rules. @@ -755,7 +755,7 @@ mod tests { .decide(&with_token(request("/demo"), &mismatched)) .await .unwrap_err(), - Refusal::UnknownKey + Denial::UnknownKey ); } @@ -782,7 +782,7 @@ mod tests { let mismatched = sign(&wrong, "demo", &["**"], &[], None); assert!(matches!( policy.decide(&with_token(request("/demo"), &mismatched)).await, - Err(Refusal::InvalidToken(_)) + Err(Denial::InvalidToken(_)) )); } @@ -805,7 +805,7 @@ mod tests { second.transport = transport; assert_eq!( server.answer(&second).await.unwrap_err(), - Refusal::RemoteLimit { root: None } + Denial::RemoteLimit { root: None } ); first.event = Event::End { reason: Reason::Shutdown, @@ -846,7 +846,7 @@ mod tests { .decide(&with_setup_token(request("/demo"), Token::OUT_OF_BAND, &forged)) .await .unwrap_err(); - assert!(matches!(err, Refusal::InvalidToken(_)), "{err}"); + assert!(matches!(err, Denial::InvalidToken(_)), "{err}"); } #[tokio::test] @@ -862,7 +862,7 @@ mod tests { .decide(&with_setup_token(request("/demo"), Token::CAT, &jwt)) .await .unwrap_err(); - assert_eq!(err, Refusal::UnsupportedToken(Token::CAT)); + assert_eq!(err, Denial::UnsupportedToken(Token::CAT)); assert_eq!( err.to_string(), "SETUP token type 0x1 is not supported; only type 0 (a JWT) is" @@ -894,11 +894,11 @@ mod tests { let setup = sign(&key, "demo", &["**"], &[], None); let query = sign(&key, "demo", &[], &["**"], None); let different = with_setup_token(with_token(request("/demo"), &query), Token::OUT_OF_BAND, &setup); - assert_eq!(policy.decide(&different).await.unwrap_err(), Refusal::TwoTokens); + assert_eq!(policy.decide(&different).await.unwrap_err(), Denial::TwoTokens); // The same bytes under another token type are still a second credential. let other_type = with_setup_token(with_token(request("/demo"), &setup), Token::CAT, &setup); - assert_eq!(policy.decide(&other_type).await.unwrap_err(), Refusal::TwoTokens); + assert_eq!(policy.decide(&other_type).await.unwrap_err(), Denial::TwoTokens); } /// Two `jwt` parameters would leave the server guessing which one the client meant. @@ -925,7 +925,7 @@ mod tests { format!("jwt={jwt}&j%77t=stale"), ] { request.query = Some(query); - assert_eq!(policy.decide(&request).await.unwrap_err(), Refusal::DuplicateJwt); + assert_eq!(policy.decide(&request).await.unwrap_err(), Denial::DuplicateJwt); } // An empty one alone is no token, so the session is anonymous. @@ -943,7 +943,7 @@ mod tests { let none = Policy::default(); assert_eq!( none.decide(&with_peer(request("/"), None)).await.unwrap_err(), - Refusal::NoMtlsGrant + Denial::NoMtlsGrant ); let policy = Policy { @@ -962,7 +962,7 @@ mod tests { assert!(!grant.peer); // The certificate does not stand in for a public grant. - assert_eq!(policy.decide(&request("/")).await.unwrap_err(), Refusal::NoPublicGrant); + assert_eq!(policy.decide(&request("/")).await.unwrap_err(), Denial::NoPublicGrant); } /// `mtls_peer` and `mtls_upstream` mark a certificate's grant, and only a certificate's. @@ -1020,7 +1020,7 @@ mod tests { with_peer(with_token(request("/demo"), "garbage"), None), with_peer(with_setup_token(request("/demo"), Token::OUT_OF_BAND, &jwt), None), ] { - assert_eq!(policy.decide(&request).await.unwrap_err(), Refusal::TokenAndCertificate); + assert_eq!(policy.decide(&request).await.unwrap_err(), Denial::TokenAndCertificate); } assert!(policy.decide(&with_peer(request("/demo"), None)).await.is_ok()); assert!(policy.decide(&with_token(request("/demo"), &jwt)).await.is_ok()); @@ -1067,7 +1067,7 @@ mod tests { for path in ["/rooms/123", "/other/room", "/anonymous/room"] { assert_eq!( policy.decide(&request(path)).await.unwrap_err(), - Refusal::NoAccess { + Denial::NoAccess { path: path.trim_start_matches('/').into(), root: None }, @@ -1077,7 +1077,7 @@ mod tests { let grant = policy.decide(&with_peer(request("/origin/edge0"), None)).await.unwrap(); assert_eq!(grant.publish, patterns(&[""]).into()); let err = policy.decide(&with_peer(request("/anon"), None)).await.unwrap_err(); - assert!(matches!(err, Refusal::NoAccess { .. }), "{err}"); + assert!(matches!(err, Denial::NoAccess { .. }), "{err}"); } #[tokio::test] @@ -1102,14 +1102,14 @@ mod tests { server.answer(&second).await.unwrap(); assert_eq!( server.answer(&third).await.unwrap_err(), - Refusal::RemoteLimit { root: None } + Denial::RemoteLimit { root: None } ); // A repeated connect for a known id refreshes rather than double-counting. server.answer(&first).await.unwrap(); assert_eq!( server.answer(&third).await.unwrap_err(), - Refusal::RemoteLimit { root: None } + Denial::RemoteLimit { root: None } ); // Another address is unaffected. @@ -1138,7 +1138,7 @@ mod tests { server.answer(&fourth).await.unwrap(); assert_eq!( server.answer(&request("/")).await.unwrap_err(), - Refusal::RemoteLimit { root: None } + Denial::RemoteLimit { root: None } ); } @@ -1182,7 +1182,7 @@ mod tests { }; assert_eq!( endless.decide(&request("/")).await.unwrap_err(), - Refusal::ExpiresOutOfRange + Denial::ExpiresOutOfRange ); assert!(matches!(Server::new(endless), Err(Error::ExpiresOutOfRange))); } @@ -1204,7 +1204,7 @@ mod tests { server.answer(&request("/")).await.unwrap(); assert_eq!( server.answer(&request("/")).await.unwrap_err(), - Refusal::RemoteLimit { root: None } + Denial::RemoteLimit { root: None } ); } @@ -1242,7 +1242,7 @@ mod tests { mapped.remote = Some("[::ffff:203.0.113.9]:9".parse().unwrap()); assert_eq!( server.answer(&mapped).await.unwrap_err(), - Refusal::TokenLimit { + Denial::TokenLimit { root: Some("demo".into()) } ); @@ -1258,7 +1258,7 @@ mod tests { same_host.remote = Some("[::ffff:203.0.113.9]:9".parse().unwrap()); assert_eq!( server.answer(&same_host).await.unwrap_err(), - Refusal::RemoteLimit { + Denial::RemoteLimit { root: Some("demo".into()) } ); @@ -1306,7 +1306,7 @@ mod tests { server.answer(&attach(&first)).await.unwrap(); assert_eq!( server.answer(&attach(&second)).await.unwrap_err(), - Refusal::TokenLimit { + Denial::TokenLimit { root: Some("demo".into()) } ); diff --git a/rs/moq-c/src/publish.rs b/rs/moq-c/src/publish.rs index b91a258f62a..45ae9e04427 100644 --- a/rs/moq-c/src/publish.rs +++ b/rs/moq-c/src/publish.rs @@ -404,7 +404,7 @@ impl Publish { /// unless their caller explicitly identifies the frame as encoder output. pub fn media_flush(&mut self, media: Id, timestamp: hang::container::Timestamp) -> Result<(), Error> { let track = self.media.get_mut(media).ok_or(Error::MediaNotFound)?; - track.flush(timestamp, moq_net::time::now())?; + track.flush(timestamp, moq_net::time::Instant::now())?; Ok(()) } diff --git a/rs/moq-c/src/video.rs b/rs/moq-c/src/video.rs index a9fcd90232b..f0d20d58241 100644 --- a/rs/moq-c/src/video.rs +++ b/rs/moq-c/src/video.rs @@ -241,7 +241,7 @@ async fn follow_reservation( max = next; control = Control::new(Policy::new(max)); } - let Some(bitrate) = control.update(estimate, moq_net::time::now()) else { + let Some(bitrate) = control.update(estimate, moq_net::time::Instant::now()) else { continue; }; diff --git a/rs/moq-cli/src/main.rs b/rs/moq-cli/src/main.rs index aa28cdd09ce..d69e0445745 100644 --- a/rs/moq-cli/src/main.rs +++ b/rs/moq-cli/src/main.rs @@ -1083,14 +1083,14 @@ mod tests { let (client, server) = moq_net::transport::memory::pair(config); let accepting = tokio::spawn(async move { let (session, driver) = moq_net::Server::new() - .accept(moq_net::time::now(), server) + .accept(moq_net::time::Instant::now(), server) .await .unwrap(); tokio::spawn(moq_net::time::run(driver)); session }); let (_client, client_driver) = moq_net::Client::new() - .connect(moq_net::time::now(), client) + .connect(moq_net::time::Instant::now(), client) .await .unwrap(); // Never dropped, which would close the transport: polled only until the session is served. diff --git a/rs/moq-clock/MIGRATE.md b/rs/moq-clock/MIGRATE.md index c05e7ad07ad..bd3b497f610 100644 --- a/rs/moq-clock/MIGRATE.md +++ b/rs/moq-clock/MIGRATE.md @@ -4,6 +4,10 @@ How to update your code for each breaking change, newest first. ## Unreleased +### `anchor()` is `origin()` (#6510) + +Rename `moq_clock::anchor()` to `moq_clock::origin()`, matching `@moq/clock`; it still returns the fixed `(Instant, Wall)` pair. + ### moq-clock is a time library (#5465) moq-clock 0.10 was the "CLOCK over QUIC" example binary. diff --git a/rs/moq-clock/src/installed.rs b/rs/moq-clock/src/installed.rs index 634ee7c08f2..d080f5a341e 100644 --- a/rs/moq-clock/src/installed.rs +++ b/rs/moq-clock/src/installed.rs @@ -281,14 +281,14 @@ mod tests { }); } - /// Wall time and the anchor come from the installed clock, and a wall step passes no time. + /// Wall time and the origin come from the installed clock, and a wall step passes no time. #[test] fn wall_reads_the_installed_clock() { let runtime = runtime(false); let clock = Manual::new().install(runtime.handle()); let _entered = runtime.enter(); assert_eq!(crate::wall(), Manual::WALL_START); - assert_eq!(crate::anchor(), (Instant::ZERO, Manual::WALL_START)); + assert_eq!(crate::origin(), (Instant::ZERO, Manual::WALL_START)); clock.advance(Duration::from_secs(5)); assert_eq!(crate::wall(), Manual::WALL_START + Duration::from_secs(5)); @@ -296,9 +296,9 @@ mod tests { assert_eq!(crate::wall(), Manual::WALL_START); assert_eq!(crate::now(), Instant::ZERO + Duration::from_secs(5)); assert_eq!( - crate::anchor(), + crate::origin(), (Instant::ZERO, Manual::WALL_START), - "the anchor is fixed at its first read" + "the origin is fixed at its first read" ); } diff --git a/rs/moq-clock/src/lib.rs b/rs/moq-clock/src/lib.rs index 2f5f0eb9192..90071a8a0be 100644 --- a/rs/moq-clock/src/lib.rs +++ b/rs/moq-clock/src/lib.rs @@ -96,10 +96,13 @@ pub fn wall() -> Wall { runtime::wall() } -/// The first monotonic and wall readings observed on the ambient clock. +/// The ambient clock's origin: an instant and its wall time, fixed at the first read. /// -/// Unlike [`wall`], the wall half does not change after a clock correction. -pub fn anchor() -> (Instant, Wall) { +/// It maps instants onto wall time and, unlike [`wall`], does not move after a clock +/// correction. `@moq/clock`'s `origin()` returns only the wall time of instant zero, in +/// milliseconds; here [`Wall`] is nanoseconds and comes paired with an instant, since a +/// runtime clock's instant zero predates 1970. +pub fn origin() -> (Instant, Wall) { #[cfg(feature = "manual")] if let Some(clock) = deadline::installed() { return clock.anchor(); diff --git a/rs/moq-clock/src/runtime.rs b/rs/moq-clock/src/runtime.rs index 166b7c98914..067717cc535 100644 --- a/rs/moq-clock/src/runtime.rs +++ b/rs/moq-clock/src/runtime.rs @@ -319,10 +319,10 @@ mod tests { first.block_on(async { let _ = crate::now(); tokio::time::advance(Duration::from_secs(60)).await; - let _ = crate::anchor(); + let _ = crate::origin(); }); second.block_on(async { - let (instant, _) = crate::anchor(); + let (instant, _) = crate::origin(); assert_eq!(instant, crate::now()); }); } @@ -341,9 +341,9 @@ mod tests { runtime.block_on(async { let _ = crate::now(); tokio::time::advance(Duration::from_secs(3_600)).await; - let _ = crate::anchor(); + let _ = crate::origin(); }); - let (instant, _) = crate::anchor(); + let (instant, _) = crate::origin(); assert!(instant <= crate::now(), "{instant:?} > {:?}", crate::now()); } @@ -505,7 +505,7 @@ mod browser_read_tests { let start = crate::now(); assert!(crate::now() >= start); assert!(crate::wall() > crate::Wall::UNIX_EPOCH); - let (instant, _) = crate::anchor(); + let (instant, _) = crate::origin(); assert!(instant <= crate::now()); } } diff --git a/rs/moq-e2ee/tests/support/harness.rs b/rs/moq-e2ee/tests/support/harness.rs index 71844103988..e246c2a24d6 100644 --- a/rs/moq-e2ee/tests/support/harness.rs +++ b/rs/moq-e2ee/tests/support/harness.rs @@ -14,7 +14,7 @@ use moq_net::transport::memory; pub use moq_net::time::run; pub fn now() -> moq_net::time::Instant { - moq_net::time::now() + moq_net::time::Instant::now() } /// Options for [`connect_mock`]. diff --git a/rs/moq-ffi/src/auth.rs b/rs/moq-ffi/src/auth.rs index f191e07e853..6f1cb665285 100644 --- a/rs/moq-ffi/src/auth.rs +++ b/rs/moq-ffi/src/auth.rs @@ -25,7 +25,7 @@ impl From for MoqGrant { publish: patterns(&grant.publish), subscribe: patterns(&grant.subscribe), expires_us: grant.expires.map(|expires| { - let remaining = expires.saturating_duration_since(moq_net::time::now()); + let remaining = expires.saturating_duration_since(moq_net::time::Instant::now()); u64::try_from(remaining.as_micros()).unwrap_or(u64::MAX) }), } diff --git a/rs/moq-gst/src/sink/imp.rs b/rs/moq-gst/src/sink/imp.rs index 2ecda4e23c3..92a682a8273 100644 --- a/rs/moq-gst/src/sink/imp.rs +++ b/rs/moq-gst/src/sink/imp.rs @@ -758,7 +758,7 @@ impl MoqSink { let outcome = lifecycle.media.place_wall(&buffer, sample).and_then(|()| { lifecycle .media - .push_buffer(data, pts, duration, current_running_time, moq_net::time::now()) + .push_buffer(data, pts, duration, current_running_time, moq_net::time::Instant::now()) .map_err(anyhow::Error::msg) }); let changes = match &outcome { @@ -1802,7 +1802,7 @@ mod tests { let segment = gst::FormattedSegment::::new(); pad.lifecycle().media.observe_segment(segment.upcast()); sink.set_state(gst::State::Playing).unwrap(); - let anchor = moq_net::time::now(); + let anchor = moq_net::time::Instant::now(); for (pts, arrival) in [(0, 0), (20, 120), (40, 6_000), (60, 6_020)] { if pts == 40 { sink.set_state(gst::State::Paused).unwrap(); diff --git a/rs/moq-gst/src/sink/pad.rs b/rs/moq-gst/src/sink/pad.rs index 1506a6e667c..536e961f8dc 100644 --- a/rs/moq-gst/src/sink/pad.rs +++ b/rs/moq-gst/src/sink/pad.rs @@ -1192,7 +1192,7 @@ mod tests { Some(gst::ClockTime::ZERO), None, None, - moq_net::time::now(), + moq_net::time::Instant::now(), ) .unwrap(); @@ -1330,7 +1330,7 @@ mod tests { .subscribe(moq_net::track::Subscription::default().with_max_delay(Duration::from_secs(1))) .await .unwrap(); - let anchor = moq_net::time::now(); + let anchor = moq_net::time::Instant::now(); for index in 0..17 { assert_eq!( pad.push_buffer( @@ -1548,7 +1548,7 @@ mod tests { Some(gst::ClockTime::from_mseconds(20 * index as u64)), None, None, - moq_net::time::now(), + moq_net::time::Instant::now(), ) .unwrap(), PushOutcome::Published @@ -1581,7 +1581,7 @@ mod tests { Some(gst::ClockTime::ZERO), None, None, - moq_net::time::now() + moq_net::time::Instant::now() ) .unwrap(), PushOutcome::NoSegment, @@ -1593,7 +1593,7 @@ mod tests { Some(gst::ClockTime::ZERO), None, None, - moq_net::time::now() + moq_net::time::Instant::now() ) .unwrap(), PushOutcome::Dropped, @@ -1641,7 +1641,7 @@ mod tests { Some(gst::ClockTime::ZERO), None, None, - moq_net::time::now(), + moq_net::time::Instant::now(), ) .unwrap(); @@ -1675,7 +1675,7 @@ mod tests { Some(gst::ClockTime::from_mseconds(40)), None, None, - moq_net::time::now(), + moq_net::time::Instant::now(), ) .unwrap(); pad.push_buffer( @@ -1683,7 +1683,7 @@ mod tests { Some(gst::ClockTime::from_mseconds(80)), None, None, - moq_net::time::now(), + moq_net::time::Instant::now(), ) .unwrap(); @@ -1743,7 +1743,7 @@ mod tests { Some(gst::ClockTime::ZERO), None, None, - moq_net::time::now(), + moq_net::time::Instant::now(), ) .unwrap(); @@ -1813,7 +1813,7 @@ mod tests { None, None, Some(gst::ClockTime::from_mseconds(25)), - moq_net::time::now(), + moq_net::time::Instant::now(), ) .unwrap(); assert!(!pad.is_failed(), "a missing PTS uses the supplied running time"); @@ -1853,7 +1853,7 @@ mod tests { None, None, None, - moq_net::time::now() + moq_net::time::Instant::now() ) .is_err(), "the caller gets a hard error instead of a silent drop" @@ -1879,7 +1879,7 @@ mod tests { Some(gst::ClockTime::ZERO), None, None, - moq_net::time::now(), + moq_net::time::Instant::now(), ) .unwrap(); } @@ -1920,7 +1920,7 @@ mod tests { Some(gst::ClockTime::ZERO), None, None, - moq_net::time::now(), + moq_net::time::Instant::now(), ) .unwrap(); assert_eq!(outcome, PushOutcome::Published); @@ -1942,7 +1942,7 @@ mod tests { Some(gst::ClockTime::ZERO), None, None, - moq_net::time::now(), + moq_net::time::Instant::now(), ) .unwrap(); @@ -2131,7 +2131,7 @@ mod tests { Some(gst::ClockTime::ZERO), Some(gst::ClockTime::from_seconds(1)), None, - moq_net::time::now(), + moq_net::time::Instant::now(), ) .unwrap(); assert!(pad.is_failed()); @@ -2158,7 +2158,7 @@ mod tests { Some(gst::ClockTime::from_mseconds(start_ms)), Some(gst::ClockTime::from_mseconds(dur_ms)), None, - moq_net::time::now(), + moq_net::time::Instant::now(), ) .unwrap(); } @@ -2182,7 +2182,7 @@ mod tests { Some(gst::ClockTime::ZERO), None, None, - moq_net::time::now(), + moq_net::time::Instant::now(), ) .unwrap(); assert!(!pad.is_failed(), "a durationless cue drops the buffer, not the pad"); @@ -2240,7 +2240,7 @@ mod tests { import.observe_caps(&broadcast, &catalog, producer_options(&h264_caps(), Some("import"))); // The third frame reaches the sink 100ms later than its running time says it should. - let anchor = moq_net::time::now(); + let anchor = moq_net::time::Instant::now(); for (pts, arrival) in [(0, 0), (33, 33), (66, 166)] { for pad in [&mut encoder, &mut import] { pad.observe_segment(time_segment()); @@ -2274,7 +2274,7 @@ mod tests { &catalog, producer_options(&h264_caps(), Some("encoder")).with_encoder(true), ); - let anchor = moq_net::time::now(); + let anchor = moq_net::time::Instant::now(); for (pts, arrival) in [(0, 0), (33, 33), (66, 166)] { pad.observe_segment(time_segment()); assert_eq!( @@ -2333,7 +2333,7 @@ mod tests { pad.observe_caps(&broadcast, &catalog, producer_options(&h264_caps(), Some("video"))); pad.observe_segment(time_segment()); let delta = Bytes::from_static(&[0, 0, 0, 1, 0x61, 0xe0, 0x12, 0x34]); - let now = moq_net::time::now(); + let now = moq_net::time::Instant::now(); let push = |pad: &mut Pad, data: Bytes, pts: u64| { pad.push_buffer(data, Some(gst::ClockTime::from_mseconds(pts)), None, None, now) .unwrap() @@ -2354,7 +2354,7 @@ mod tests { let mut pad = Pad::new(); pad.observe_caps(&broadcast, &catalog, producer_options(&h264_caps(), Some("video"))); pad.observe_segment(time_segment()); - let now = moq_net::time::now(); + let now = moq_net::time::Instant::now(); let push = |pad: &mut Pad, data: Bytes, pts: u64| { pad.push_buffer(data, Some(gst::ClockTime::from_mseconds(pts)), None, None, now) .unwrap() @@ -2383,7 +2383,7 @@ mod tests { pad.observe_caps(&broadcast, &catalog, producer_options(&h264_caps(), Some("video"))); pad.observe_segment(time_segment()); let delta = Bytes::from_static(&[0, 0, 0, 1, 0x61, 0xe0, 0x12, 0x34]); - let now = moq_net::time::now(); + let now = moq_net::time::Instant::now(); let push = |pad: &mut Pad, data: Bytes, pts: u64| { pad.push_buffer(data, Some(gst::ClockTime::from_mseconds(pts)), None, None, now) .unwrap() @@ -2410,7 +2410,7 @@ mod tests { let keyframe = h264_keyframe_au(); let headers = keyframe.slice(..keyframe.len() - 9); let delta = Bytes::from_static(&[0, 0, 0, 1, 0x61, 0xe0, 0x12, 0x34]); - let now = moq_net::time::now(); + let now = moq_net::time::Instant::now(); let push = |pad: &mut Pad, data: Bytes, pts: u64| { pad.push_buffer(data, Some(gst::ClockTime::from_mseconds(pts)), None, None, now) .unwrap() diff --git a/rs/moq-hls/src/export/mod.rs b/rs/moq-hls/src/export/mod.rs index 2eed7f670e4..fb8735521f4 100644 --- a/rs/moq-hls/src/export/mod.rs +++ b/rs/moq-hls/src/export/mod.rs @@ -2441,7 +2441,7 @@ mod tests { // PTS zero at exactly the moq epoch, so every timestamp maps to a fixed string. let wall = UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS); let config = moq_mux::catalog::Config::default() - .with_clock(moq_mux::Clock::at(moq_net::time::now(), wall).expect("a representable wall")); + .with_clock(moq_mux::Clock::at(moq_net::time::Instant::now(), wall).expect("a representable wall")); let catalog = moq_mux::catalog::Producer::new(&mut broadcast, config).unwrap(); let reserved = catalog.reserve(); @@ -2664,12 +2664,18 @@ mod tests { .with_subscriber(remote.as_ref().unwrap().clone()); Some(tokio::join!( async { - let (session, driver) = client.connect(moq_net::time::now(), client_transport).await.unwrap(); + let (session, driver) = client + .connect(moq_net::time::Instant::now(), client_transport) + .await + .unwrap(); tokio::spawn(moq_net::time::run(driver)); session }, async { - let (session, driver) = server.accept(moq_net::time::now(), server_transport).await.unwrap(); + let (session, driver) = server + .accept(moq_net::time::Instant::now(), server_transport) + .await + .unwrap(); tokio::spawn(moq_net::time::run(driver)); session } @@ -4643,7 +4649,7 @@ mod tests { fanout.push(at, entry(at, at), &refs[0]); } // Aligned references share record numbers, so every handoff continues seamlessly. - let started = moq_net::time::now(); + let started = moq_net::time::Instant::now(); for at in retained..retained + 1_024 { let reference = &refs[(at % 2) as usize]; fanout.select(Some(reference.clone())); diff --git a/rs/moq-mux/src/container/test_util.rs b/rs/moq-mux/src/container/test_util.rs index f0bb717a357..daec6f8016d 100644 --- a/rs/moq-mux/src/container/test_util.rs +++ b/rs/moq-mux/src/container/test_util.rs @@ -260,7 +260,7 @@ impl Link { let sessions = tokio::join!( async { let (session, driver) = client - .connect_lite(moq_net::time::now(), client_transport) + .connect_lite(moq_net::time::Instant::now(), client_transport) .await .unwrap(); tokio::spawn(moq_net::time::run(driver)); @@ -268,7 +268,7 @@ impl Link { }, async { let (session, driver) = server - .accept_lite(moq_net::time::now(), server_transport) + .accept_lite(moq_net::time::Instant::now(), server_transport) .await .unwrap(); tokio::spawn(moq_net::time::run(driver)); @@ -305,7 +305,7 @@ impl Link { let sessions = tokio::join!( async { let (session, driver) = client - .connect_lite(moq_net::time::now(), client_transport) + .connect_lite(moq_net::time::Instant::now(), client_transport) .await .unwrap(); tokio::spawn(moq_net::time::run(driver)); @@ -313,7 +313,7 @@ impl Link { }, async { let (session, driver) = server - .accept_lite(moq_net::time::now(), server_transport) + .accept_lite(moq_net::time::Instant::now(), server_transport) .await .unwrap(); tokio::spawn(moq_net::time::run(driver)); diff --git a/rs/moq-net/MIGRATE.md b/rs/moq-net/MIGRATE.md index e16d361e179..da7a8b465af 100644 --- a/rs/moq-net/MIGRATE.md +++ b/rs/moq-net/MIGRATE.md @@ -4,6 +4,11 @@ How to update your code for each breaking change, newest first. ## Unreleased +### `stats::Refusal` is `stats::RefusalKind`, and `time::now` is gone (#6510) + +Rename `moq_net::stats::Refusal` to `moq_net::stats::RefusalKind`, so it no longer shares a name with `moq_auth::Refusal`; its variants and `Refusals` are unchanged. +Replace `moq_net::time::now()` with `moq_net::time::Instant::now()`, the one way to read the clock. + ### IETF whole-group FETCH answers name the requested group ([#6199](https://github.com/moq-dev/moq/issues/6199)) On moq-transport drafts 14 through 19, a whole-group `FETCH_OK` now names `{g, 0}` instead of `{g+1, 0}`. diff --git a/rs/moq-net/src/model/clock.rs b/rs/moq-net/src/model/clock.rs index 38e3a6d1ecf..4545f5ac68d 100644 --- a/rs/moq-net/src/model/clock.rs +++ b/rs/moq-net/src/model/clock.rs @@ -56,7 +56,7 @@ pub(super) fn wall() -> crate::time::Instant { pub(super) fn anchor() -> (crate::time::Instant, Duration) { static ANCHORS: LazyLock>> = LazyLock::new(Default::default); - let (instant, wall) = moq_clock::anchor(); + let (instant, wall) = moq_clock::origin(); let mut anchors = ANCHORS.lock().unwrap(); let offset = *anchors.entry((instant, wall)).or_insert_with(|| { let jitter = Duration::from_millis(rand::rng().random_range(1..69_420)); diff --git a/rs/moq-net/src/stats.rs b/rs/moq-net/src/stats.rs index 1f8d048b79e..ae2f2266ec6 100644 --- a/rs/moq-net/src/stats.rs +++ b/rs/moq-net/src/stats.rs @@ -147,7 +147,7 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; use crate::{AsPath, PathOwned, Pattern, Patterns, util::SendCell}; mod outcomes; -pub use outcomes::{Failure, Failures, Refusal, Refusals}; +pub use outcomes::{Failure, Failures, RefusalKind, Refusals}; use outcomes::{FailureCounters, RefusalCounters}; /// Cumulative atomic counters for a single `(tier, role)` on a broadcast. @@ -1411,7 +1411,7 @@ pub struct Handle { impl Handle { /// Count a session refused outside relay admission under its resolved label and tier. - pub fn refuse(&self, label: impl AsPath, reason: Refusal) { + pub fn refuse(&self, label: impl AsPath, reason: RefusalKind) { if let Some(presence) = self.stats.session_counters(&self.tier, label) { presence .sessions_refused @@ -2271,7 +2271,7 @@ mod tests { fn outcomes_survive_clones_tier_changes_and_pruning() { let stats = test_stats(); let handle = stats.tier(Tier::new("gateway")); - handle.refuse("root", Refusal::Forbidden); + handle.refuse("root", RefusalKind::Forbidden); let session = handle.session("root"); let clone = session.clone(); session.retag(Tier::new("next"), "root"); @@ -2301,7 +2301,7 @@ mod tests { let after = stats.snapshot(); assert_eq!(before.sessions(), after.sessions(), "retirement keeps outcomes once"); let disabled = Registry::disabled(); - disabled.tier(Tier::default()).refuse("root", Refusal::Refused); + disabled.tier(Tier::default()).refuse("root", RefusalKind::Refused); disabled.tier(Tier::default()).session("root").fail(Failure::Expired); assert!(disabled.snapshot().sessions().is_empty()); } diff --git a/rs/moq-net/src/stats/outcomes.rs b/rs/moq-net/src/stats/outcomes.rs index 0ed219342c6..e1d73f29c9c 100644 --- a/rs/moq-net/src/stats/outcomes.rs +++ b/rs/moq-net/src/stats/outcomes.rs @@ -6,7 +6,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; /// The reason a session was refused. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[non_exhaustive] -pub enum Refusal { +pub enum RefusalKind { /// The admission decider refused the session. Refused, /// The admission decider could not answer. @@ -21,7 +21,7 @@ pub enum Refusal { Expired, } -impl Refusal { +impl RefusalKind { /// Every currently defined kind, in display order. pub const ALL: &'static [Self] = &[ Self::Refused, @@ -65,14 +65,14 @@ pub struct Refusals { impl Refusals { /// The cumulative count for this kind. - pub fn count(&self, kind: Refusal) -> u64 { + pub fn count(&self, kind: RefusalKind) -> u64 { match kind { - Refusal::Refused => self.refused, - Refusal::Unavailable => self.unavailable, - Refusal::Request => self.request, - Refusal::Forbidden => self.forbidden, - Refusal::Lan => self.lan, - Refusal::Expired => self.expired, + RefusalKind::Refused => self.refused, + RefusalKind::Unavailable => self.unavailable, + RefusalKind::Request => self.request, + RefusalKind::Forbidden => self.forbidden, + RefusalKind::Lan => self.lan, + RefusalKind::Expired => self.expired, } } /// Add every kind from another readout. @@ -106,14 +106,14 @@ pub(super) struct RefusalCounters { } impl RefusalCounters { - pub(super) fn counter(&self, kind: Refusal) -> &AtomicU64 { + pub(super) fn counter(&self, kind: RefusalKind) -> &AtomicU64 { match kind { - Refusal::Refused => &self.refused, - Refusal::Unavailable => &self.unavailable, - Refusal::Request => &self.request, - Refusal::Forbidden => &self.forbidden, - Refusal::Lan => &self.lan, - Refusal::Expired => &self.expired, + RefusalKind::Refused => &self.refused, + RefusalKind::Unavailable => &self.unavailable, + RefusalKind::Request => &self.request, + RefusalKind::Forbidden => &self.forbidden, + RefusalKind::Lan => &self.lan, + RefusalKind::Expired => &self.expired, } } pub(super) fn snapshot(&self) -> Refusals { diff --git a/rs/moq-net/src/time.rs b/rs/moq-net/src/time.rs index f39a7bb50d1..a2d9b7b4f67 100644 --- a/rs/moq-net/src/time.rs +++ b/rs/moq-net/src/time.rs @@ -2,8 +2,8 @@ //! //! Drivers take the current [`Instant`] on every poll and never read a clock. +pub use moq_clock::Instant; pub(crate) use moq_clock::{Deadline, Deadlines}; -pub use moq_clock::{Instant, now}; use crate::Error; diff --git a/rs/moq-relay/src/auth/refresh.rs b/rs/moq-relay/src/auth/refresh.rs index 009d0acd4b3..c775d9026f3 100644 --- a/rs/moq-relay/src/auth/refresh.rs +++ b/rs/moq-relay/src/auth/refresh.rs @@ -518,7 +518,7 @@ mod tests { /// A client session and the server session `lease` was prepared for, before supervision. async fn connect(lease: super::super::Lease) -> (moq_net::Session, moq_net::Session, super::super::Lease) { let (client, server) = transports().await; - let now = moq_net::time::now(); + let now = moq_net::time::Instant::now(); let client = async { let origin = moq_tokio::origin::spawn(); let (session, driver) = moq_net::Client::new() @@ -615,7 +615,7 @@ mod tests { let stats = registry.tier(moq_net::stats::Tier::default()).session("room"); let lease = super::super::Lease::new("/room", consumer).with_stats(stats.clone()); let (client_transport, server) = transports().await; - let now = moq_net::time::now(); + let now = moq_net::time::Instant::now(); let origin = moq_tokio::origin::spawn(); let client = moq_net::Client::new() .with_versions("moq-lite-07-wip".parse::().unwrap().into()) diff --git a/rs/moq-relay/src/connection.rs b/rs/moq-relay/src/connection.rs index e9c44913af2..9aa943c62d5 100644 --- a/rs/moq-relay/src/connection.rs +++ b/rs/moq-relay/src/connection.rs @@ -1,4 +1,4 @@ -use crate::{auth, cluster, incoming::Incoming, refusals::Refusal}; +use crate::{auth, cluster, incoming::Incoming, refusals::RefusalKind}; use axum::http; use tracing::Instrument; @@ -9,7 +9,7 @@ use tracing::Instrument; /// the right code instead of sprinkling close/return at each failure site. pub(crate) struct StatusError { pub(crate) status: http::StatusCode, - refusal: Option, + refusal: Option, pub(crate) source: anyhow::Error, } @@ -93,7 +93,7 @@ impl Connection { let admitted = request .within(Box::pin(lifecycle.admit(request.admission(&lifecycle.auth)))) .await - .inspect_err(|_| lifecycle.cluster.refusals.record(Refusal::Unavailable)) + .inspect_err(|_| lifecycle.cluster.refusals.record(RefusalKind::Unavailable)) .map_err(|err| err.context("admission timed out"))?; let (admitted, registration) = match admitted { Ok(admitted) => admitted, @@ -284,7 +284,7 @@ impl Lifecycle { let Some(presented) = cluster::Cluster::lan_credential(&request.path) else { return Err(StatusError { status: http::StatusCode::FORBIDDEN, - refusal: Some(Refusal::Lan), + refusal: Some(RefusalKind::Lan), source: anyhow::anyhow!("LAN peer did not present a membership proof"), }); }; @@ -297,14 +297,14 @@ impl Lifecycle { Some(false) => { return Err(StatusError { status: http::StatusCode::FORBIDDEN, - refusal: Some(Refusal::Lan), + refusal: Some(RefusalKind::Lan), source: anyhow::anyhow!("LAN peer did not present this listener's membership proof"), }); } None => { return Err(StatusError { status: http::StatusCode::FORBIDDEN, - refusal: Some(Refusal::Lan), + refusal: Some(RefusalKind::Lan), source: anyhow::anyhow!("/.cluster request refused: LAN discovery is not enabled"), }); } diff --git a/rs/moq-relay/src/internal.rs b/rs/moq-relay/src/internal.rs index d61ec6ffb6e..97f26878710 100644 --- a/rs/moq-relay/src/internal.rs +++ b/rs/moq-relay/src/internal.rs @@ -626,7 +626,7 @@ fn render_drain(out: &mut String, tally: crate::shutdown::Tally) { /// zero so a rate over it is defined from the first scrape. A refused session /// never reaches the traffic counters above. fn render_refusals(out: &mut String, refusals: &crate::refusals::Refusals) { - use crate::refusals::Refusal; + use crate::refusals::RefusalKind; use std::fmt::Write as _; let _ = writeln!( @@ -635,7 +635,7 @@ fn render_refusals(out: &mut String, refusals: &crate::refusals::Refusals) { ); let _ = writeln!(out, "# TYPE moq_relay_sessions_refused_total counter"); let counts = refusals.snapshot(); - for &refusal in Refusal::ALL { + for &refusal in RefusalKind::ALL { let _ = writeln!( out, "moq_relay_sessions_refused_total{{reason=\"{}\"}} {}", @@ -1178,10 +1178,10 @@ mod tests { /// defined before the first refusal. #[test] fn refusal_metrics_list_every_reason_from_zero() { - use crate::refusals::{Refusal, Refusals}; + use crate::refusals::{RefusalKind, Refusals}; let refusals = Refusals::default(); - refusals.record(Refusal::Unavailable); + refusals.record(RefusalKind::Unavailable); let mut body = String::new(); render_refusals(&mut body, &refusals); @@ -1189,8 +1189,8 @@ mod tests { body.contains("# TYPE moq_relay_sessions_refused_total counter"), "type header:\n{body}" ); - for &refusal in Refusal::ALL { - let expected = u64::from(refusal == Refusal::Unavailable); + for &refusal in RefusalKind::ALL { + let expected = u64::from(refusal == RefusalKind::Unavailable); let row = format!( "moq_relay_sessions_refused_total{{reason=\"{}\"}} {expected}", refusal.as_str() diff --git a/rs/moq-relay/src/refusals.rs b/rs/moq-relay/src/refusals.rs index 07d9c65b5ca..52debeb4ccb 100644 --- a/rs/moq-relay/src/refusals.rs +++ b/rs/moq-relay/src/refusals.rs @@ -1,21 +1,21 @@ //! Relay refusal collection, shared with published stats when enabled. use crate::auth; -pub(crate) use moq_net::stats::Refusal; +pub(crate) use moq_net::stats::RefusalKind; use moq_net::stats::{Registry, Tier}; -impl From<&auth::Error> for Refusal { +impl From<&auth::Error> for RefusalKind { // Exhaustive on purpose: a new `auth::Error` variant must pick its reason here. fn from(err: &auth::Error) -> Self { match err { auth::Error::Refused(refusal) => match refusal.reason { - moq_auth::refusal::Reason::Forbidden => Refusal::Forbidden, - moq_auth::refusal::Reason::Expired => Refusal::Expired, - _ => Refusal::Refused, + moq_auth::refusal::Reason::Forbidden => RefusalKind::Forbidden, + moq_auth::refusal::Reason::Expired => RefusalKind::Expired, + _ => RefusalKind::Refused, }, - auth::Error::Unavailable(_) => Refusal::Unavailable, - auth::Error::Forbidden(_) => Refusal::Forbidden, - auth::Error::Request(_) => Refusal::Request, + auth::Error::Unavailable(_) => RefusalKind::Unavailable, + auth::Error::Forbidden(_) => RefusalKind::Forbidden, + auth::Error::Request(_) => RefusalKind::Request, } } } @@ -38,7 +38,7 @@ impl Refusals { Self::default() } } - pub(crate) fn record(&self, reason: Refusal) { + pub(crate) fn record(&self, reason: RefusalKind) { self.0.tier(Tier::default()).refuse("", reason); } pub(crate) fn record_auth(&self, err: &auth::Error) { @@ -58,7 +58,7 @@ impl Refusals { counts } #[cfg(test)] - pub(crate) fn count(&self, reason: Refusal) -> u64 { + pub(crate) fn count(&self, reason: RefusalKind) -> u64 { self.snapshot().count(reason) } } @@ -99,6 +99,6 @@ mod tests { assert_eq!(presence.sessions_refused.forbidden, 1); assert_eq!(presence.sessions_refused.expired, 1); } - assert_eq!(refusals.count(Refusal::Expired), 4); + assert_eq!(refusals.count(RefusalKind::Expired), 4); } } diff --git a/rs/moq-relay/src/uring.rs b/rs/moq-relay/src/uring.rs index 371bea3f427..6545ab36e05 100644 --- a/rs/moq-relay/src/uring.rs +++ b/rs/moq-relay/src/uring.rs @@ -726,7 +726,7 @@ async fn serve_connection( None => moq_net::transport::Binding::InBand, }; let session = moq_uring::transport::Session::new(transport, binding); - let now = moq_net::time::now(); + let now = moq_net::time::Instant::now(); // moq-lite on its own ALPN runs unboxed on this worker. Everything else // (moq-transport, and the versions that negotiate in a bidi SETUP, which a // browser offering no subprotocol falls back to) boxes its futures with a @@ -832,7 +832,7 @@ async fn serve_request( .await .inspect_err(|err| { if matches!(err.downcast_ref::(), Some(moq_net::Error::Timeout)) { - serve.cluster.refusals.record(crate::refusals::Refusal::Unavailable); + serve.cluster.refusals.record(crate::refusals::RefusalKind::Unavailable); } })?; let (admitted, registration) = match decided { diff --git a/rs/moq-relay/src/web.rs b/rs/moq-relay/src/web.rs index de58da2f33e..1e7c8664cfe 100644 --- a/rs/moq-relay/src/web.rs +++ b/rs/moq-relay/src/web.rs @@ -997,7 +997,7 @@ async fn admit_http( .inspect_err(|err| state.cluster.refusals.record_auth(err))?; let token = lease.token(); let Some(origin) = state.cluster.subscriber(token) else { - state.cluster.refusals.record(crate::refusals::Refusal::Forbidden); + state.cluster.refusals.record(crate::refusals::RefusalKind::Forbidden); return Err(StatusCode::UNAUTHORIZED.into()); }; let stats = state.cluster.stats.tier(token.tier.clone()).request(&token.label); @@ -1187,7 +1187,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn http_refusals_count_at_both_endpoints() { - use crate::refusals::Refusal; + use crate::refusals::RefusalKind; let dir = TempDir::new().unwrap(); let (_, cert, _) = make_certs(&dir); let certificates = moq_tokio::tls::Certificates::from_pem(&std::fs::read(cert).unwrap()).unwrap(); @@ -1241,9 +1241,9 @@ mod tests { }; assert_eq!(status, StatusCode::UNAUTHORIZED); let reason = if publish_only { - Refusal::Forbidden + RefusalKind::Forbidden } else { - Refusal::Refused + RefusalKind::Refused }; assert_eq!( state.cluster.refusals.count(reason), @@ -2174,7 +2174,7 @@ mod tests { let (session, driver) = moq_net::Client::new() .with_versions("moq-lite-06".parse::().unwrap().into()) .with_publisher(origin.consume()) - .connect(moq_net::time::now(), transport) + .connect(moq_net::time::Instant::now(), transport) .await .unwrap(); tokio::spawn(moq_net::time::run(driver)); diff --git a/rs/moq-relay/tests/integration/auth_lifetime.rs b/rs/moq-relay/tests/integration/auth_lifetime.rs index cd5784fdae3..019af43813b 100644 --- a/rs/moq-relay/tests/integration/auth_lifetime.rs +++ b/rs/moq-relay/tests/integration/auth_lifetime.rs @@ -1368,7 +1368,7 @@ async fn memory_sessions() -> (moq_net::Session, moq_net::Session) { config.protocol = Some(crate::memory::newest().alpn().to_string()); let (client, server) = moq_net::transport::memory::pair(config); - let now = moq_net::time::now(); + let now = moq_net::time::Instant::now(); let client = async { let (session, driver) = moq_net::Client::new() .connect(now, client) diff --git a/rs/moq-relay/tests/integration/drain.rs b/rs/moq-relay/tests/integration/drain.rs index 97d1e90cccf..dc94ea90750 100644 --- a/rs/moq-relay/tests/integration/drain.rs +++ b/rs/moq-relay/tests/integration/drain.rs @@ -41,7 +41,7 @@ async fn admit(observer: &shutdown::Observer, version: moq_net::Version, stalled tokio::spawn(async move { let server = moq_net::Server::new().with_versions(version.into()); let handshake = server - .accept_request(moq_net::time::now(), relay_link) + .accept_request(moq_net::time::Instant::now(), relay_link) .await .expect("relay handshake"); let request = Accepted::new(handshake, moq_auth::Transport::Quic); @@ -58,7 +58,7 @@ async fn admit(observer: &shutdown::Observer, version: moq_net::Version, stalled }); let (client, driver) = moq_net::Client::new() .with_versions(version.into()) - .connect(moq_net::time::now(), client_link) + .connect(moq_net::time::Instant::now(), client_link) .await .expect("client handshake"); diff --git a/rs/moq-relay/tests/integration/memory.rs b/rs/moq-relay/tests/integration/memory.rs index c5c7c2367f1..f06174d4b30 100644 --- a/rs/moq-relay/tests/integration/memory.rs +++ b/rs/moq-relay/tests/integration/memory.rs @@ -30,7 +30,7 @@ pub async fn connect( let (cluster, auth) = (cluster.clone(), auth.clone()); tokio::spawn(async move { let server = moq_net::Server::new().with_versions(version.into()); - let Ok(handshake) = server.accept_request(moq_net::time::now(), relay_link).await else { + let Ok(handshake) = server.accept_request(moq_net::time::Instant::now(), relay_link).await else { return; }; let request = Accepted::new(handshake, moq_auth::Transport::Quic); @@ -39,7 +39,7 @@ pub async fn connect( let (session, driver) = client .with_versions(version.into()) - .connect(moq_net::time::now(), client_link) + .connect(moq_net::time::Instant::now(), client_link) .await?; tokio::spawn(moq_net::time::run(driver)); Ok(session) diff --git a/rs/moq-relay/tests/integration/refusals.rs b/rs/moq-relay/tests/integration/refusals.rs index ede5bec86e0..40dc797f5be 100644 --- a/rs/moq-relay/tests/integration/refusals.rs +++ b/rs/moq-relay/tests/integration/refusals.rs @@ -225,7 +225,7 @@ async fn unavailable_auth_server_is_counted() { /// A refusal creates the root stats group even when no session was ever admitted. #[tokio::test] async fn refused_only_stats_depth_one_has_root_totals_and_shared_embedder_metrics() { - use moq_net::stats::{Refusal, Tier}; + use moq_net::stats::{RefusalKind, Tier}; let dir = tempfile::tempdir().unwrap(); let mut config = config(dir.path(), false); config.auth.public = vec!["anon/**".parse().unwrap()]; @@ -265,7 +265,7 @@ async fn refused_only_stats_depth_one_has_root_totals_and_shared_embedder_metric relay .stats .tier(Tier::new("gateway")) - .refuse("tenant", Refusal::Forbidden); + .refuse("tenant", RefusalKind::Forbidden); assert_eq!( relay.refused("forbidden").await, 1, diff --git a/rs/moq-room/src/chat.rs b/rs/moq-room/src/chat.rs index b9d2db7e208..58f26667fc8 100644 --- a/rs/moq-room/src/chat.rs +++ b/rs/moq-room/src/chat.rs @@ -256,7 +256,7 @@ mod tests { tokio::join!( async { let (session, driver) = client - .connect_lite(moq_net::time::now(), client_transport) + .connect_lite(moq_net::time::Instant::now(), client_transport) .await .unwrap(); tokio::spawn(moq_net::time::run(driver)); @@ -264,7 +264,7 @@ mod tests { }, async { let (session, driver) = server - .accept_lite(moq_net::time::now(), server_transport) + .accept_lite(moq_net::time::Instant::now(), server_transport) .await .unwrap(); tokio::spawn(moq_net::time::run(driver)); diff --git a/rs/moq-srt/src/server.rs b/rs/moq-srt/src/server.rs index 41511572626..1deb8ad1af4 100644 --- a/rs/moq-srt/src/server.rs +++ b/rs/moq-srt/src/server.rs @@ -602,7 +602,7 @@ pub(crate) async fn serve_subscribe( // program clock re-anchors the pacing rather than mapping the new timeline // through the old anchor. srt-tokio paces on std's clock, where a late payload // keeps its past instant, so TSBPD still sees its spacing from its neighbors. - for (at, payload) in egress.push(&frame, subscriber.discontinuity(), moq_net::time::now()) { + for (at, payload) in egress.push(&frame, subscriber.discontinuity(), moq_net::time::Instant::now()) { socket.send((at.into_std(), payload)).await?; } } @@ -682,7 +682,7 @@ mod tests { /// already buffered from an earlier pacing instant. #[test] fn chunker_flushes_before_the_pacing_instant_changes() { - let first = moq_net::time::now(); + let first = moq_net::time::Instant::now(); let second = first + Duration::from_millis(25); let mut chunker = SrtChunker::default(); @@ -790,7 +790,7 @@ mod tests { fn the_33_bit_wrap_is_not_a_rewind() { // 2^33 ticks of the 90 kHz TS clock, in microseconds: where a PTS wraps. const WRAP: u64 = (1u64 << 33) * 100 / 9; - let start = moq_net::time::now(); + let start = moq_net::time::Instant::now(); let mut egress = Egress::default(); let before = egress.push(&frame(WRAP - 25_000, &[1; SRT_PAYLOAD]), 0, start); @@ -817,7 +817,7 @@ mod tests { #[test] fn a_new_clock_re_anchors_the_pacing() { const SLOT: Duration = Duration::from_millis(25); - let start = moq_net::time::now(); + let start = moq_net::time::Instant::now(); let mut egress = Egress::default(); // Ten minutes into the program, on the muxer's 25ms grid. @@ -849,7 +849,7 @@ mod tests { #[test] fn a_new_clock_flushes_the_partial_chunk_first() { const SLOT: Duration = Duration::from_millis(25); - let start = moq_net::time::now(); + let start = moq_net::time::Instant::now(); let mut egress = Egress::default(); // A partial chunk buffered under the first generation, then a new clock paced at diff --git a/rs/moq-srt/src/ts.rs b/rs/moq-srt/src/ts.rs index cbee735bb79..3e854d13ce5 100644 --- a/rs/moq-srt/src/ts.rs +++ b/rs/moq-srt/src/ts.rs @@ -102,7 +102,7 @@ impl Publisher { Ok(Self { importer, log: ts::stats::Log::default(), - sampled: moq_net::time::now(), + sampled: moq_net::time::Instant::now(), span: tracing::info_span!("srt", %path), }) } @@ -120,7 +120,7 @@ impl Publisher { } .map_err(moq_mux::Error::from)?; if self.sampled.elapsed() >= ts::stats::Log::INTERVAL { - self.sampled = moq_net::time::now(); + self.sampled = moq_net::time::Instant::now(); let _span = self.span.enter(); self.log.sample(self.stats()); } diff --git a/rs/moq-stats/MIGRATE.md b/rs/moq-stats/MIGRATE.md index a7c8ddf77f9..ce5ae41548c 100644 --- a/rs/moq-stats/MIGRATE.md +++ b/rs/moq-stats/MIGRATE.md @@ -4,6 +4,10 @@ How to update your code for each breaking change, newest first. ## Unreleased +### `Refusal` is `RefusalKind` (#6510) + +The re-exported `moq_stats::Refusal` follows moq-net's rename: use `moq_stats::RefusalKind`. + ### The `.z` flavor ends with the plain one past 32 MB A frame whose uncompressed JSON passes the 32 MB group budget now ends both the plain track and its `.z` sibling with `FrameTooLarge`: a reader inflates the whole group, so compression no longer carries a larger frame. diff --git a/rs/moq-stats/src/lib.rs b/rs/moq-stats/src/lib.rs index d4a358fca7a..7aa568e920c 100644 --- a/rs/moq-stats/src/lib.rs +++ b/rs/moq-stats/src/lib.rs @@ -46,7 +46,7 @@ use std::collections::BTreeMap; /// Counter collection, re-exported from [`moq_net::stats`] so stats consumers /// can depend on this crate alone. -pub use moq_net::stats::{Failure, Failures, Handle, Presence, Refusal, Refusals, Registry, Role, Tier, Traffic}; +pub use moq_net::stats::{Failure, Failures, Handle, Presence, RefusalKind, Refusals, Registry, Role, Tier, Traffic}; use moq_net::{AsPath, Path, PathOwned}; diff --git a/rs/moq-tokio/src/client.rs b/rs/moq-tokio/src/client.rs index 6b7074796a8..e72efc09a32 100644 --- a/rs/moq-tokio/src/client.rs +++ b/rs/moq-tokio/src/client.rs @@ -772,7 +772,7 @@ async fn connect_session( client: &moq_net::Client, transport: S, ) -> Result { - let (session, driver) = client.connect(moq_net::time::now(), transport).await?; + let (session, driver) = client.connect(moq_net::time::Instant::now(), transport).await?; use tracing::Instrument; tokio::spawn(crate::panic::isolate(moq_net::time::run(driver)).instrument(tracing::Span::current())); Ok(session) diff --git a/rs/moq-tokio/src/connection/auth.rs b/rs/moq-tokio/src/connection/auth.rs index 761a4bd23aa..8ec71205cc3 100644 --- a/rs/moq-tokio/src/connection/auth.rs +++ b/rs/moq-tokio/src/connection/auth.rs @@ -426,7 +426,7 @@ mod tests { qmux::Session::accept(stream(server), config()) ) .unwrap(); - let now = moq_net::time::now(); + let now = moq_net::time::Instant::now(); let client = async { let (session, driver) = moq_net::Client::new() .with_versions(versions.clone()) diff --git a/rs/moq-tokio/src/server.rs b/rs/moq-tokio/src/server.rs index 935e76922f3..267b6d4ea10 100644 --- a/rs/moq-tokio/src/server.rs +++ b/rs/moq-tokio/src/server.rs @@ -1060,7 +1060,7 @@ where S::RecvStream: moq_net::transport::MaybeSync, { let deadline = deadline.map(|at| Deadline::new(at, session.clone())); - let accept = async { Ok(server.accept_request(moq_net::time::now(), session).await?) }; + let accept = async { Ok(server.accept_request(moq_net::time::Instant::now(), session).await?) }; let request = Deadline::bound(deadline.as_ref(), accept).await?; Ok((request, deadline)) } @@ -2479,7 +2479,9 @@ mod tests { let client = tokio::spawn({ let recorder = crate::transport::Session::new(recorder.clone(), moq_net::transport::Binding::Uri); async move { - let _ = moq_net::Client::new().connect(moq_net::time::now(), recorder).await; + let _ = moq_net::Client::new() + .connect(moq_net::time::Instant::now(), recorder) + .await; } }); tokio::time::sleep(std::time::Duration::from_secs(1)).await; @@ -2538,7 +2540,7 @@ mod tests { let transport = client.clone(); let connect = tokio::spawn(async move { let (session, driver) = moq_net::Client::new() - .connect(moq_net::time::now(), transport) + .connect(moq_net::time::Instant::now(), transport) .await .expect("client handshake"); tokio::spawn(moq_net::time::run(driver)); @@ -2582,7 +2584,7 @@ mod tests { .await .expect("upgrade"); let (_session, driver) = moq_net::Client::new() - .connect(moq_net::time::now(), session) + .connect(moq_net::time::Instant::now(), session) .await .expect("client handshake"); moq_net::time::run(driver).await diff --git a/rs/moq-transcode/src/catalog.rs b/rs/moq-transcode/src/catalog.rs index f21c0f5d6e9..48561ae003c 100644 --- a/rs/moq-transcode/src/catalog.rs +++ b/rs/moq-transcode/src/catalog.rs @@ -1025,9 +1025,9 @@ mod tests { // A minute in, the source's mapping is far from the one a fresh clock would advertise. let ago = Duration::from_secs(60); - let _ = moq_net::time::now(); + let _ = moq_net::time::Instant::now(); tokio::time::advance(ago).await; - let clock = moq_mux::Clock::at(moq_net::time::now() - ago, SystemTime::now() - ago).unwrap(); + let clock = moq_mux::Clock::at(moq_net::time::Instant::now() - ago, SystemTime::now() - ago).unwrap(); let mut input = moq_net::broadcast::Info::default().produce(); let source = moq_mux::catalog::Producer::new(&mut input, moq_mux::catalog::Config::default().with_clock(clock)).unwrap(); diff --git a/rs/moq-uring/benches/session_lite.rs b/rs/moq-uring/benches/session_lite.rs index e59725e755d..be79a37630f 100644 --- a/rs/moq-uring/benches/session_lite.rs +++ b/rs/moq-uring/benches/session_lite.rs @@ -141,7 +141,7 @@ mod linux { let (session, driver) = moq_net::Server::new() .with_publisher(&pub_origin) .accept_lite( - moq_net::time::now(), + moq_net::time::Instant::now(), moq_uring::transport::Session::new( quic::web::Session::raw(conn), moq_net::transport::Binding::InBand, @@ -160,7 +160,7 @@ mod linux { let (session, driver) = moq_net::Client::new() .with_subscriber(sub_origin.clone()) .connect_lite( - moq_net::time::now(), + moq_net::time::Instant::now(), moq_uring::transport::Session::new( quic::web::Session::raw(conn), moq_net::transport::Binding::InBand, diff --git a/rs/moq-uring/src/worker.rs b/rs/moq-uring/src/worker.rs index 42856a95dfa..166b2b3946e 100644 --- a/rs/moq-uring/src/worker.rs +++ b/rs/moq-uring/src/worker.rs @@ -1025,12 +1025,12 @@ mod tests { fn the_worker_reads_its_manual_clocks_wall_time() { let Some((mut worker, clock)) = manual() else { return }; clock.advance(Duration::from_secs(5)); - let (wall, anchor) = worker - .block_on(async { (moq_clock::wall(), moq_clock::anchor()) }) + let (wall, origin) = worker + .block_on(async { (moq_clock::wall(), moq_clock::origin()) }) .unwrap(); assert_eq!(wall, clock.wall(), "the worker read the host's wall time"); - assert_eq!(anchor.0, clock.now()); - assert_eq!(anchor.1, clock.wall()); + assert_eq!(origin.0, clock.now()); + assert_eq!(origin.1, clock.wall()); } /// A timer made between turns counts from the clock, not from the last turn's diff --git a/rs/moq-uring/tests/integration/session.rs b/rs/moq-uring/tests/integration/session.rs index eceb3bd7ca3..fed97a56a9b 100644 --- a/rs/moq-uring/tests/integration/session.rs +++ b/rs/moq-uring/tests/integration/session.rs @@ -94,7 +94,7 @@ fn lite_session_over_the_worker() { let (session, driver) = moq_net::Server::new() .with_publisher(&pub_origin) .accept_lite( - moq_net::time::now(), + moq_net::time::Instant::now(), moq_uring::transport::Session::new(quic::web::Session::raw(conn), moq_net::transport::Binding::InBand), ) .await @@ -117,7 +117,7 @@ fn lite_session_over_the_worker() { let (session, driver) = moq_net::Client::new() .with_subscriber(sub.clone()) .connect_lite( - moq_net::time::now(), + moq_net::time::Instant::now(), moq_uring::transport::Session::new( quic::web::Session::raw(conn), moq_net::transport::Binding::InBand, @@ -229,7 +229,7 @@ fn two_lite_sessions_share_the_server_socket() { let (session, driver) = moq_net::Server::new() .with_publisher(&pub_origin) .accept_lite( - moq_net::time::now(), + moq_net::time::Instant::now(), moq_uring::transport::Session::new( quic::web::Session::raw(conn), moq_net::transport::Binding::InBand, @@ -258,7 +258,7 @@ fn two_lite_sessions_share_the_server_socket() { let (session, driver) = moq_net::Client::new() .with_subscriber(sub.clone()) .connect_lite( - moq_net::time::now(), + moq_net::time::Instant::now(), moq_uring::transport::Session::new( quic::web::Session::raw(conn), moq_net::transport::Binding::InBand, diff --git a/rs/moq-uring/tests/integration/web.rs b/rs/moq-uring/tests/integration/web.rs index b334a60a880..93bf022d3b0 100644 --- a/rs/moq-uring/tests/integration/web.rs +++ b/rs/moq-uring/tests/integration/web.rs @@ -285,7 +285,7 @@ fn lite_session_over_webtransport() { let (moq, session_driver) = moq_net::Client::new() .with_subscriber(sub_origin.clone()) .connect_lite( - moq_net::time::now(), + moq_net::time::Instant::now(), moq_tokio::transport::Session::new(session, moq_net::transport::Binding::Uri), ) .await @@ -336,7 +336,7 @@ fn lite_session_over_webtransport() { let (session, driver) = moq_net::Server::new() .with_publisher(&serve_origin) .accept_lite( - moq_net::time::now(), + moq_net::time::Instant::now(), moq_uring::transport::Session::new(session, moq_net::transport::Binding::Uri), ) .await diff --git a/rs/moq-video/src/encode/producer.rs b/rs/moq-video/src/encode/producer.rs index d71957a3dda..cf10d0e6dcf 100644 --- a/rs/moq-video/src/encode/producer.rs +++ b/rs/moq-video/src/encode/producer.rs @@ -202,13 +202,13 @@ impl Producer { let mut frames = split.decode(&frame.payload, timestamp)?; frames.extend(split.flush(timestamp)?); import.decode(frames)?; - import.flush(frame.timestamp, moq_net::time::now())?; + import.flush(frame.timestamp, moq_net::time::Instant::now())?; } Codecs::H265 { split, import } => { let mut frames = split.decode(&frame.payload, timestamp)?; frames.extend(split.flush(timestamp)?); import.decode(frames)?; - import.flush(frame.timestamp, moq_net::time::now())?; + import.flush(frame.timestamp, moq_net::time::Instant::now())?; } } } @@ -605,7 +605,7 @@ async fn apply_estimate( return; }; - let Some(bitrate) = control.update(estimate, moq_net::time::now()) else { + let Some(bitrate) = control.update(estimate, moq_net::time::Instant::now()) else { return; }; diff --git a/rs/moq-wasm/src/lib.rs b/rs/moq-wasm/src/lib.rs index 89877491265..f21c58317d1 100644 --- a/rs/moq-wasm/src/lib.rs +++ b/rs/moq-wasm/src/lib.rs @@ -126,7 +126,10 @@ impl Session { let client = moq_net::Client::new().with_subscriber(origin); // The driver holds no session clone, so dropping this `Session` still // closes the transport and ends the spawned task. - let (inner, driver) = client.connect(moq_net::time::now(), transport).await.map_err(js_err)?; + let (inner, driver) = client + .connect(moq_net::time::Instant::now(), transport) + .await + .map_err(js_err)?; web_async::spawn(async move { moq_net::time::run(driver).await; }); From 8eb878975c24e53b27e59aafc6bef09deaa2d12e Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:42:14 -0700 Subject: [PATCH 3/3] fix(clock): keep Installed free of the disposable lib Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EeyiEy5FWz3z44DYZVo7vU --- doc/lib/js/clock.md | 3 +-- js/clock/MIGRATE.md | 4 +--- js/clock/src/ambient.ts | 13 +++++++------ js/net/src/goaway-requests.test.ts | 3 ++- js/net/src/ietf/aliases.test.ts | 3 ++- js/net/src/ietf/subscribe_tracks.test.ts | 15 ++++++++++----- js/net/src/ietf/tail.test.ts | 3 ++- test/audio-quality/clients/js/src/probe.test.ts | 4 ++-- 8 files changed, 27 insertions(+), 21 deletions(-) diff --git a/doc/lib/js/clock.md b/doc/lib/js/clock.md index 4c4b225378f..f3b5ca05387 100644 --- a/doc/lib/js/clock.md +++ b/doc/lib/js/clock.md @@ -57,8 +57,7 @@ wall time without the jitter of subtracting two live reads. On the host it is the realm's performance time origin; on a `Manual` it follows `stepWall()`. Installation is scoped to the current JS realm. Close the handle `install()` -returns in `finally`, or hold it with `using`, and keep tests sharing that -realm serial. Timers remain bound to the clock on +returns in `finally`, and keep tests sharing that realm serial. Timers remain bound to the clock on which they were created, even after restoration. Host timers used by a test runner or RPC framework keep running in real time. diff --git a/js/clock/MIGRATE.md b/js/clock/MIGRATE.md index febbca4ce77..7939225d4c8 100644 --- a/js/clock/MIGRATE.md +++ b/js/clock/MIGRATE.md @@ -7,7 +7,7 @@ How to update your code for each breaking change, newest first. ### `Manual.install()` returns an `Installed` handle (#6510) `install()` returns an `Installed` handle instead of a restore function, matching Rust's `Manual::install`. -Call `installed.close()` where you called `restore()`, or hold it with `using`: +Call `installed.close()` where you called `restore()`: ```ts // Before @@ -17,8 +17,6 @@ restore(); // After const installed = clock.install(); installed.close(); -// or -using _installed = clock.install(); ``` ### Manual time steps through timer deadlines diff --git a/js/clock/src/ambient.ts b/js/clock/src/ambient.ts index 8d515da4b3b..4936048b30f 100644 --- a/js/clock/src/ambient.ts +++ b/js/clock/src/ambient.ts @@ -4,7 +4,7 @@ import { host } from "./host.ts"; let current: { backend: Backend; previous?: typeof current; active: boolean } = { backend: host, active: true }; /** A clock installed in the current realm; close it to restore the clock it replaced. */ -export interface Installed extends Disposable { +export interface Installed { /** Restore the clock this one replaced. Idempotent, and safe out of order. */ close(): void; } @@ -16,10 +16,11 @@ export function backend(): Backend { export function install(backend: Backend): Installed { const entry = { backend, previous: current, active: true }; current = entry; - const close = () => { - entry.active = false; - // Out-of-order cleanup must not revive an already-restored outer clock. - while (!current.active && current.previous) current = current.previous; + return { + close: () => { + entry.active = false; + // Out-of-order cleanup must not revive an already-restored outer clock. + while (!current.active && current.previous) current = current.previous; + }, }; - return { close, [Symbol.dispose]: close }; } diff --git a/js/net/src/goaway-requests.test.ts b/js/net/src/goaway-requests.test.ts index 33c59daffef..70d541ea09b 100644 --- a/js/net/src/goaway-requests.test.ts +++ b/js/net/src/goaway-requests.test.ts @@ -293,7 +293,8 @@ test("announcing and subscribing after GOAWAY still open streams, on the adapter */ async function routeDeath(kind: "lite" | "ietf", after: boolean): Promise { const clock = new Manual(); - using _clock = clock.install(); + const installed = clock.install(); + using _clock = { [Symbol.dispose]: () => installed.close() }; const protocol = kind === "lite" ? ALPN_06 : ALPN.DRAFT_17; const pair = createMockTransportPair(protocol); const inject = kind === "ietf" ? captureFirstUni(pair.server) : undefined; diff --git a/js/net/src/ietf/aliases.test.ts b/js/net/src/ietf/aliases.test.ts index 8fa8c30f19e..7da96f0325e 100644 --- a/js/net/src/ietf/aliases.test.ts +++ b/js/net/src/ietf/aliases.test.ts @@ -107,7 +107,8 @@ test("a later subscribe reclaims a retired alias", async () => { // one entry per alias it ever used. test("retired aliases are capped", async () => { const clock = new Manual(); - using _clock = clock.install(); + const installed = clock.install(); + using _clock = { [Symbol.dispose]: () => installed.close() }; const aliases = new TrackAliases(); for (let i = 0n; i < 74n; i++) { diff --git a/js/net/src/ietf/subscribe_tracks.test.ts b/js/net/src/ietf/subscribe_tracks.test.ts index a8752d48259..3acd052c0f5 100644 --- a/js/net/src/ietf/subscribe_tracks.test.ts +++ b/js/net/src/ietf/subscribe_tracks.test.ts @@ -92,7 +92,8 @@ async function update(stream: Stream, version: IetfVersion, id: bigint, forward: for (const version of drafts) { test(`track listing pauses, resumes, survives listing cancellation and ends on withdrawal (${version})`, async () => { const clock = new Manual(); - using _installed = clock.install(); + const installed = clock.install(); + using _installed = { [Symbol.dispose]: () => installed.close() }; const fx = fixture(version); const broadcast = fx.origin.createBroadcast(Path.from("room/live")); broadcast.announce(); @@ -203,7 +204,8 @@ test("draft-18 refuses SUBSCRIBE to a PUBLISHed track", async () => { test("a cancelled listing cannot release its replacement's prefix", async () => { const version = Version.DRAFT_22; const clock = new Manual(); - using _installed = clock.install(); + const installed = clock.install(); + using _installed = { [Symbol.dispose]: () => installed.close() }; const fx = fixture(version); const broadcast = fx.origin.createBroadcast(Path.from("room/live")); broadcast.announce(); @@ -228,7 +230,8 @@ test("grants hide tracks, revoke PUBLISHes and relist when broadened", async () const empty = (): Grant => ({ publish: new Path.Patterns([]), subscribe: new Path.Patterns([]) }); const grant = new Signal(empty()); const clock = new Manual(); - using _installed = clock.install(); + const installed = clock.install(); + using _installed = { [Symbol.dispose]: () => installed.close() }; const fx = fixture(version, 10, grant); const listing = await fx.list(); await ok(listing, version); @@ -292,7 +295,8 @@ test("paused updates keep one slot and release it when the PUBLISH ends", async const version = Version.DRAFT_22; const fx = fixture(version, 1); const clock = new Manual(); - using _installed = clock.install(); + const installed = clock.install(); + using _installed = { [Symbol.dispose]: () => installed.close() }; const broadcast = fx.origin.createBroadcast(Path.from("room/live")); broadcast.announce(); broadcast.createTrack("video"); @@ -313,7 +317,8 @@ test("a failed PUBLISH stream open returns its subscription slot", async () => { const version = Version.DRAFT_22; const fx = fixture(version, 1); const clock = new Manual(); - using _installed = clock.install(); + const installed = clock.install(); + using _installed = { [Symbol.dispose]: () => installed.close() }; const open = spyOn(fx.session, "openBi").mockRejectedValue(new StreamError(StreamCode.Cancel)); const broadcast = fx.origin.createBroadcast(Path.from("room/live")); broadcast.announce(); diff --git a/js/net/src/ietf/tail.test.ts b/js/net/src/ietf/tail.test.ts index 08301d3c8dd..23a16bf55f8 100644 --- a/js/net/src/ietf/tail.test.ts +++ b/js/net/src/ietf/tail.test.ts @@ -133,7 +133,8 @@ test("a group read across PUBLISH_DONE is delivered whole", async () => { test("a Stream Count of 0 is a hint, so a late stream within the grace is still delivered", async () => { const clock = new Manual(); - using _clock = clock.install(); + const installed = clock.install(); + using _clock = { [Symbol.dispose]: () => installed.close() }; const { subscriber, reader, done } = await subscribed(); await done(TRACK_ENDED, 0n); diff --git a/test/audio-quality/clients/js/src/probe.test.ts b/test/audio-quality/clients/js/src/probe.test.ts index ce69d2c1973..9df2a49b35f 100644 --- a/test/audio-quality/clients/js/src/probe.test.ts +++ b/test/audio-quality/clients/js/src/probe.test.ts @@ -12,7 +12,7 @@ const { probe } = await import("./probe.ts"); test("audio-only sampling holds probe demand until its final RTT sample", async () => { jest.useFakeTimers(); const clock = new Manual(); - const restore = clock.install(); + const installed = clock.install(); const network = new Observed<{ rtt: Milli } | undefined>(undefined); const producer = new Effect((effect) => { if (effect.get(network.used)) effect.set(network, { rtt: Milli(12) }, undefined); @@ -41,7 +41,7 @@ test("audio-only sampling holds probe demand until its final RTT sample", async expect(measurement.drain()).toEqual([]); } finally { producer.close(); - restore(); + installed.close(); jest.useRealTimers(); } });