From 07d2a36e2e78c0040cde963f3b67f43ee9becc12 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 09:25:38 -0800 Subject: [PATCH 01/17] chore(quest): claim quest/m2/js-time-types.md Quest-Claim: 1eda9c38859df4e9 From e7619d87d8c0b6d14d7346f497a63756695adb27 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 09:31:53 -0800 Subject: [PATCH 02/17] feat(clock,signals)!: Duration, Instant, and Wall are classes Co-Authored-By: Claude Opus 5.5 --- doc/lib/js/clock.md | 29 ++- doc/lib/js/signals.md | 6 +- js/clock/README.md | 8 +- js/clock/bench/timers.ts | 8 +- js/clock/src/guard.test.ts | 6 +- js/clock/src/index.test.ts | 333 ++++++++++++++------------- js/clock/src/index.ts | 15 +- js/clock/src/manual.ts | 41 ++-- js/clock/src/timer.ts | 38 ++-- js/clock/src/types.ts | 428 ++++++++++++++++++++++++++++------- js/signals/README.md | 6 +- js/signals/src/index.test.ts | 53 +++-- js/signals/src/index.ts | 21 +- 13 files changed, 650 insertions(+), 342 deletions(-) diff --git a/doc/lib/js/clock.md b/doc/lib/js/clock.md index 418be7bb7bd..77d434c1dbd 100644 --- a/doc/lib/js/clock.md +++ b/doc/lib/js/clock.md @@ -17,33 +17,38 @@ bun add @moq/clock ``` ```ts -import { Manual, Milli, Nano, now, sleep } from "@moq/clock"; +import { Duration, Manual, now, sleep } from "@moq/clock"; const clock = new Manual(); const installed = clock.install(); try { const start = now(); - const pending = sleep(Nano.fromMilli(Milli(10))); - await clock.advance(Nano.fromMilli(Milli(10))); + const pending = sleep(Duration.millis(10)); + await clock.advance(Duration.millis(10)); await pending; - console.log(now() - start); // 10,000,000 nanoseconds + console.log(now().since(start).asMillis()); // 10 } finally { installed.close(); } ``` -`Instant` counts nanoseconds from its clock's origin: the realm's performance -time origin on the host, so DOM timestamps convert by unit, or zero for a -`Manual` clock. `Nano`, `Micro`, -`Milli`, and `Second` brand duration units; convert a duration to nanoseconds -before passing it to a timer. Number nanoseconds are exact for roughly 104 +`Duration`, `Instant`, and `Wall` are immutable objects that mirror Rust's +`Duration` and `kio::clock`'s `Instant` and `Wall`. Build a duration with a unit +(`Duration.millis(5)`) and read it with one (`asMillis()`); compare with +`lt`, `ge`, and friends. None of them converts to a number: arithmetic, `<`, +and `JSON.stringify` throw a `TypeError`, so a unit mistake can't hide behind a +cast. A template string prints one with its unit. + +`Instant` counts from its clock's origin: the realm's performance time origin +on the host, so a DOM timestamp `t` is `Instant.ZERO.add(Duration.millis(t))`, +or zero for a `Manual` clock. Its nanoseconds are exact for roughly 104 days, then gradually lose sub-microsecond precision. Compare instants only from the same clock. Rust and JS each own their origin: no instant may cross that boundary until the backend explicitly shares one. -`Wall` is a separate branded number of milliseconds since the Unix epoch. -Use it for dates, rather than measuring elapsed time. A Rust wall-time -boundary must convert its units explicitly. A new `Manual` starts at instant +`Wall` is wall-clock time, separate from monotonic time: Unix milliseconds `ms` +are `Wall.UNIX_EPOCH.add(Duration.millis(ms))`. Use it for dates, rather than +measuring elapsed time. A new `Manual` starts at instant zero and 2025-01-01 UTC. `await advance()` moves both readings through each due timer deadline, draining tasks between deadlines, including timers those tasks re-arm before the target. `yieldNow()` waits for a later host task, giving the diff --git a/doc/lib/js/signals.md b/doc/lib/js/signals.md index 1bb3f8aa560..faf2cc5d0a7 100644 --- a/doc/lib/js/signals.md +++ b/doc/lib/js/signals.md @@ -21,14 +21,14 @@ the rest. | `Derived` | A cheap mapped view with no lifecycle. | ```ts -import { Milli, Nano } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { Effect, Signal } from "@moq/signals"; const volume = new Signal(1); const effect = new Effect((effect) => { const v = effect.get(volume); // read AND subscribe; peek() reads without subscribing - effect.interval(() => console.log(v), Nano.fromMilli(Milli(1000))); // cancelled on rerun or close + effect.interval(() => console.log(v), Duration.secs(1)); // cancelled on rerun or close effect.cleanup(() => console.log("bye")); }); @@ -40,7 +40,7 @@ The rules that differ from other signal libraries: - **Nothing is tracked implicitly.** `effect.get(signal)` subscribes; `signal.peek()` doesn't. - **Writes coalesce per microtask** and only notify on a real change (deep for plain objects, identity for class instances). -- **Effects own their resources.** `effect.timer`, `interval`, `animate`, `event`, `spawn`, and `run` (a nested effect) all clean up on rerun or close, so never call `setTimeout` or `addEventListener` inside one directly. Timers take `Nano` durations and run on the [`@moq/clock`](./clock) clock, so a `Manual` clock drives them in tests. +- **Effects own their resources.** `effect.timer`, `interval`, `animate`, `event`, `spawn`, and `run` (a nested effect) all clean up on rerun or close, so never call `setTimeout` or `addEventListener` inside one directly. Timers take a `Duration` and run on the [`@moq/clock`](./clock) clock, so a `Manual` clock drives them in tests. - **Teardown runs last-in, first-out**, like `DisposableStack`. - **Race with `race`, not `Promise.race`.** `Promise.race` leaves a listener on every loser, so racing a long-lived promise once per frame grows the heap. `race([...])` and `effect.race(promise)` drop their listeners when they settle. - **Misuse warns in every build**, with the effect's creation stack: effects that tracked nothing, or were garbage-collected without `close()`. diff --git a/js/clock/README.md b/js/clock/README.md index 561634a60f6..b1a0fe6edbc 100644 --- a/js/clock/README.md +++ b/js/clock/README.md @@ -4,15 +4,15 @@ Logical monotonic time, wall time, and timers from one clock per JavaScript real Use `Manual` to test time without replacing the host's timers. ```ts -import { Manual, Milli, Nano, now, sleep } from "@moq/clock"; +import { Duration, Instant, Manual, now, sleep } from "@moq/clock"; const clock = new Manual(); const installed = clock.install(); try { - const pending = sleep(Nano.fromMilli(Milli(10))); - await clock.advance(Nano.fromMilli(Milli(10))); + const pending = sleep(Duration.millis(10)); + await clock.advance(Duration.millis(10)); await pending; - console.log(now()); // 10,000,000 nanoseconds + console.log(now().since(Instant.ZERO).asMillis()); // 10 } finally { installed.close(); } diff --git a/js/clock/bench/timers.ts b/js/clock/bench/timers.ts index 36ce4e7e18f..d8803805130 100644 --- a/js/clock/bench/timers.ts +++ b/js/clock/bench/timers.ts @@ -1,5 +1,5 @@ // Sweep armed timers x timers made ready, with independent and shared abort scopes. -import { Manual, Nano, sleep } from "../src/index.ts"; +import { Duration, Manual, sleep } from "../src/index.ts"; console.log("mode,scope,armed,ready,arm_us,advance_us,cancel_us"); for (const mode of ["jump", "advance"]) { @@ -14,13 +14,13 @@ for (const mode of ["jump", "advance"]) { try { const start = performance.now(); const timers = Array.from({ length: armed }, (_, index) => - sleep(Nano(index < ready ? index + 1 : armed + 1), { + sleep(Duration.nanos(index < ready ? index + 1 : armed + 1), { signal: aborts[index % aborts.length].signal, }).catch(() => {}), ); const armedAt = performance.now(); - if (mode === "jump") clock.jump(Nano(ready)); - else await clock.advance(Nano(ready)); + if (mode === "jump") clock.jump(Duration.nanos(ready)); + else await clock.advance(Duration.nanos(ready)); const advancedAt = performance.now(); for (const abort of aborts) abort.abort(); const cancelledAt = performance.now(); diff --git a/js/clock/src/guard.test.ts b/js/clock/src/guard.test.ts index 45878ddcbf0..464558baf7e 100644 --- a/js/clock/src/guard.test.ts +++ b/js/clock/src/guard.test.ts @@ -8,10 +8,10 @@ const src = import.meta.dir; // Each case runs as its own test under the real preload, since the guard fails a test from a host callback. const fixture = ` import { test } from "bun:test"; -import { Milli, Nano, sleep, timeout, yieldNow } from "${join(src, "index.ts")}"; +import { Duration, sleep, timeout, yieldNow } from "${join(src, "index.ts")}"; import { hostTime } from "${join(src, "test.ts")}"; -const ms = (n) => Nano.fromMilli(Milli(n)); +const ms = (n) => Duration.millis(n); test("waits 50ms on the real clock", async () => { await sleep(ms(50)); @@ -23,7 +23,7 @@ test("a watchdog on progress that settles first", async () => { await timeout(ms(1000), Promise.resolve(1)); }); test("a sleep already due", async () => { - await sleep(Nano(0)); + await sleep(Duration.ZERO); }); test("opted out with hostTime", async () => { hostTime(); // the case under test diff --git a/js/clock/src/index.test.ts b/js/clock/src/index.test.ts index 7bd3d8097dd..8646c821715 100644 --- a/js/clock/src/index.test.ts +++ b/js/clock/src/index.test.ts @@ -2,18 +2,15 @@ import { afterEach, expect, test } from "bun:test"; // biome-ignore lint/style/noRestrictedImports: a host task that bypasses the installed Manual clock. import { setTimeout as hostTimeout } from "node:timers/promises"; import { + Duration, Elapsed, type Installed, Instant, interval, Manual, - Micro, - Milli, MissedTickBehavior, - Nano, now, origin, - Second, sleep, sleepUntil, timeout, @@ -32,100 +29,118 @@ function manual(): Manual { installs.push(clock.install()); return clock; } -const ns = Nano.fromMilli; - -test("units convert without permitting instant or wall time as durations", () => { - expect(Nano.fromSecond(Second(1))).toBe(1_000_000_000); - expect(Micro.fromMilli(Milli(2))).toBe(2000); - expect(Milli.fromNano(Nano(1_500_000))).toBe(1.5); - expect(Second.fromMicro(Micro(2_000_000))).toBe(2); - expect(() => Nano(-1)).toThrow(RangeError); - expect(() => Milli(Number.POSITIVE_INFINITY)).toThrow(RangeError); - expect(() => Instant(Number.NaN)).toThrow(RangeError); +// Read an instant or wall time as a plain number for assertions. +const ns = (at: Instant): number => at.since(Instant.ZERO).asNanos(); +const ms = (at: Wall): number => at.since(Wall.UNIX_EPOCH).asMillis(); +const instant = (nanos: number): Instant => Instant.ZERO.add(Duration.nanos(nanos)); +const unix = (millis: number): Wall => Wall.UNIX_EPOCH.add(Duration.millis(millis)); +const START = ms(Manual.WALL_START); + +test("durations convert units and refuse to become numbers", () => { + expect(Duration.secs(1).asNanos()).toBe(1_000_000_000); + expect(Duration.millis(2).asMicros()).toBe(2000); + expect(Duration.nanos(1_500_000).asMillis()).toBe(1.5); + expect(Duration.micros(2_000_000).asSecs()).toBe(2); + expect(() => Duration.nanos(-1)).toThrow(RangeError); + expect(() => Duration.millis(Number.POSITIVE_INFINITY)).toThrow(RangeError); + expect(() => instant(Number.NaN)).toThrow(RangeError); + expect(() => Duration.millis(1).sub(Duration.millis(2))).toThrow(RangeError); + expect(() => Instant.ZERO.sub(Duration.nanos(1))).toThrow(RangeError); + expect(Duration.millis(1).saturatingSub(Duration.millis(2)).isZero()).toBe(true); + expect(instant(5).since(instant(9)).isZero()).toBe(true); + expect(`${Duration.micros(1500)}`).toBe("1.5ms"); + const loose: unknown = Duration.millis(1); + expect(() => (loose as number) + 1).toThrow(TypeError); + expect(() => (loose as number) < 2).toThrow(TypeError); + expect(() => JSON.stringify({ loose })).toThrow(TypeError); + expect(() => (instant(1) as unknown as number) * 2).toThrow(TypeError); + expect(() => JSON.stringify(Wall.UNIX_EPOCH)).toThrow(TypeError); if (false as boolean) { // @ts-expect-error instants are not durations - void sleep(Instant.zero); + void sleep(Instant.ZERO); // @ts-expect-error wall time is not monotonic time void sleepUntil(Wall.UNIX_EPOCH); - // @ts-expect-error milliseconds must be converted to nanoseconds - void sleep(Milli(1)); + // @ts-expect-error a duration is not a number + void sleep(5); + // @ts-expect-error a duration does not convert to a number + void (Duration.millis(1) as number); } }); test("manual reads and wall corrections share a clock without inventing elapsed time", () => { const clock = manual(); - expect(now()).toBe(0); - expect(wall()).toBe(Manual.WALL_START); - clock.jump(ns(Milli(5))); - expect(now()).toBe(5_000_000); - expect(wall()).toBe(Manual.WALL_START + 5); - clock.stepWall(Wall(Manual.WALL_START - 1000)); - expect(now()).toBe(5_000_000); - clock.stepWall(Wall(Manual.WALL_START + 1000)); - clock.jump(ns(Milli(1))); - expect(clock.now()).toBe(6_000_000); - expect(clock.wall()).toBe(Manual.WALL_START + 1001); - expect(origin()).toBe(Manual.WALL_START + 1000 - 5); + expect(ns(now())).toBe(0); + expect(ms(wall())).toBe(START); + clock.jump(Duration.millis(5)); + expect(ns(now())).toBe(5_000_000); + expect(ms(wall())).toBe(START + 5); + clock.stepWall(unix(START - 1000)); + expect(ns(now())).toBe(5_000_000); + clock.stepWall(unix(START + 1000)); + clock.jump(Duration.millis(1)); + expect(ns(clock.now())).toBe(6_000_000); + expect(ms(clock.wall())).toBe(START + 1001); + expect(ms(origin())).toBe(START + 1000 - 5); }); test("many small advances move wall time by their combined duration", () => { const clock = new Manual(); - for (let i = 0; i < 10_000; i++) clock.jump(Nano(100)); - expect(clock.now()).toBe(1_000_000); - expect(clock.wall()).toBe(Manual.WALL_START + 1); + for (let i = 0; i < 10_000; i++) clock.jump(Duration.nanos(100)); + expect(ns(clock.now())).toBe(1_000_000); + expect(ms(clock.wall())).toBe(START + 1); }); test("installation restores nested and out-of-order scopes without reviving them", () => { const outer = manual(); - outer.jump(Nano(4)); + outer.jump(Duration.nanos(4)); const inner = manual(); - inner.jump(Nano(8)); - expect(now()).toBe(8); + inner.jump(Duration.nanos(8)); + expect(ns(now())).toBe(8); installs[0].close(); - expect(now()).toBe(8); + expect(ns(now())).toBe(8); installs[1].close(); - const restored = now(); + const restored = ns(now()); installs[1].close(); - expect(now()).toBeGreaterThanOrEqual(restored); - expect(now()).not.toBe(4); + expect(ns(now())).toBeGreaterThanOrEqual(restored); + expect(ns(now())).not.toBe(4); }); test("deadlines fire in time then arming order and reached deadlines fire without advance", async () => { const clock = manual(); const order: number[] = []; - void sleepUntil(Instant(10)).then(() => order.push(2)); - void sleepUntil(Instant(5)).then(() => order.push(1)); - void sleepUntil(Instant(10)).then(() => order.push(3)); - await clock.advance(Nano(10)); + void sleepUntil(instant(10)).then(() => order.push(2)); + void sleepUntil(instant(5)).then(() => order.push(1)); + void sleepUntil(instant(10)).then(() => order.push(3)); + await clock.advance(Duration.nanos(10)); expect(order).toEqual([1, 2, 3]); - await sleepUntil(Instant(1)); - await sleep(Nano.zero); + await sleepUntil(instant(1)); + await sleep(Duration.ZERO); }); test("advance drains arbitrarily deep microtasks and newly due timers", async () => { const clock = manual(); let done = false; void (async () => { - await sleep(Nano(5)); + await sleep(Duration.nanos(5)); for (let i = 0; i < 1000; i++) await Promise.resolve(); - await sleep(Nano.zero); + await sleep(Duration.ZERO); done = true; })(); - await clock.advance(Nano(5)); + await clock.advance(Duration.nanos(5)); expect(done).toBe(true); }); for (const driver of ["advance", "fire"] as const) { test(`${driver} waits out a chain of host-task yields before moving time`, async () => { const clock = manual(); - void sleep(Nano(10)); + void sleep(Duration.nanos(10)); const seen: number[] = []; void (async () => { for (let i = 0; i < 3; i++) await yieldNow(); - seen.push(now()); + seen.push(ns(now())); })(); - if (driver === "advance") await clock.advance(Nano(10)); - else expect(await clock.fire()).toBe(10); + if (driver === "advance") await clock.advance(Duration.nanos(10)); + else expect(ns(await clock.fire())).toBe(10); expect(seen).toEqual([0]); }); } @@ -133,46 +148,46 @@ for (const driver of ["advance", "fire"] as const) { test("a sleep stays on its creation clock and abort releases it", async () => { const first = manual(); let done = false; - const pending = sleep(Nano(10)).then(() => { + const pending = sleep(Duration.nanos(10)).then(() => { done = true; }); const second = manual(); - await second.advance(Nano(10)); + await second.advance(Duration.nanos(10)); expect(done).toBe(false); - await first.advance(Nano(10)); + await first.advance(Duration.nanos(10)); await pending; const abort = new AbortController(); - const cancelled = sleep(Nano(100), { signal: abort.signal }).catch((error: unknown) => error); + const cancelled = sleep(Duration.nanos(100), { signal: abort.signal }).catch((error: unknown) => error); abort.abort(); expect(await cancelled).toHaveProperty("name", "AbortError"); - await second.advance(Nano(100)); - await expect(sleep(Nano.zero, { signal: abort.signal })).rejects.toHaveProperty("name", "AbortError"); + await second.advance(Duration.nanos(100)); + await expect(sleep(Duration.ZERO, { signal: abort.signal })).rejects.toHaveProperty("name", "AbortError"); }); test("timeouts prefer ready work, propagate rejection, and expire on the manual deadline", async () => { const clock = manual(); - expect(await timeout(Nano.zero, Promise.resolve(7))).toBe(7); + expect(await timeout(Duration.ZERO, Promise.resolve(7))).toBe(7); const failure = new Error("operation failed"); - await expect(timeout(Nano(10), Promise.reject(failure))).rejects.toBe(failure); - const pending = timeout(Nano(10), new Promise(() => {})).catch((error: unknown) => error); - await clock.advance(Nano(9)); - await clock.advance(Nano(1)); + await expect(timeout(Duration.nanos(10), Promise.reject(failure))).rejects.toBe(failure); + const pending = timeout(Duration.nanos(10), new Promise(() => {})).catch((error: unknown) => error); + await clock.advance(Duration.nanos(9)); + await clock.advance(Duration.nanos(1)); expect(await pending).toBeInstanceOf(Elapsed); }); test("interval burst delivers every missed scheduled tick", async () => { const clock = manual(); - const ticks = interval(Nano(10)); + const ticks = interval(Duration.nanos(10)); try { - expect(await ticks.tick()).toBe(0); - clock.jump(Nano(35)); - expect(await ticks.tick()).toBe(10); - expect(await ticks.tick()).toBe(20); - expect(await ticks.tick()).toBe(30); + expect(ns(await ticks.tick())).toBe(0); + clock.jump(Duration.nanos(35)); + expect(ns(await ticks.tick())).toBe(10); + expect(ns(await ticks.tick())).toBe(20); + expect(ns(await ticks.tick())).toBe(30); const next = ticks.tick(); - await clock.advance(Nano(5)); - expect(await next).toBe(40); - expect(ticks.period()).toBe(10); + await clock.advance(Duration.nanos(5)); + expect(ns(await next)).toBe(40); + expect(ticks.period().asNanos()).toBe(10); } finally { ticks.close(); } @@ -181,15 +196,15 @@ test("interval burst delivers every missed scheduled tick", async () => { for (const behavior of [MissedTickBehavior.Delay, MissedTickBehavior.Skip]) { test(`interval ${behavior} resumes after a missed tick`, async () => { const clock = manual(); - const ticks = interval(Nano(10)); + const ticks = interval(Duration.nanos(10)); ticks.setMissedTickBehavior(behavior); try { - expect(await ticks.tick()).toBe(0); - clock.jump(Nano(35)); - expect(await ticks.tick()).toBe(10); + expect(ns(await ticks.tick())).toBe(0); + clock.jump(Duration.nanos(35)); + expect(ns(await ticks.tick())).toBe(10); const next = ticks.tick(); - await clock.advance(Nano(behavior === MissedTickBehavior.Delay ? 10 : 5)); - expect(await next).toBe(behavior === MissedTickBehavior.Delay ? 45 : 40); + await clock.advance(Duration.nanos(behavior === MissedTickBehavior.Delay ? 10 : 5)); + expect(ns(await next)).toBe(behavior === MissedTickBehavior.Delay ? 45 : 40); } finally { ticks.close(); } @@ -198,8 +213,8 @@ for (const behavior of [MissedTickBehavior.Delay, MissedTickBehavior.Skip]) { test("an interval cancels pending ticks, refuses concurrent ticks and stays closed", async () => { manual(); - expect(() => interval(Nano.zero)).toThrow(RangeError); - const ticks = interval(Nano(10)); + expect(() => interval(Duration.ZERO)).toThrow(RangeError); + const ticks = interval(Duration.nanos(10)); await ticks.tick(); const pending = ticks.tick().catch((error: unknown) => error); await expect(ticks.tick()).rejects.toThrow("already pending"); @@ -213,21 +228,21 @@ test("the host clock counts from the performance time origin", () => { // biome-ignore lint/style/noRestrictedGlobals: checks the host backend against the global it wraps. const host = performance; const before = host.now(); - const at = Nano.toMilli(Instant.durationSince(now(), Instant.zero)); + const at = now().since(Instant.ZERO).asMillis(); expect(at).toBeGreaterThanOrEqual(before); expect(at).toBeLessThanOrEqual(host.now()); - expect(origin()).toBe(host.timeOrigin); + expect(ms(origin())).toBe(host.timeOrigin); }); test("an unreferenced sleep still completes on the host", async () => { hostTime(); // tests the host backend itself - await sleep(Nano.fromMilli(Milli(1)), { ref: false }); + await sleep(Duration.millis(1), { ref: false }); }); test("manual installation leaves the host's own timers real", async () => { manual(); await hostTimeout(0); - expect(now()).toBe(0); + expect(ns(now())).toBe(0); }); test("many cancelled and live timers retain deadline and arming order", async () => { @@ -240,7 +255,7 @@ test("many cancelled and live timers retain deadline and arming order", async () aborts.push(abort); const at = 1 + ((index * 73) % 17); if (index % 3 !== 0) expected.push({ at, index }); - return sleepUntil(Instant(at), { signal: abort.signal }).then( + return sleepUntil(instant(at), { signal: abort.signal }).then( () => { fired.push(index); }, @@ -248,7 +263,7 @@ test("many cancelled and live timers retain deadline and arming order", async () ); }); for (let index = aborts.length - 1; index >= 0; index--) if (index % 3 === 0) aborts[index].abort(); - await clock.advance(Nano(17)); + await clock.advance(Duration.nanos(17)); await Promise.all(pending); expect(fired).toEqual(expected.sort((a, b) => a.at - b.at || a.index - b.index).map(({ index }) => index)); }); @@ -256,62 +271,62 @@ test("many cancelled and live timers retain deadline and arming order", async () test("fire advances exactly to the earliest deadline and runs only what is due", async () => { const clock = manual(); const order: number[] = []; - void sleepUntil(Instant(30)).then(() => order.push(30)); - void sleepUntil(Instant(10)).then(() => order.push(1)); - void sleepUntil(Instant(20)).then(() => order.push(20)); - void sleepUntil(Instant(10)).then(() => order.push(2)); - clock.jump(Nano(3)); - expect(await clock.fire()).toBe(10); - expect(now()).toBe(10); + void sleepUntil(instant(30)).then(() => order.push(30)); + void sleepUntil(instant(10)).then(() => order.push(1)); + void sleepUntil(instant(20)).then(() => order.push(20)); + void sleepUntil(instant(10)).then(() => order.push(2)); + clock.jump(Duration.nanos(3)); + expect(ns(await clock.fire())).toBe(10); + expect(ns(now())).toBe(10); expect(order).toEqual([1, 2]); - expect(await clock.fire()).toBe(20); - expect(await clock.fire()).toBe(30); + expect(ns(await clock.fire())).toBe(20); + expect(ns(await clock.fire())).toBe(30); expect(order).toEqual([1, 2, 20, 30]); }); test("fire picks an earlier timer that a pending microtask chain arms", async () => { const clock = manual(); - void sleepUntil(Instant(100)); - void Promise.resolve().then(() => sleepUntil(Instant(10))); - expect(await clock.fire()).toBe(10); + void sleepUntil(instant(100)); + void Promise.resolve().then(() => sleepUntil(instant(10))); + expect(ns(await clock.fire())).toBe(10); }); test("fire waits, without a timer, until a later host task arms one", async () => { const clock = manual(); const abort = new AbortController(); - void sleep(Nano(5), { signal: abort.signal }).catch(() => {}); + void sleep(Duration.nanos(5), { signal: abort.signal }).catch(() => {}); abort.abort(); let fired: number | undefined; const pending = clock.fire().then((at) => { - fired = at; + fired = ns(at); }); await hostTimeout(0); await hostTimeout(0); expect(fired).toBeUndefined(); await expect(clock.fire()).rejects.toThrow("already pending"); - void sleep(Nano(7)); + void sleep(Duration.nanos(7)); await pending; expect(fired).toBe(7); }); test("fire resolves when a later host task arms an already-due timer", async () => { const clock = manual(); - clock.jump(Nano(4)); + clock.jump(Duration.nanos(4)); let woke = false; const pending = clock.fire(); await hostTimeout(0); - void sleep(Nano(0)).then(() => { + void sleep(Duration.nanos(0)).then(() => { woke = true; }); - expect(await pending).toBe(4); + expect(ns(await pending)).toBe(4); expect(woke).toBe(true); }); test("fire stops at an already-due timer a pending microtask chain arms", async () => { const clock = manual(); - void sleepUntil(Instant(100)); - void Promise.resolve().then(() => sleep(Nano(0))); - expect(await clock.fire()).toBe(0); + void sleepUntil(instant(100)); + void Promise.resolve().then(() => sleep(Duration.nanos(0))); + expect(ns(await clock.fire())).toBe(0); }); test("advance steps through deadlines armed by earlier timers and stops at its target", async () => { @@ -319,14 +334,14 @@ test("advance steps through deadlines armed by earlier timers and stops at its t const at: number[] = []; void (async () => { for (let i = 0; i < 4; i++) { - await sleep(Nano(10)); - at.push(now()); + await sleep(Duration.nanos(10)); + at.push(ns(now())); } })(); - await clock.advance(Nano(30)); + await clock.advance(Duration.nanos(30)); expect(at).toEqual([10, 20, 30]); - expect(now()).toBe(30); - expect(await clock.fire()).toBe(40); + expect(ns(now())).toBe(30); + expect(ns(await clock.fire())).toBe(40); expect(at).toEqual([10, 20, 30, 40]); }); @@ -334,56 +349,56 @@ test("advance drains one timer's tasks before firing the next at the same deadli const clock = manual(); const abort = new AbortController(); const order: string[] = []; - void sleep(Nano(10)).then(() => { + void sleep(Duration.nanos(10)).then(() => { order.push("first"); abort.abort(); }); - void sleep(Nano(10), { signal: abort.signal }).then( + void sleep(Duration.nanos(10), { signal: abort.signal }).then( () => order.push("second"), () => order.push("cancelled"), ); - await clock.advance(Nano(10)); + await clock.advance(Duration.nanos(10)); expect(order).toEqual(["first", "cancelled"]); }); test("a timer armed while draining joins existing timers at the same deadline", async () => { const clock = manual(); const order: string[] = []; - void sleep(Nano(10)).then(() => { + void sleep(Duration.nanos(10)).then(() => { order.push("first"); - void sleepUntil(Instant(10)).then(() => order.push("new")); + void sleepUntil(instant(10)).then(() => order.push("new")); }); - void sleep(Nano(10)).then(() => order.push("second")); - await clock.advance(Nano(10)); + void sleep(Duration.nanos(10)).then(() => order.push("second")); + await clock.advance(Duration.nanos(10)); expect(order).toEqual(["first", "second", "new"]); }); test("a past deadline armed while draining observes the current instant", async () => { const clock = manual(); const at: number[] = []; - void sleep(Nano(10)).then(async () => { - at.push(now()); - await sleepUntil(Instant(3)); - at.push(now()); + void sleep(Duration.nanos(10)).then(async () => { + at.push(ns(now())); + await sleepUntil(instant(3)); + at.push(ns(now())); }); - await clock.advance(Nano(10)); + await clock.advance(Duration.nanos(10)); expect(at).toEqual([10, 10]); - expect(clock.now()).toBe(10); + expect(ns(clock.now())).toBe(10); }); test("drive fires each deadline its work waits on and stops when the work settles", async () => { const clock = manual(); let late = false; - void sleepUntil(Instant(100)).then(() => { + void sleepUntil(instant(100)).then(() => { late = true; }); const work = (async () => { - await sleep(Nano(10)); - await sleep(Nano(20)); + await sleep(Duration.nanos(10)); + await sleep(Duration.nanos(20)); return now(); })(); - expect(await clock.drive(work)).toBe(30); - expect(clock.now()).toBe(30); + expect(ns(await clock.drive(work))).toBe(30); + expect(ns(clock.now())).toBe(30); await hostTimeout(0); expect(late).toBe(false); }); @@ -392,12 +407,12 @@ test("drive settles with its work's rejection at the deadline that caused it", a const clock = manual(); await expect( clock.drive( - sleep(Nano(10)).then(() => { + sleep(Duration.nanos(10)).then(() => { throw new Error("boom"); }), ), ).rejects.toThrow("boom"); - expect(clock.now()).toBe(10); + expect(ns(clock.now())).toBe(10); }); for (const settles of ["before any timer", "on a later host task"] as const) { @@ -406,13 +421,13 @@ for (const settles of ["before any timer", "on a later host task"] as const) { const work = settles === "before any timer" ? Promise.resolve(1) : hostTimeout(0).then(() => 1); expect(await clock.drive(work)).toBe(1); const fired: number[] = []; - void sleep(ns(Milli(60_000))).then(() => fired.push(now())); - void sleep(ns(Milli(70_000))).then(() => fired.push(now())); + void sleep(Duration.millis(60_000)).then(() => fired.push(ns(now()))); + void sleep(Duration.millis(70_000)).then(() => fired.push(ns(now()))); await hostTimeout(0); expect(fired).toEqual([]); - expect(clock.now()).toBe(0); - expect(await clock.fire()).toBe(ns(Milli(60_000))); - expect(fired).toEqual([ns(Milli(60_000))]); + expect(ns(clock.now())).toBe(0); + expect(ns(await clock.fire())).toBe(60_000_000_000); + expect(fired).toEqual([60_000_000_000]); }); } @@ -424,62 +439,62 @@ for (const driver of ["advance", "fire", "drive"] as const) { release = resolve; }); const pending = - driver === "advance" ? clock.advance(Nano(10)) : driver === "fire" ? clock.fire() : clock.drive(work); + driver === "advance" ? clock.advance(Duration.nanos(10)) : driver === "fire" ? clock.fire() : clock.drive(work); try { - await expect(clock.advance(Nano(100))).rejects.toThrow("already pending"); - expect(() => clock.jump(Nano(100))).toThrow("already pending"); + await expect(clock.advance(Duration.nanos(100))).rejects.toThrow("already pending"); + expect(() => clock.jump(Duration.nanos(100))).toThrow("already pending"); await expect(clock.fire()).rejects.toThrow("already pending"); await expect(clock.drive(Promise.resolve())).rejects.toThrow("already pending"); - expect(clock.now()).toBe(0); + expect(ns(clock.now())).toBe(0); } finally { // Let fire and drive finish even if an assertion fails before they have a timer. - void sleepUntil(Instant(10)).then(release); + void sleepUntil(instant(10)).then(release); await pending; } - expect(clock.now()).toBe(10); - clock.jump(Nano(1)); - await clock.advance(Nano(1)); - void sleep(Nano(1)); - expect(await clock.fire()).toBe(13); + expect(ns(clock.now())).toBe(10); + clock.jump(Duration.nanos(1)); + await clock.advance(Duration.nanos(1)); + void sleep(Duration.nanos(1)); + expect(ns(await clock.fire())).toBe(13); }); } test("a timer callback cannot move time beyond the active advance target", async () => { const clock = manual(); const at: number[] = []; - const callback = sleep(Nano(5)).then(async () => { - await expect(clock.advance(Nano(100))).rejects.toThrow("already pending"); - expect(() => clock.jump(Nano(100))).toThrow("already pending"); + const callback = sleep(Duration.nanos(5)).then(async () => { + await expect(clock.advance(Duration.nanos(100))).rejects.toThrow("already pending"); + expect(() => clock.jump(Duration.nanos(100))).toThrow("already pending"); await expect(clock.fire()).rejects.toThrow("already pending"); - await sleepUntil(Instant(7)); - at.push(now()); + await sleepUntil(instant(7)); + at.push(ns(now())); }); - await clock.advance(Nano(10)); + await clock.advance(Duration.nanos(10)); await callback; expect(at).toEqual([7]); - expect(clock.now()).toBe(10); + expect(ns(clock.now())).toBe(10); }); test("fire returns the first deadline reached when a host task arms an earlier timer", async () => { const clock = manual(); const at: number[] = []; - void sleepUntil(Instant(10)).then(() => at.push(now())); + void sleepUntil(instant(10)).then(() => at.push(ns(now()))); const pending = clock.fire(); const channel = new MessageChannel(); try { channel.port1.onmessage = () => { channel.port1.close(); channel.port2.close(); - void sleepUntil(Instant(5)).then(() => at.push(now())); + void sleepUntil(instant(5)).then(() => at.push(ns(now()))); }; channel.port2.postMessage(null); - const fired = await pending; + const fired = ns(await pending); // A host may run the task before selection or during the drain after firing. // Either way fire must stop where it first observed a timer becoming ready. - expect(fired).toBe(at[0]); + expect(fired).toBe(at[0]); expect(at.every((value) => value === fired)).toBe(true); if (fired < 10) { - expect(await clock.fire()).toBe(10); + expect(ns(await clock.fire())).toBe(10); expect(at).toEqual([5, 10]); } } finally { diff --git a/js/clock/src/index.ts b/js/clock/src/index.ts index 54599b7718a..9506bfb4221 100644 --- a/js/clock/src/index.ts +++ b/js/clock/src/index.ts @@ -6,22 +6,19 @@ */ import { backend } from "./ambient.ts"; -import { Wall } from "./types.ts"; +import { type Wall, wallOf } from "./types.ts"; export type { Installed } from "./ambient.ts"; export { Manual } from "./manual.ts"; export { Elapsed, Interval, interval, MissedTickBehavior, now, sleep, sleepUntil, timeout, yieldNow } from "./timer.ts"; -export { Instant, Micro, Milli, Nano, Second, Wall } from "./types.ts"; +export { Duration, Instant, Wall } from "./types.ts"; -/** Read the installed clock's wall time in Unix milliseconds. */ +/** Read the installed clock's wall time. */ export function wall(): Wall { - return Wall(backend().wall()); + return wallOf(backend().wall()); } -/** - * Read the installed clock's wall time at instant zero, in Unix milliseconds. - * Rust's `kio::clock::origin()` pairs a nanosecond `Wall` with an instant instead. - */ +/** Read the installed clock's wall time at `Instant.ZERO`. */ export function origin(): Wall { - return Wall(backend().origin()); + return wallOf(backend().origin()); } diff --git a/js/clock/src/manual.ts b/js/clock/src/manual.ts index f742edf2b2e..b63c664aeb5 100644 --- a/js/clock/src/manual.ts +++ b/js/clock/src/manual.ts @@ -1,7 +1,7 @@ import { type Installed, install } from "./ambient.ts"; import type { Backend } from "./backend.ts"; import { drain, host } from "./host.ts"; -import { Instant, Nano, Wall } from "./types.ts"; +import { type Duration, type Instant, instantOf, type Wall, wallMillis, wallOf } from "./types.ts"; type Timer = { at: number; order: number; index: number; ready: () => void }; @@ -11,11 +11,12 @@ type Timer = { at: number; order: number; index: number; ready: () => void }; */ export class Manual { /** The reproducible starting wall time, 2025-01-01T00:00:00Z. */ - static readonly WALL_START = Wall(1_735_689_600_000); - #now = Instant.zero; + static readonly WALL_START: Wall = wallOf(1_735_689_600_000); + // Nanoseconds since the origin. + #now = 0; // Wall time is derived from an anchor so tiny advances don't vanish into an epoch-sized float. - #wallAnchor = Manual.WALL_START; - #wallAnchorAt = Instant.zero; + #wallAnchor = wallMillis(Manual.WALL_START); + #wallAnchorAt = 0; #timers: Timer[] = []; #order = 0; #revision = 0; @@ -26,8 +27,8 @@ export class Manual { #armed?: () => void; #backend: Backend = { now: () => this.#now, - wall: () => this.wall(), - origin: () => this.#wallAnchor - Nano.toMilli(Nano(this.#wallAnchorAt)), + wall: () => this.#wall(), + origin: () => this.#wallAnchor - this.#wallAnchorAt / 1_000_000, arm: (at, ready) => { const timer = { at, order: this.#order++, index: this.#timers.length, ready }; this.#timers.push(timer); @@ -57,20 +58,24 @@ export class Manual { /** Read this clock's instant without installing it. */ now(): Instant { - return this.#now; + return instantOf(this.#now); } /** Read this clock's wall time without installing it. */ wall(): Wall { - return Wall.add(this.#wallAnchor, Instant.durationSince(this.#now, this.#wallAnchorAt)); + return wallOf(this.#wall()); + } + + #wall(): number { + return this.#wallAnchor + (this.#now - this.#wallAnchorAt) / 1_000_000; } /** Jump forward without draining tasks, firing due timers late as a stalled event loop would. */ - jump(duration: Nano): void { + jump(duration: Duration): void { if (this.#driving) throw new Error("time driver already pending"); this.#driving = true; try { - this.#now = Instant.add(this.#now, duration); + this.#now += duration.asNanos(); this.#fire(); } finally { this.#driving = false; @@ -78,11 +83,11 @@ export class Manual { } /** Advance through each due deadline, draining tasks and pending yields before continuing to the target. */ - async advance(duration: Nano): Promise { + async advance(duration: Duration): Promise { if (this.#driving) throw new Error("time driver already pending"); this.#driving = true; try { - await this.#advance(Instant.add(this.#now, duration)); + await this.#advance(this.#now + duration.asNanos()); } finally { this.#driving = false; } @@ -97,7 +102,7 @@ export class Manual { this.#driving = true; try { await this.#advance(); - return this.#now; + return instantOf(this.#now); } finally { this.#driving = false; } @@ -131,12 +136,12 @@ export class Manual { /** Set wall time forward or backward without passing monotonic time. */ stepWall(wall: Wall): void { - this.#wallAnchor = Wall(wall); + this.#wallAnchor = wallMillis(wall); this.#wallAnchorAt = this.#now; } // Without a target, advances to the earliest deadline unless `stop` holds first. - async #advance(target?: Instant, stop?: () => boolean): Promise { + async #advance(target?: number, stop?: () => boolean): Promise { const fired = this.#fired; // Reached timers armed while draining join the heap once a target is chosen. this.#advancing = target !== undefined; @@ -158,12 +163,12 @@ export class Manual { this.#armed = undefined; continue; } - target = Instant(Math.max(this.#now, at)); + target = Math.max(this.#now, at); this.#advancing = true; } const first = this.#timers[0]; if (first !== undefined && first.at <= target) { - this.#now = Instant(Math.max(this.#now, first.at)); + this.#now = Math.max(this.#now, first.at); this.#ready(first); } else if (this.#now < target) { this.#now = target; diff --git a/js/clock/src/timer.ts b/js/clock/src/timer.ts index 96695107259..5e0d5347ae3 100644 --- a/js/clock/src/timer.ts +++ b/js/clock/src/timer.ts @@ -1,6 +1,6 @@ import { backend } from "./ambient.ts"; import type { Backend } from "./backend.ts"; -import { Instant, type Nano } from "./types.ts"; +import { type Duration, type Instant, instantNanos, instantOf } from "./types.ts"; function aborted(): DOMException { return new DOMException("timer closed", "AbortError"); @@ -9,7 +9,7 @@ function aborted(): DOMException { // `ref: false` lets a Node or Bun process exit while only this timer is pending; browsers ignore it. type Options = { signal?: AbortSignal; ref?: boolean }; -function wait(clock: Backend, at: Instant, options: Options = {}): { promise: Promise; cancel: () => void } { +function wait(clock: Backend, at: number, options: Options = {}): { promise: Promise; cancel: () => void } { const { signal, ref = true } = options; let cancel = () => {}; const promise = new Promise((resolve, reject) => { @@ -35,18 +35,18 @@ function wait(clock: Backend, at: Instant, options: Options = {}): { promise: Pr /** Read the installed clock's monotonic instant. */ export function now(): Instant { - return Instant(backend().now()); + return instantOf(backend().now()); } /** Complete when the installed clock reaches an instant, or reject on abort; `ref: false` won't hold the process open. */ export function sleepUntil(at: Instant, options?: { signal?: AbortSignal; ref?: boolean }): Promise { - return wait(backend(), Instant(at), options).promise; + return wait(backend(), instantNanos(at), options).promise; } /** Complete after a duration on the installed clock, or reject on abort; `ref: false` won't hold the process open. */ -export function sleep(duration: Nano, options?: { signal?: AbortSignal; ref?: boolean }): Promise { +export function sleep(duration: Duration, options?: { signal?: AbortSignal; ref?: boolean }): Promise { const clock = backend(); - return wait(clock, Instant.add(Instant(clock.now()), duration), options).promise; + return wait(clock, clock.now() + duration.asNanos(), options).promise; } /** Complete in a later host task, giving the host's other work a turn; a `Manual` clock won't advance past it. */ @@ -65,9 +65,9 @@ export class Elapsed extends Error { } /** Resolve an operation within a duration, preferring an already-ready operation. */ -export function timeout(duration: Nano, operation: PromiseLike): Promise { +export function timeout(duration: Duration, operation: PromiseLike): Promise { const clock = backend(); - const timer = wait(clock, Instant.add(Instant(clock.now()), duration)); + const timer = wait(clock, clock.now() + duration.asNanos()); return new Promise((resolve, reject) => { let done = false; const finish = (ok: boolean, value: unknown) => { @@ -104,16 +104,15 @@ export type MissedTickBehavior = (typeof MissedTickBehavior)[keyof typeof Missed /** An owned repeating timer, bound to the clock it was created on. */ export class Interval { #clock = backend(); - #next = Instant(this.#clock.now()); - #period: Nano; + #next = this.#clock.now(); + #period: Duration; #missed: MissedTickBehavior = MissedTickBehavior.Burst; #abort = new AbortController(); #pending = false; /** Start a positive-period interval whose first tick is ready at once. */ - constructor(period: Nano) { - Instant.add(Instant.zero, period); - if (period === 0) throw new RangeError("interval period must be positive"); + constructor(period: Duration) { + if (period.isZero()) throw new RangeError("interval period must be positive"); this.#period = period; } @@ -125,19 +124,20 @@ export class Interval { await wait(this.#clock, this.#next, { signal: this.#abort.signal }).promise; const scheduled = this.#next; const now = this.#clock.now(); - let next = Instant.add(scheduled, this.#period); + const period = this.#period.asNanos(); + let next = scheduled + period; if (next <= now) { switch (this.#missed) { case MissedTickBehavior.Delay: - next = Instant(now + this.#period); + next = now + period; break; case MissedTickBehavior.Skip: - next = Instant(now + this.#period - ((now - scheduled) % this.#period)); + next = now + period - ((now - scheduled) % period); break; } } this.#next = next; - return scheduled; + return instantOf(scheduled); } finally { this.#pending = false; } @@ -150,7 +150,7 @@ export class Interval { } /** Return the time between ticks. */ - period(): Nano { + period(): Duration { return this.#period; } @@ -161,6 +161,6 @@ export class Interval { } /** Tick every positive period on the installed clock, starting at once. */ -export function interval(period: Nano): Interval { +export function interval(period: Duration): Interval { return new Interval(period); } diff --git a/js/clock/src/types.ts b/js/clock/src/types.ts index e78e40d48ec..e7965612534 100644 --- a/js/clock/src/types.ts +++ b/js/clock/src/types.ts @@ -1,82 +1,352 @@ -function checked(value: number): number { - if (!Number.isFinite(value) || value < 0) throw new RangeError(`invalid time: ${value}`); +function checked(value: number, what: string): number { + if (!Number.isFinite(value) || value < 0) throw new RangeError(`invalid ${what}: ${value}`); return value; } -/** A nonnegative duration in nanoseconds. */ -export type Nano = number & { readonly _brand: "clock-nano" }; - -/** Brand nanoseconds or convert another duration unit. */ -export const Nano = Object.assign((value: number): Nano => checked(value) as Nano, { - zero: 0 as Nano, - fromMicro: (value: Micro): Nano => Nano(value * 1_000), - toMicro: (value: Nano): Micro => Micro(value / 1_000), - fromMilli: (value: Milli): Nano => Nano(value * 1_000_000), - toMilli: (value: Nano): Milli => Milli(value / 1_000_000), - fromSecond: (value: Second): Nano => Nano(value * 1_000_000_000), - toSecond: (value: Nano): Second => Second(value / 1_000_000_000), -}); - -/** A nonnegative duration in microseconds. */ -export type Micro = number & { readonly _brand: "clock-micro" }; - -/** Brand microseconds or convert another duration unit. */ -export const Micro = Object.assign((value: number): Micro => checked(value) as Micro, { - zero: 0 as Micro, - fromNano: (value: Nano): Micro => Micro(value / 1_000), - toNano: (value: Micro): Nano => Nano(value * 1_000), - fromMilli: (value: Milli): Micro => Micro(value * 1_000), - toMilli: (value: Micro): Milli => Milli(value / 1_000), - fromSecond: (value: Second): Micro => Micro(value * 1_000_000), - toSecond: (value: Micro): Second => Second(value / 1_000_000), -}); - -/** A nonnegative duration in milliseconds. */ -export type Milli = number & { readonly _brand: "clock-milli" }; - -/** Brand milliseconds or convert another duration unit. */ -export const Milli = Object.assign((value: number): Milli => checked(value) as Milli, { - zero: 0 as Milli, - fromNano: (value: Nano): Milli => Milli(value / 1_000_000), - toNano: (value: Milli): Nano => Nano(value * 1_000_000), - fromMicro: (value: Micro): Milli => Milli(value / 1_000), - toMicro: (value: Milli): Micro => Micro(value * 1_000), - fromSecond: (value: Second): Milli => Milli(value * 1_000), - toSecond: (value: Milli): Second => Second(value / 1_000), -}); - -/** A nonnegative duration in seconds. */ -export type Second = number & { readonly _brand: "clock-second" }; - -/** Brand seconds or convert another duration unit. */ -export const Second = Object.assign((value: number): Second => checked(value) as Second, { - zero: 0 as Second, - fromNano: (value: Nano): Second => Second(value / 1_000_000_000), - toNano: (value: Second): Nano => Nano(value * 1_000_000_000), - fromMicro: (value: Micro): Second => Second(value / 1_000_000), - toMicro: (value: Second): Micro => Micro(value * 1_000_000), - fromMilli: (value: Milli): Second => Second(value / 1_000), - toMilli: (value: Second): Milli => Milli(value * 1_000), -}); - -/** Nanoseconds since this clock's origin, separate from durations and wall time. */ -export type Instant = number & { readonly _brand: "clock-instant" }; - -/** Brand a logical instant or do arithmetic on its own clock's coordinates. */ -export const Instant = Object.assign((value: number): Instant => checked(value) as Instant, { - zero: 0 as Instant, - add: (at: Instant, duration: Nano): Instant => Instant(at + Nano(duration)), - sub: (at: Instant, duration: Nano): Instant => Instant(at - Nano(duration)), - durationSince: (at: Instant, earlier: Instant): Nano => Nano(Math.max(0, at - earlier)), -}); - -/** Milliseconds since the Unix epoch, separate from monotonic time. */ -export type Wall = number & { readonly _brand: "clock-wall" }; - -/** Brand Unix milliseconds or move wall time by a duration. */ -export const Wall = Object.assign((unixMillis: number): Wall => checked(unixMillis) as Wall, { - UNIX_EPOCH: 0 as Wall, - add: (at: Wall, duration: Nano): Wall => Wall(at + Nano.toMilli(duration)), - sub: (at: Wall, duration: Nano): Wall => Wall(at - Nano.toMilli(duration)), - durationSince: (at: Wall, earlier: Wall): Nano => Nano.fromMilli(Milli(Math.max(0, at - earlier))), -}); +function refuse(what: string): never { + throw new TypeError(`a ${what} is not a number; read it with an explicit unit`); +} + +// Package-private bridges for backends that count in plain numbers. +/** @internal */ +export let instantOf: (nanos: number) => Instant; +/** @internal */ +export let instantNanos: (at: Instant) => number; +/** @internal */ +export let wallOf: (unixMillis: number) => Wall; +/** @internal */ +export let wallMillis: (at: Wall) => number; + +/** + * A nonnegative span of time, mirroring Rust's `std::time::Duration`. + * + * Build one with a unit (`Duration.millis(5)`) and read it with one (`asMillis()`). It never + * converts to a number implicitly: arithmetic, `<`, and `JSON.stringify` throw. + */ +export class Duration { + /** No time at all. */ + static readonly ZERO: Duration = new Duration(0); + + readonly #nanos: number; + + private constructor(nanos: number) { + this.#nanos = nanos; + } + + /** A duration of `value` nanoseconds; throws a `RangeError` unless finite and nonnegative. */ + static nanos(value: number): Duration { + return new Duration(checked(value, "duration")); + } + + /** A duration of `value` microseconds; throws a `RangeError` unless finite and nonnegative. */ + static micros(value: number): Duration { + return new Duration(checked(value * 1_000, "duration")); + } + + /** A duration of `value` milliseconds; throws a `RangeError` unless finite and nonnegative. */ + static millis(value: number): Duration { + return new Duration(checked(value * 1_000_000, "duration")); + } + + /** A duration of `value` seconds; throws a `RangeError` unless finite and nonnegative. */ + static secs(value: number): Duration { + return new Duration(checked(value * 1_000_000_000, "duration")); + } + + /** The duration in nanoseconds, possibly fractional. */ + asNanos(): number { + return this.#nanos; + } + + /** The duration in microseconds, possibly fractional. */ + asMicros(): number { + return this.#nanos / 1_000; + } + + /** The duration in milliseconds, possibly fractional. */ + asMillis(): number { + return this.#nanos / 1_000_000; + } + + /** The duration in seconds, possibly fractional. */ + asSecs(): number { + return this.#nanos / 1_000_000_000; + } + + /** Whether this is no time at all. */ + isZero(): boolean { + return this.#nanos === 0; + } + + /** The sum of both durations. */ + add(other: Duration): Duration { + return new Duration(checked(this.#nanos + other.#nanos, "duration")); + } + + /** This duration minus `other`; throws a `RangeError` if `other` is longer. */ + sub(other: Duration): Duration { + return new Duration(checked(this.#nanos - other.#nanos, "duration")); + } + + /** This duration minus `other`, or zero if `other` is longer. */ + saturatingSub(other: Duration): Duration { + return this.#nanos > other.#nanos ? new Duration(this.#nanos - other.#nanos) : Duration.ZERO; + } + + /** This duration scaled by a finite, nonnegative factor. */ + mul(factor: number): Duration { + return new Duration(checked(this.#nanos * factor, "duration")); + } + + /** This duration divided by a finite, positive divisor. */ + div(divisor: number): Duration { + if (!(divisor > 0)) throw new RangeError(`invalid divisor: ${divisor}`); + return new Duration(checked(this.#nanos / divisor, "duration")); + } + + /** How many times `other` fits in this duration, possibly fractional; throws a `RangeError` if `other` is zero. */ + divDuration(other: Duration): number { + if (other.#nanos === 0) throw new RangeError("division by a zero duration"); + return this.#nanos / other.#nanos; + } + + /** The distance between both durations, whichever is longer. */ + absDiff(other: Duration): Duration { + return new Duration(Math.abs(this.#nanos - other.#nanos)); + } + + /** Whether both durations are the same length. */ + eq(other: Duration): boolean { + return this.#nanos === other.#nanos; + } + + /** Whether this duration is shorter than `other`. */ + lt(other: Duration): boolean { + return this.#nanos < other.#nanos; + } + + /** Whether this duration is at most `other`. */ + le(other: Duration): boolean { + return this.#nanos <= other.#nanos; + } + + /** Whether this duration is longer than `other`. */ + gt(other: Duration): boolean { + return this.#nanos > other.#nanos; + } + + /** Whether this duration is at least `other`. */ + ge(other: Duration): boolean { + return this.#nanos >= other.#nanos; + } + + /** The shorter of both durations. */ + min(other: Duration): Duration { + return other.#nanos < this.#nanos ? other : this; + } + + /** The longer of both durations. */ + max(other: Duration): Duration { + return other.#nanos > this.#nanos ? other : this; + } + + /** This duration limited to `[lo, hi]`. */ + clamp(lo: Duration, hi: Duration): Duration { + return this.max(lo).min(hi); + } + + /** The duration in milliseconds with a unit, such as `1.5ms`. */ + toString(): string { + return `${this.asMillis()}ms`; + } + + /** Refuses: a duration has no unitless number. */ + valueOf(): never { + return refuse("Duration"); + } + + /** Refuses: serialize a number with an explicit unit instead. */ + toJSON(): never { + return refuse("Duration"); + } + + [Symbol.toPrimitive](hint: string): string { + if (hint === "string") return this.toString(); + return refuse("Duration"); + } +} + +/** + * A point on the installed clock's monotonic timeline, mirroring `kio::clock::Instant`. + * + * Instants are only comparable within one clock. The host clock's origin is the realm's + * performance time origin, so a DOM timestamp `t` is `Instant.ZERO.add(Duration.millis(t))`. + */ +export class Instant { + /** The clock's origin. */ + static readonly ZERO: Instant = new Instant(0); + + readonly #nanos: number; + + private constructor(nanos: number) { + this.#nanos = nanos; + } + + static { + instantOf = (nanos) => new Instant(checked(nanos, "instant")); + instantNanos = (at) => at.#nanos; + } + + /** This instant moved forward by `duration`. */ + add(duration: Duration): Instant { + return new Instant(checked(this.#nanos + duration.asNanos(), "instant")); + } + + /** This instant moved back by `duration`; throws a `RangeError` before the clock's origin. */ + sub(duration: Duration): Instant { + return new Instant(checked(this.#nanos - duration.asNanos(), "instant")); + } + + /** The time from `earlier` to this instant, zero if `earlier` is later. */ + since(earlier: Instant): Duration { + return this.#nanos > earlier.#nanos ? Duration.nanos(this.#nanos - earlier.#nanos) : Duration.ZERO; + } + + /** Whether both are the same instant. */ + eq(other: Instant): boolean { + return this.#nanos === other.#nanos; + } + + /** Whether this instant is before `other`. */ + lt(other: Instant): boolean { + return this.#nanos < other.#nanos; + } + + /** Whether this instant is at or before `other`. */ + le(other: Instant): boolean { + return this.#nanos <= other.#nanos; + } + + /** Whether this instant is after `other`. */ + gt(other: Instant): boolean { + return this.#nanos > other.#nanos; + } + + /** Whether this instant is at or after `other`. */ + ge(other: Instant): boolean { + return this.#nanos >= other.#nanos; + } + + /** The earlier of both instants. */ + min(other: Instant): Instant { + return other.#nanos < this.#nanos ? other : this; + } + + /** The later of both instants. */ + max(other: Instant): Instant { + return other.#nanos > this.#nanos ? other : this; + } + + /** The time since the origin with a unit, such as `Instant(1.5ms)`. */ + toString(): string { + return `Instant(${this.#nanos / 1_000_000}ms)`; + } + + /** Refuses: an instant has no unitless number. */ + valueOf(): never { + return refuse("Instant"); + } + + /** Refuses: an instant is meaningless outside its clock. */ + toJSON(): never { + return refuse("Instant"); + } + + [Symbol.toPrimitive](hint: string): string { + if (hint === "string") return this.toString(); + return refuse("Instant"); + } +} + +/** + * A point in wall-clock time, separate from monotonic time, mirroring `kio::clock::Wall`. + * + * Convert Unix milliseconds with `Wall.UNIX_EPOCH.add(Duration.millis(ms))` and back with + * `wall.since(Wall.UNIX_EPOCH).asMillis()`. + */ +export class Wall { + /** 1970-01-01T00:00:00Z. */ + static readonly UNIX_EPOCH: Wall = new Wall(0); + + // Milliseconds, since Unix nanoseconds pass 2^53. + readonly #millis: number; + + private constructor(millis: number) { + this.#millis = millis; + } + + static { + wallOf = (millis) => new Wall(checked(millis, "wall time")); + wallMillis = (at) => at.#millis; + } + + /** This time moved forward by `duration`. */ + add(duration: Duration): Wall { + return new Wall(checked(this.#millis + duration.asMillis(), "wall time")); + } + + /** This time moved back by `duration`; throws a `RangeError` before the Unix epoch. */ + sub(duration: Duration): Wall { + return new Wall(checked(this.#millis - duration.asMillis(), "wall time")); + } + + /** The time from `earlier` to this one, zero if `earlier` is later. */ + since(earlier: Wall): Duration { + return this.#millis > earlier.#millis ? Duration.millis(this.#millis - earlier.#millis) : Duration.ZERO; + } + + /** Whether both are the same time. */ + eq(other: Wall): boolean { + return this.#millis === other.#millis; + } + + /** Whether this time is before `other`. */ + lt(other: Wall): boolean { + return this.#millis < other.#millis; + } + + /** Whether this time is at or before `other`. */ + le(other: Wall): boolean { + return this.#millis <= other.#millis; + } + + /** Whether this time is after `other`. */ + gt(other: Wall): boolean { + return this.#millis > other.#millis; + } + + /** Whether this time is at or after `other`. */ + ge(other: Wall): boolean { + return this.#millis >= other.#millis; + } + + /** The time as an ISO 8601 string, or Unix milliseconds past `Date`'s range. */ + toString(): string { + return this.#millis <= 8.64e15 ? new Date(this.#millis).toISOString() : `Wall(${this.#millis}ms)`; + } + + /** Refuses: a wall time has no unitless number. */ + valueOf(): never { + return refuse("Wall"); + } + + /** Refuses: serialize `since(Wall.UNIX_EPOCH)` with an explicit unit instead. */ + toJSON(): never { + return refuse("Wall"); + } + + [Symbol.toPrimitive](hint: string): string { + if (hint === "string") return this.toString(); + return refuse("Wall"); + } +} diff --git a/js/signals/README.md b/js/signals/README.md index 48fcc380b72..403ad58bc23 100644 --- a/js/signals/README.md +++ b/js/signals/README.md @@ -153,9 +153,9 @@ const effect = new Effect((effect) => { Effects also provide lifecycle helpers that auto-cleanup: - **`effect.set(signal, value, cleanup)`** - temporarily set the value of a signal for the duration of the effect -- **`effect.timer(fn, duration)`** - run once after a `Nano` duration on the `@moq/clock` clock, cancelled on cleanup -- **`effect.timeout(fn, duration)`** - run a nested effect until a `Nano` duration elapses -- **`effect.interval(fn, period)`** - run every `Nano` period on the `@moq/clock` clock, cancelled on cleanup +- **`effect.timer(fn, duration)`** - run once after a `Duration` on the `@moq/clock` clock, cancelled on cleanup +- **`effect.timeout(fn, duration)`** - run a nested effect until a `Duration` elapses +- **`effect.interval(fn, period)`** - run every `Duration` period on the `@moq/clock` clock, cancelled on cleanup - **`effect.animate(fn)`** - `requestAnimationFrame` that cancels on cleanup - **`effect.event(target, type, fn)`** - `addEventListener` that removes on cleanup/rerun via `AbortSignal` - **`effect.subscribe(signal, fn)`** - shorthand: run `fn` each time `signal` changes diff --git a/js/signals/src/index.test.ts b/js/signals/src/index.test.ts index 0453e62e8a4..f32ea493b5a 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 { type Installed, Manual, Milli, Nano, now, Second, yieldNow } from "@moq/clock"; +import { Duration, type Installed, Instant, Manual, now, yieldNow } 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."; @@ -84,6 +84,21 @@ describe("Signal", () => { dispose(); }); + test("clock values compare by value, nested or not", async () => { + const signal = new Signal({ delay: Duration.millis(5) }); + let notified = 0; + const dispose = signal.subscribe(() => notified++); + + signal.set({ delay: Duration.micros(5000) }); + await settle(); + expect(notified).toBe(0); + + signal.set({ delay: Duration.millis(6) }); + await settle(); + expect(notified).toBe(1); + dispose(); + }); + test("deep equality sees structure that reads as undefined", async () => { const signal = new Signal(new Array(1)); let notified = 0; @@ -623,7 +638,7 @@ describe("Effect", () => { expect(runs).toBe(1); // parked awaiting the task // Five seconds pass. The warning fires, but the next run must stay shut. - await clock.advance(Nano.fromSecond(Second(5))); + await clock.advance(Duration.secs(5)); expect(runs).toBe(1); expect(warn).toHaveBeenCalled(); @@ -672,7 +687,7 @@ describe("Effect", () => { await settle(); // The wait let go, so five seconds later a closed effect is not warned about. - await clock.advance(Nano.fromSecond(Second(5))); + await clock.advance(Duration.secs(5)); const warned = warn.mock.calls.some((call) => String(call[0]).includes("spawn is still running")); expect(warned).toBe(false); } finally { @@ -892,7 +907,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 ms = (value: number) => Duration.millis(value); const clock = new Manual(); const installed = clock.install(); const fired: string[] = []; @@ -1484,11 +1499,11 @@ test("an effect interval arms its first period synchronously and steps subsequen const effect = new Effect(); const at: number[] = []; try { - effect.interval(() => at.push(clock.now()), Nano(10)); - clock.jump(Nano(10)); - await clock.advance(Nano.zero); + effect.interval(() => at.push(clock.now().since(Instant.ZERO).asNanos()), Duration.nanos(10)); + clock.jump(Duration.nanos(10)); + await clock.advance(Duration.ZERO); expect(at).toEqual([10]); - await clock.advance(Nano(30)); + await clock.advance(Duration.nanos(30)); expect(at).toEqual([10, 20, 30, 40]); } finally { effect.close(); @@ -1499,7 +1514,7 @@ test("an effect interval arms its first period synchronously and steps subsequen test("an effect interval refuses a zero period synchronously", () => { const effect = new Effect(); try { - expect(() => effect.interval(() => {}, Nano.zero)).toThrow(RangeError); + expect(() => effect.interval(() => {}, Duration.ZERO)).toThrow(RangeError); } finally { effect.close(); } @@ -1511,13 +1526,13 @@ test("an effect interval delays a full period after a stalled event loop", async const effect = new Effect(); const at: number[] = []; try { - effect.interval(() => at.push(clock.now()), Nano(10)); - clock.jump(Nano(35)); - await clock.advance(Nano.zero); + effect.interval(() => at.push(clock.now().since(Instant.ZERO).asNanos()), Duration.nanos(10)); + clock.jump(Duration.nanos(35)); + await clock.advance(Duration.ZERO); expect(at).toEqual([35]); - await clock.advance(Nano(9)); + await clock.advance(Duration.nanos(9)); expect(at).toEqual([35]); - await clock.advance(Nano(1)); + await clock.advance(Duration.nanos(1)); expect(at).toEqual([35, 45]); } finally { effect.close(); @@ -1527,7 +1542,7 @@ test("an effect interval delays a full period after a stalled event loop", async test("an effect interval starts its next period on a newly installed clock's origin", async () => { const first = new Manual(); - first.jump(Nano(1000)); + first.jump(Duration.nanos(1000)); const installedFirst = first.install(); const second = new Manual(); let installedSecond: Installed | undefined; @@ -1535,12 +1550,12 @@ test("an effect interval starts its next period on a newly installed clock's ori const at: number[] = []; try { effect.interval(() => { - at.push(now()); + at.push(now().since(Instant.ZERO).asNanos()); if (at.length === 1) installedSecond = second.install(); - }, Nano(10)); - await first.advance(Nano(10)); + }, Duration.nanos(10)); + await first.advance(Duration.nanos(10)); expect(at).toEqual([1010]); - await second.advance(Nano(10)); + await second.advance(Duration.nanos(10)); expect(at).toEqual([1010, 10]); } finally { effect.close(); diff --git a/js/signals/src/index.ts b/js/signals/src/index.ts index 1eb72ecacf6..f530a6508fb 100644 --- a/js/signals/src/index.ts +++ b/js/signals/src/index.ts @@ -4,7 +4,7 @@ * * @module */ -import { Instant, Nano, now, Second, sleep, sleepUntil } from "@moq/clock"; +import { Duration, Instant, now, sleep, sleepUntil, Wall } from "@moq/clock"; /** Cancels a subscription, effect, or other registration when called. */ export type Dispose = () => void; @@ -689,7 +689,7 @@ export class Effect { if (this.#async.size > 0) { // Diagnostic only: a task that ignores cancellation stalls the rerun, so name it. const warn = new AbortController(); - sleep(Nano.fromSecond(Second(5)), { signal: warn.signal, ref: false }).then(() => { + sleep(Duration.secs(5), { signal: warn.signal, ref: false }).then(() => { // A close() racing the timer disarms it, but the wakeup can already be // queued by then. There is nothing to warn about once the effect is gone. if (this.#dispose === undefined) return; @@ -808,7 +808,7 @@ export class Effect { } /** Runs `fn` after `duration` on the installed clock, unless the effect reruns or closes first. */ - timer(fn: () => void, duration: Nano) { + timer(fn: () => void, duration: Duration) { if (this.#dispose === undefined) { console.warn("Effect.timer called when closed, ignoring"); return; @@ -828,7 +828,7 @@ export class Effect { * Shares {@link run}'s handling of a task that outlived its run: the child is closed at the * next teardown, not immediately. */ - timeout(fn: (effect: Effect) => void, duration: Nano) { + timeout(fn: (effect: Effect) => void, duration: Duration) { if (this.#dispose === undefined) { console.warn("Effect.timeout called when closed, ignoring"); return; @@ -864,16 +864,15 @@ export class Effect { * Runs `fn` every positive period until cleanup, arming the first deadline before returning. * Each period uses the clock installed then; a late callback delays the next by a full period. */ - interval(fn: () => void, period: Nano) { + interval(fn: () => void, period: Duration) { if (this.#dispose === undefined) { console.warn("Effect.interval called when closed, ignoring"); return; } - Instant.add(Instant.zero, period); - if (period === 0) throw new RangeError("interval period must be positive"); + if (period.isZero()) throw new RangeError("interval period must be positive"); const abort = new AbortController(); - let next = Instant.add(now(), period); + let next = now().add(period); void (async () => { for (;;) { await sleepUntil(next, { signal: abort.signal }); @@ -885,7 +884,7 @@ export class Effect { } // A callback may install a clock with a different origin. A full Delay period // starts from that clock's now, never from the previous clock's deadline. - next = Instant.add(now(), period); + next = now().add(period); } })().catch(noop); this.cleanup(() => abort.abort()); @@ -1300,7 +1299,8 @@ export class Derived[], T> implements G } // Deep equality for plain objects/arrays, SameValueZero for everything else. -// Class instances have identity semantics (e.g. two different Broadcast instances are never equal). +// Class instances have identity semantics (e.g. two different Broadcast instances are never equal), +// except the clock's immutable values, which compare by value like the numbers they replace. function isEqual(a: unknown, b: unknown): boolean { if (a === b || (Number.isNaN(a) && Number.isNaN(b))) return true; if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false; @@ -1310,6 +1310,7 @@ function isEqual(a: unknown, b: unknown): boolean { // Both must be plain objects or both arrays to deep-compare. if (protoA !== protoB) return false; + if (a instanceof Duration || a instanceof Instant || a instanceof Wall) return a.eq(b as never); if (protoA !== Object.prototype && protoA !== Array.prototype) return false; // Holes are not keys, so a sparse array's length is only visible here. From 22f1488ff5ae486fd92a5c27b97253ff3e8a9c81 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 09:44:57 -0800 Subject: [PATCH 03/17] feat(net,qmux)!: durations and instants are Clock types Co-Authored-By: Claude Opus 5.5 --- js/clock/src/index.test.ts | 6 +- js/clock/src/types.ts | 123 +++-- js/net/bench/broadcasts.ts | 3 +- js/net/bench/drift.ts | 6 +- js/net/bench/fetch.ts | 4 +- js/net/bench/fills.ts | 4 +- js/net/bench/ledger.ts | 8 +- js/net/bench/refresh.ts | 4 +- js/net/bench/replay.ts | 4 +- js/net/bench/resume-history.ts | 6 +- js/net/bench/resume.ts | 4 +- js/net/bench/serve-browser-entry.ts | 6 +- js/net/bench/subscribe-drop.ts | 3 +- js/net/bench/track.ts | 8 +- js/net/src/auth.test.ts | 48 +- js/net/src/auth.ts | 5 +- js/net/src/auth_session.ts | 32 +- js/net/src/broadcast.test.ts | 34 +- js/net/src/cache.test.ts | 10 +- js/net/src/cache.ts | 18 +- js/net/src/connection/accept.ts | 7 +- js/net/src/connection/bandwidth.test.ts | 12 +- js/net/src/connection/close.test.ts | 4 +- js/net/src/connection/connect.test.ts | 119 +++-- js/net/src/connection/connect.ts | 43 +- js/net/src/connection/forward.test.ts | 6 +- js/net/src/connection/forward.ts | 6 +- js/net/src/connection/goaway.test.ts | 10 +- js/net/src/connection/goaway.ts | 12 +- js/net/src/connection/handshake.ts | 4 +- js/net/src/connection/migrate.test.ts | 74 ++-- js/net/src/connection/pool.test.ts | 26 +- js/net/src/connection/pool.ts | 10 +- js/net/src/connection/reload.test.ts | 122 ++--- js/net/src/connection/reload.ts | 84 ++-- js/net/src/connection/scope.test.ts | 4 +- js/net/src/connection/stats.test.ts | 8 +- js/net/src/connection/stats.ts | 8 +- js/net/src/connection/ticker.test.ts | 10 +- js/net/src/connection/ticker.ts | 21 +- js/net/src/error.ts | 8 +- js/net/src/fill.test.ts | 31 +- js/net/src/fill.ts | 6 +- js/net/src/goaway-requests.test.ts | 8 +- js/net/src/group.test.ts | 30 +- js/net/src/ietf/aliases.test.ts | 4 +- js/net/src/ietf/aliases.ts | 4 +- js/net/src/ietf/connection.ts | 10 +- js/net/src/ietf/datagram.test.ts | 4 +- js/net/src/ietf/fetch.test.ts | 16 +- js/net/src/ietf/fetch.ts | 5 +- js/net/src/ietf/filter.test.ts | 7 +- js/net/src/ietf/filter.ts | 7 +- js/net/src/ietf/goaway.test.ts | 8 +- js/net/src/ietf/goaway.ts | 4 +- js/net/src/ietf/ietf.test.ts | 4 +- js/net/src/ietf/join.test.ts | 12 +- js/net/src/ietf/malformed.test.ts | 4 +- js/net/src/ietf/parameters.ts | 7 +- js/net/src/ietf/publisher.test.ts | 86 ++-- js/net/src/ietf/publisher.ts | 36 +- js/net/src/ietf/request_stream.test.ts | 14 +- js/net/src/ietf/request_stream.ts | 2 +- js/net/src/ietf/subscriber.test.ts | 21 +- js/net/src/ietf/subscriber.ts | 6 +- js/net/src/ietf/tail.test.ts | 10 +- js/net/src/index.ts | 4 +- js/net/src/integers.test.ts | 6 +- js/net/src/integration.test.ts | 120 +++-- js/net/src/internal.ts | 24 +- js/net/src/ledger.test.ts | 34 +- js/net/src/ledger.ts | 15 +- js/net/src/lite/compression.test.ts | 6 +- js/net/src/lite/connection.test.ts | 8 +- js/net/src/lite/connection.ts | 4 +- js/net/src/lite/copy_fill.test.ts | 12 +- js/net/src/lite/fetch.test.ts | 11 +- js/net/src/lite/fetch.ts | 11 +- js/net/src/lite/publisher.test.ts | 110 +++-- js/net/src/lite/publisher.ts | 18 +- js/net/src/lite/refresh.test.ts | 10 +- js/net/src/lite/subscriber.test.ts | 50 +-- js/net/src/lite/subscriber.ts | 34 +- js/net/src/lite/tail.test.ts | 39 +- js/net/src/lite/track.test.ts | 10 +- js/net/src/lite/track_stream.test.ts | 34 +- js/net/src/lite/tracks.test.ts | 6 +- js/net/src/lite/widened_max_age.test.ts | 18 +- js/net/src/mock.test.ts | 10 +- js/net/src/mock.ts | 6 +- js/net/src/net-cleanups.test.ts | 25 +- js/net/src/open.test.ts | 14 +- js/net/src/open.ts | 11 +- js/net/src/order.test.ts | 4 +- js/net/src/parked-expiry.test.ts | 14 +- js/net/src/request-deadline.test.ts | 22 +- js/net/src/resume.model.test.ts | 16 +- js/net/src/resume.test.ts | 136 +++--- js/net/src/resume.ts | 31 +- js/net/src/socket.test.ts | 44 +- js/net/src/tail.test.ts | 22 +- js/net/src/tail.ts | 8 +- js/net/src/time.ts | 8 +- js/net/src/track.test.ts | 567 +++++++++++++----------- js/net/src/track.ts | 78 ++-- js/net/src/util/deadline.ts | 10 +- js/net/src/util/timeout.test.ts | 12 +- js/net/src/util/timeout.ts | 4 +- js/net/src/util/timer.ts | 4 +- js/qmux/src/session.test.ts | 50 ++- js/qmux/src/session.ts | 63 ++- js/qmux/src/web-socket-stream.test.ts | 4 +- js/qmux/src/web-socket-stream.ts | 4 +- 113 files changed, 1561 insertions(+), 1470 deletions(-) diff --git a/js/clock/src/index.test.ts b/js/clock/src/index.test.ts index 8646c821715..63fafad956f 100644 --- a/js/clock/src/index.test.ts +++ b/js/clock/src/index.test.ts @@ -439,7 +439,11 @@ for (const driver of ["advance", "fire", "drive"] as const) { release = resolve; }); const pending = - driver === "advance" ? clock.advance(Duration.nanos(10)) : driver === "fire" ? clock.fire() : clock.drive(work); + driver === "advance" + ? clock.advance(Duration.nanos(10)) + : driver === "fire" + ? clock.fire() + : clock.drive(work); try { await expect(clock.advance(Duration.nanos(100))).rejects.toThrow("already pending"); expect(() => clock.jump(Duration.nanos(100))).toThrow("already pending"); diff --git a/js/clock/src/types.ts b/js/clock/src/types.ts index e7965612534..3666df5fa08 100644 --- a/js/clock/src/types.ts +++ b/js/clock/src/types.ts @@ -7,6 +7,11 @@ function refuse(what: string): never { throw new TypeError(`a ${what} is not a number; read it with an explicit unit`); } +// Values live under a symbol rather than a `#private` field so test matchers such as `toEqual` +// compare them by value; a private field is invisible to them, so every pair would match. +/** @internal */ +export const VALUE: unique symbol = Symbol("clock value"); + // Package-private bridges for backends that count in plain numbers. /** @internal */ export let instantOf: (nanos: number) => Instant; @@ -27,10 +32,12 @@ export class Duration { /** No time at all. */ static readonly ZERO: Duration = new Duration(0); - readonly #nanos: number; + /** @internal Nanoseconds. */ + readonly [VALUE]: number; + declare private readonly kind: "duration"; private constructor(nanos: number) { - this.#nanos = nanos; + this[VALUE] = nanos; } /** A duration of `value` nanoseconds; throws a `RangeError` unless finite and nonnegative. */ @@ -55,99 +62,104 @@ export class Duration { /** The duration in nanoseconds, possibly fractional. */ asNanos(): number { - return this.#nanos; + return this[VALUE]; } /** The duration in microseconds, possibly fractional. */ asMicros(): number { - return this.#nanos / 1_000; + return this[VALUE] / 1_000; } /** The duration in milliseconds, possibly fractional. */ asMillis(): number { - return this.#nanos / 1_000_000; + return this[VALUE] / 1_000_000; } /** The duration in seconds, possibly fractional. */ asSecs(): number { - return this.#nanos / 1_000_000_000; + return this[VALUE] / 1_000_000_000; } /** Whether this is no time at all. */ isZero(): boolean { - return this.#nanos === 0; + return this[VALUE] === 0; } /** The sum of both durations. */ add(other: Duration): Duration { - return new Duration(checked(this.#nanos + other.#nanos, "duration")); + return new Duration(checked(this[VALUE] + other[VALUE], "duration")); } /** This duration minus `other`; throws a `RangeError` if `other` is longer. */ sub(other: Duration): Duration { - return new Duration(checked(this.#nanos - other.#nanos, "duration")); + return new Duration(checked(this[VALUE] - other[VALUE], "duration")); } /** This duration minus `other`, or zero if `other` is longer. */ saturatingSub(other: Duration): Duration { - return this.#nanos > other.#nanos ? new Duration(this.#nanos - other.#nanos) : Duration.ZERO; + return this[VALUE] > other[VALUE] ? new Duration(this[VALUE] - other[VALUE]) : Duration.ZERO; } /** This duration scaled by a finite, nonnegative factor. */ mul(factor: number): Duration { - return new Duration(checked(this.#nanos * factor, "duration")); + return new Duration(checked(this[VALUE] * factor, "duration")); } /** This duration divided by a finite, positive divisor. */ div(divisor: number): Duration { if (!(divisor > 0)) throw new RangeError(`invalid divisor: ${divisor}`); - return new Duration(checked(this.#nanos / divisor, "duration")); + return new Duration(checked(this[VALUE] / divisor, "duration")); } /** How many times `other` fits in this duration, possibly fractional; throws a `RangeError` if `other` is zero. */ divDuration(other: Duration): number { - if (other.#nanos === 0) throw new RangeError("division by a zero duration"); - return this.#nanos / other.#nanos; + if (other[VALUE] === 0) throw new RangeError("division by a zero duration"); + return this[VALUE] / other[VALUE]; } /** The distance between both durations, whichever is longer. */ absDiff(other: Duration): Duration { - return new Duration(Math.abs(this.#nanos - other.#nanos)); + return new Duration(Math.abs(this[VALUE] - other[VALUE])); } /** Whether both durations are the same length. */ eq(other: Duration): boolean { - return this.#nanos === other.#nanos; + return this[VALUE] === other[VALUE]; + } + + /** -1, 0, or 1 as this is less than, equal to, or greater than `other`, for sorting. */ + cmp(other: Duration): -1 | 0 | 1 { + return this[VALUE] < other[VALUE] ? -1 : this[VALUE] > other[VALUE] ? 1 : 0; } /** Whether this duration is shorter than `other`. */ lt(other: Duration): boolean { - return this.#nanos < other.#nanos; + return this[VALUE] < other[VALUE]; } /** Whether this duration is at most `other`. */ le(other: Duration): boolean { - return this.#nanos <= other.#nanos; + return this[VALUE] <= other[VALUE]; } /** Whether this duration is longer than `other`. */ gt(other: Duration): boolean { - return this.#nanos > other.#nanos; + return this[VALUE] > other[VALUE]; } /** Whether this duration is at least `other`. */ ge(other: Duration): boolean { - return this.#nanos >= other.#nanos; + return this[VALUE] >= other[VALUE]; } /** The shorter of both durations. */ min(other: Duration): Duration { - return other.#nanos < this.#nanos ? other : this; + return other[VALUE] < this[VALUE] ? other : this; } /** The longer of both durations. */ max(other: Duration): Duration { - return other.#nanos > this.#nanos ? other : this; + return other[VALUE] > this[VALUE] ? other : this; } /** This duration limited to `[lo, hi]`. */ @@ -186,70 +198,77 @@ export class Instant { /** The clock's origin. */ static readonly ZERO: Instant = new Instant(0); - readonly #nanos: number; + /** @internal Nanoseconds since the origin. */ + readonly [VALUE]: number; + declare private readonly kind: "instant"; private constructor(nanos: number) { - this.#nanos = nanos; + this[VALUE] = nanos; } static { instantOf = (nanos) => new Instant(checked(nanos, "instant")); - instantNanos = (at) => at.#nanos; + instantNanos = (at) => at[VALUE]; } /** This instant moved forward by `duration`. */ add(duration: Duration): Instant { - return new Instant(checked(this.#nanos + duration.asNanos(), "instant")); + return new Instant(checked(this[VALUE] + duration.asNanos(), "instant")); } /** This instant moved back by `duration`; throws a `RangeError` before the clock's origin. */ sub(duration: Duration): Instant { - return new Instant(checked(this.#nanos - duration.asNanos(), "instant")); + return new Instant(checked(this[VALUE] - duration.asNanos(), "instant")); } /** The time from `earlier` to this instant, zero if `earlier` is later. */ since(earlier: Instant): Duration { - return this.#nanos > earlier.#nanos ? Duration.nanos(this.#nanos - earlier.#nanos) : Duration.ZERO; + return this[VALUE] > earlier[VALUE] ? Duration.nanos(this[VALUE] - earlier[VALUE]) : Duration.ZERO; } /** Whether both are the same instant. */ eq(other: Instant): boolean { - return this.#nanos === other.#nanos; + return this[VALUE] === other[VALUE]; + } + + /** -1, 0, or 1 as this is less than, equal to, or greater than `other`, for sorting. */ + cmp(other: Instant): -1 | 0 | 1 { + return this[VALUE] < other[VALUE] ? -1 : this[VALUE] > other[VALUE] ? 1 : 0; } /** Whether this instant is before `other`. */ lt(other: Instant): boolean { - return this.#nanos < other.#nanos; + return this[VALUE] < other[VALUE]; } /** Whether this instant is at or before `other`. */ le(other: Instant): boolean { - return this.#nanos <= other.#nanos; + return this[VALUE] <= other[VALUE]; } /** Whether this instant is after `other`. */ gt(other: Instant): boolean { - return this.#nanos > other.#nanos; + return this[VALUE] > other[VALUE]; } /** Whether this instant is at or after `other`. */ ge(other: Instant): boolean { - return this.#nanos >= other.#nanos; + return this[VALUE] >= other[VALUE]; } /** The earlier of both instants. */ min(other: Instant): Instant { - return other.#nanos < this.#nanos ? other : this; + return other[VALUE] < this[VALUE] ? other : this; } /** The later of both instants. */ max(other: Instant): Instant { - return other.#nanos > this.#nanos ? other : this; + return other[VALUE] > this[VALUE] ? other : this; } /** The time since the origin with a unit, such as `Instant(1.5ms)`. */ toString(): string { - return `Instant(${this.#nanos / 1_000_000}ms)`; + return `Instant(${this[VALUE] / 1_000_000}ms)`; } /** Refuses: an instant has no unitless number. */ @@ -278,61 +297,67 @@ export class Wall { /** 1970-01-01T00:00:00Z. */ static readonly UNIX_EPOCH: Wall = new Wall(0); - // Milliseconds, since Unix nanoseconds pass 2^53. - readonly #millis: number; + /** @internal Unix milliseconds, since Unix nanoseconds pass 2^53. */ + readonly [VALUE]: number; + declare private readonly kind: "wall"; private constructor(millis: number) { - this.#millis = millis; + this[VALUE] = millis; } static { wallOf = (millis) => new Wall(checked(millis, "wall time")); - wallMillis = (at) => at.#millis; + wallMillis = (at) => at[VALUE]; } /** This time moved forward by `duration`. */ add(duration: Duration): Wall { - return new Wall(checked(this.#millis + duration.asMillis(), "wall time")); + return new Wall(checked(this[VALUE] + duration.asMillis(), "wall time")); } /** This time moved back by `duration`; throws a `RangeError` before the Unix epoch. */ sub(duration: Duration): Wall { - return new Wall(checked(this.#millis - duration.asMillis(), "wall time")); + return new Wall(checked(this[VALUE] - duration.asMillis(), "wall time")); } /** The time from `earlier` to this one, zero if `earlier` is later. */ since(earlier: Wall): Duration { - return this.#millis > earlier.#millis ? Duration.millis(this.#millis - earlier.#millis) : Duration.ZERO; + return this[VALUE] > earlier[VALUE] ? Duration.millis(this[VALUE] - earlier[VALUE]) : Duration.ZERO; } /** Whether both are the same time. */ eq(other: Wall): boolean { - return this.#millis === other.#millis; + return this[VALUE] === other[VALUE]; + } + + /** -1, 0, or 1 as this is less than, equal to, or greater than `other`, for sorting. */ + cmp(other: Wall): -1 | 0 | 1 { + return this[VALUE] < other[VALUE] ? -1 : this[VALUE] > other[VALUE] ? 1 : 0; } /** Whether this time is before `other`. */ lt(other: Wall): boolean { - return this.#millis < other.#millis; + return this[VALUE] < other[VALUE]; } /** Whether this time is at or before `other`. */ le(other: Wall): boolean { - return this.#millis <= other.#millis; + return this[VALUE] <= other[VALUE]; } /** Whether this time is after `other`. */ gt(other: Wall): boolean { - return this.#millis > other.#millis; + return this[VALUE] > other[VALUE]; } /** Whether this time is at or after `other`. */ ge(other: Wall): boolean { - return this.#millis >= other.#millis; + return this[VALUE] >= other[VALUE]; } /** The time as an ISO 8601 string, or Unix milliseconds past `Date`'s range. */ toString(): string { - return this.#millis <= 8.64e15 ? new Date(this.#millis).toISOString() : `Wall(${this.#millis}ms)`; + return this[VALUE] <= 8.64e15 ? new Date(this[VALUE]).toISOString() : `Wall(${this[VALUE]}ms)`; } /** Refuses: a wall time has no unitless number. */ diff --git a/js/net/bench/broadcasts.ts b/js/net/bench/broadcasts.ts index ec5b9d44e8d..5407694736d 100644 --- a/js/net/bench/broadcasts.ts +++ b/js/net/bench/broadcasts.ts @@ -1,5 +1,6 @@ /** Sweep observers against routes for one route update, and against tracks for one listing change. */ +import { Duration, Wall } from "@moq/clock"; import { Signal } from "@moq/signals"; import type { Grant } from "../src/auth.ts"; import { Producer as BroadcastProducer } from "../src/broadcast.ts"; @@ -215,7 +216,7 @@ for (const patternCount of [8, 32, 128]) { ); const start = performance.now(); for (let i = 0; i < 1024; i++) { - grant.set({ publish: new Path.Patterns(), subscribe, expires: i }); + grant.set({ publish: new Path.Patterns(), subscribe, expires: Wall.UNIX_EPOCH.add(Duration.millis(i)) }); await Promise.resolve(); } console.log(`fetch,${patternCount},${fetchCount},${(((performance.now() - start) * 1000) / 1024).toFixed(2)}`); diff --git a/js/net/bench/drift.ts b/js/net/bench/drift.ts index 65dd33ea94e..33bde3424d2 100644 --- a/js/net/bench/drift.ts +++ b/js/net/bench/drift.ts @@ -1,5 +1,5 @@ /** Sweep publishers, readers, and retained history for a parked frame read's drift check. */ -import { Manual, Milli } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { type Group, Time, Track } from "@moq/net"; import { hooks } from "../src/internal.ts"; @@ -15,7 +15,7 @@ export async function run(): Promise { // The same reordered-PTS verdict runs here in Chromium before timing any work. // No publisher limit, so the reader's own 80 ms budget alone judges the reordered tail. const check = new Track.Producer("reordered").accept({ timescale: Time.Timescale.MILLI, maxAge: null }); - const reader = check.subscribe({ delay: { max: Milli(80) } }); + const reader = check.subscribe({ delay: { max: Duration.millis(80) } }); try { for (const timestamps of [[0], [100], [150, 200, 160]]) { const group = check.appendGroup(); @@ -62,7 +62,7 @@ export async function run(): Promise { const subscribers = Array.from({ length: readers }, () => track.subscribe({ delay: { - max: Milli( + max: Duration.millis( (retained + Math.ceil((iterations + warmup) / offsets.length) + 1) * 100, ), diff --git a/js/net/bench/fetch.ts b/js/net/bench/fetch.ts index 0728d2c2350..e1b8800e8fa 100644 --- a/js/net/bench/fetch.ts +++ b/js/net/bench/fetch.ts @@ -1,5 +1,5 @@ /** Sweep cached groups, independent FETCH peers, and small or chunked frame payloads. */ -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { Fetch, FetchHeader, FetchOk } from "../src/ietf/fetch.ts"; import { decodeFetchObject } from "../src/ietf/object.ts"; import { Publisher } from "../src/ietf/publisher.ts"; @@ -20,7 +20,7 @@ for (const groups of [2, 128]) { for (const size of [16, 1000, SEGMENT_BYTES * 2]) { const origin = new Producer(); const route = origin.route(Path.from("fetch")); - const track = route.broadcast.createTrack("video", { maxAge: Milli(60_000) }); + const track = route.broadcast.createTrack("video", { maxAge: Duration.millis(60_000) }); for (let sequence = 0; sequence < groups; sequence++) { const group = track.appendGroup(); // Only the selected group needs payloads; the rest expose cache-table scans. diff --git a/js/net/bench/fills.ts b/js/net/bench/fills.ts index 498fdcb86a7..8991a448c78 100644 --- a/js/net/bench/fills.ts +++ b/js/net/bench/fills.ts @@ -1,5 +1,5 @@ /** Sweep cached groups against independent peers requesting draft-22 fills. */ -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { FetchHeader } from "../src/ietf/fetch"; import * as Filter from "../src/ietf/filter"; import { Parameters } from "../src/ietf/parameters"; @@ -20,7 +20,7 @@ for (const groups of [2, 16, 128]) { for (const subscribers of [1, 8]) { const origin = new Producer(); const publication = origin.route(Path.from("fills")); - const track = publication.broadcast.createTrack("video", { maxAge: Milli(60_000) }); + const track = publication.broadcast.createTrack("video", { maxAge: Duration.millis(60_000) }); for (let i = 0; i < groups; i++) { const group = track.appendGroup(); group.writeFrame({ payload: new Uint8Array([i % 256]) }); diff --git a/js/net/bench/ledger.ts b/js/net/bench/ledger.ts index f781b39c970..93041156533 100644 --- a/js/net/bench/ledger.ts +++ b/js/net/bench/ledger.ts @@ -1,5 +1,5 @@ /** Sweep sparse arrival order and rolling expiration against the retained gap count. */ -import { Instant, Milli, Nano } from "@moq/clock"; +import { Duration, Instant } from "@moq/clock"; import { Ledger } from "../src/ledger.ts"; /** Measure each arrival with the expiration and coverage checks its consumers perform. */ @@ -23,18 +23,18 @@ export function run(): void { ? Array.from({ length: count * 2 }, (_, i) => BigInt(i * 2)) : sequences.map((sequence) => BigInt(sequence)); const ledger = new Ledger(); - const grace = Milli(count); + const grace = Duration.millis(count); const start = performance.now(); for (let i = 0; i < count * (order === "rolling" ? 2 : 1); i++) { const sequence = keys[i]; - const at = order === "rolling" ? Instant(Nano.fromMilli(Milli(i))) : Instant.zero; + const at = order === "rolling" ? Instant.ZERO.add(Duration.millis(i)) : Instant.ZERO; ledger.account(sequence, sequence + 1n, at); ledger.expire(at, grace); if (!ledger.covers(sequence, sequence + 1n)) throw new Error("arrival missing"); } const arrivals = count * (order === "rolling" ? 2 : 1); console.log(`${count},${order},${(((performance.now() - start) * 1e6) / arrivals).toFixed(0)}`); - ledger.expire(Instant(Nano.fromMilli(Milli(count * 3))), grace); + ledger.expire(Instant.ZERO.add(Duration.millis(count * 3)), grace); if (!ledger.covers(0n, BigInt(arrivals * 2 - 1)) || ledger.hasGaps()) throw new Error("expiration incomplete"); } diff --git a/js/net/bench/refresh.ts b/js/net/bench/refresh.ts index 916d57df29e..0dca76f3ce0 100644 --- a/js/net/bench/refresh.ts +++ b/js/net/bench/refresh.ts @@ -1,5 +1,5 @@ /** Sweep retained groups, unrelated tracks, and joined readers for a refresh crossing one lite hop. */ -import { Manual, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { accept } from "../src/connection/accept.ts"; import { connect } from "../src/connection/connect.ts"; import { ALPN_07_WIP } from "../src/lite/version.ts"; @@ -83,7 +83,7 @@ for (const retained of [1, 64, 1024]) destination.close(); source.close(); for (const peer of peers) peer.abort(); - await clock.advance(Nano(0)); + await clock.advance(Duration.nanos(0)); installed.close(); } } diff --git a/js/net/bench/replay.ts b/js/net/bench/replay.ts index 558862700e1..7d445d1d692 100644 --- a/js/net/bench/replay.ts +++ b/js/net/bench/replay.ts @@ -1,5 +1,5 @@ /** Sweep cached-group replay to joining subscribers, and arrivals into unread backlogs. */ -import { Manual, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { Track } from "@moq/net"; type Order = "monotonic" | "reverse" | "mixed"; @@ -109,7 +109,7 @@ async function shape( track.finish(); track.close(); try { - await clock.advance(Nano.fromMilli(Milli(60_000))); + await clock.advance(Duration.millis(60_000)); } finally { installed.close(); } diff --git a/js/net/bench/resume-history.ts b/js/net/bench/resume-history.ts index fd417fbf752..2045992cbea 100644 --- a/js/net/bench/resume-history.ts +++ b/js/net/bench/resume-history.ts @@ -16,7 +16,7 @@ * exposes `gc` and fails once a retired route stays reachable. Bun scans its stack conservatively, * so a dead reference there can survive a collection. */ -import { Manual, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import type { Producer as BroadcastProducer } from "../src/broadcast.ts"; import { accept } from "../src/connection/accept.ts"; import { connect } from "../src/connection/connect.ts"; @@ -28,9 +28,9 @@ import { Front } from "../src/resume.ts"; import { wireOf } from "../src/wire.ts"; const PAYLOAD = 4096; -const MAX_DELAY = Milli(1000); +const MAX_DELAY = Duration.millis(1000); /** Past every cache's age-out, including the 30 s window a closed track's cache drains over. */ -const EXPIRY = Nano.fromMilli(Milli(60_000)); +const EXPIRY = Duration.millis(60_000); const url = new URL("https://localhost/resume-history"); type History = "stable" | "churn"; type Access = "lookup" | "fetch" | "subscribe"; diff --git a/js/net/bench/resume.ts b/js/net/bench/resume.ts index de26949e05b..a1b59ebedb2 100644 --- a/js/net/bench/resume.ts +++ b/js/net/bench/resume.ts @@ -6,7 +6,7 @@ * direct read does, and each swap should leave nothing behind once its groups are read. */ -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { Producer as BroadcastProducer } from "../src/broadcast.ts"; import { Producer as GroupProducer } from "../src/group.ts"; import { hooks } from "../src/internal.ts"; @@ -150,7 +150,7 @@ async function measureFlaps(readers: number, flaps: number): Promise { }); front.serve(handles[0]); const subscribers = Array.from({ length: readers }, () => - front.consumer.track("seq").subscribe({ delay: { max: Milli(3_600_000) } }), + front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(3_600_000) } }), ); const held = subscribers.map((subscriber) => { const group = subscriber.tryRecvGroup(); diff --git a/js/net/bench/serve-browser-entry.ts b/js/net/bench/serve-browser-entry.ts index bde56cddf01..7987ce60cda 100644 --- a/js/net/bench/serve-browser-entry.ts +++ b/js/net/bench/serve-browser-entry.ts @@ -1,6 +1,6 @@ /** Measure publisher fairness with memory-resident groups and an immediately writable transport. */ -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { randomHop } from "../src/hop.ts"; import { Publisher as IetfPublisher } from "../src/ietf/publisher.ts"; import { NativeSession } from "../src/ietf/session.ts"; @@ -19,7 +19,7 @@ async function measure(protocol: string, groups: number, viewers: number) { const origin = new Origin(); const broadcastRoute = origin.route(Path.from("bench")); const broadcast = broadcastRoute.broadcast; - const track = broadcast.createTrack("data", { maxAge: Milli(60_000), timescale: Timescale.MICRO }); + const track = broadcast.createTrack("data", { maxAge: Duration.millis(60_000), timescale: Timescale.MICRO }); const pair = createMockTransportPair(protocol === "lite" ? ALPN_05 : ALPN.DRAFT_22); const version = protocol === "lite" ? LiteVersion.DRAFT_05 : IetfVersion.DRAFT_22; let written = 0, @@ -65,7 +65,7 @@ async function measure(protocol: string, groups: number, viewers: number) { track: "data", priority: 0, startGroup: 0n, - maxDelay: Milli(60_000), + maxDelay: 60_000, }), stream, ) diff --git a/js/net/bench/subscribe-drop.ts b/js/net/bench/subscribe-drop.ts index bf4d9af8f59..1388d441e8d 100644 --- a/js/net/bench/subscribe-drop.ts +++ b/js/net/bench/subscribe-drop.ts @@ -1,5 +1,4 @@ /** Sweep failed group sends over independent publishers and subscribers. */ -import { Milli } from "@moq/clock"; import { randomHop } from "../src/hop.ts"; import { Publisher } from "../src/lite/publisher.ts"; import { decodeSubscribeResponseMaybe, Subscribe } from "../src/lite/subscribe.ts"; @@ -59,7 +58,7 @@ try { broadcast: Path.from("bench"), track: "video", priority: 0, - maxDelay: Milli(30_000), + maxDelay: 30_000, startGroup: 0n, }), server, diff --git a/js/net/bench/track.ts b/js/net/bench/track.ts index ce7d312ebc7..bcfabf27c67 100644 --- a/js/net/bench/track.ts +++ b/js/net/bench/track.ts @@ -1,6 +1,6 @@ /** Sweep retained groups and subscribers for one group published through a track and received. */ -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { DEFAULT_EXPIRY } from "../src/cache.ts"; import type { Consumer as GroupConsumer, Producer as GroupProducer } from "../src/group.ts"; import { Timescale, Timestamp } from "../src/time.ts"; @@ -54,13 +54,13 @@ async function measure( ): Promise<{ publish: number; end: number; idle: number }> { // Held rows stay within the idle window while the media budget keeps their frames usable. const held = hold.count; - const window = Milli(held > 0 ? 3_600_000 : retained); + const window = Duration.millis(held > 0 ? 3_600_000 : retained); const producer = new Producer("bench").accept({ timescale: Timescale.MILLI, maxAge: window }); const subscribers = Array.from({ length: subscriberCount }, () => producer.subscribe({ delay: { max: window } })); let sequence = 0; // Inserted by sequence, the way the wire hands a subscribed track its groups. const publish = (close: boolean) => { - clock += held > 0 ? 1 : DEFAULT_EXPIRY / retained; + clock += held > 0 ? 1 : DEFAULT_EXPIRY.asMillis() / retained; const group = producer.createGroup(BigInt(sequence)); group.writeFrame({ payload, timestamp: Timestamp.fromMillis(sequence++) }); if (close) group.finish(); @@ -113,7 +113,7 @@ async function measure( producer.finish(); producer.close(); // Ending the track releases the newest group too; idle cleanup reclaims the cache. - clock += 2 * DEFAULT_EXPIRY; + clock += 2 * DEFAULT_EXPIRY.asMillis(); const idleStart = now(); const replay = producer.subscribe({ delay: { max: window } }); if (replay.tryRecvGroup()) throw new Error("idle cache entries were retained"); diff --git a/js/net/src/auth.test.ts b/js/net/src/auth.test.ts index c8db03b39d1..7fa515241e9 100644 --- a/js/net/src/auth.test.ts +++ b/js/net/src/auth.test.ts @@ -1,5 +1,5 @@ import { describe, expect, spyOn, test } from "bun:test"; -import { Manual, Milli, Nano, yieldNow } from "@moq/clock"; +import { Duration, Manual, yieldNow } from "@moq/clock"; import { Duplicate, type Grant, Handle, type Issued, type Request, type Requests, Unsupported } from "./auth.ts"; import { accept as acceptSession, connect as connectSession, type Established } from "./connection/index.ts"; import { SessionCode, SessionError, StreamCode, StreamError, toStreamCode } from "./error.ts"; @@ -153,10 +153,10 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("%s", (protocol) => { streams[0]?.abort(new StreamError(StreamCode.Internal, { message: "lost" })); await waitFor(token.grant, (g) => g === undefined); - await clock.advance(Nano.fromMilli(Milli(999))); + await clock.advance(Duration.millis(999)); for (let i = 0; i < 10; i++) await yieldNow(); expect(streams.length).toBe(1); - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); await waitFor(token.grant, (g) => g?.publish.equals(patterns("a")) === true); expect(streams.length).toBe(2); expect(ended).toBe(false); @@ -204,7 +204,7 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("%s", (protocol) => { first.writer.reset(new StreamError(StreamCode.Internal, { message: "lost" })); await waitFor(token.grant, (g) => g === undefined); - await clock.advance(Nano.fromMilli(Milli(1000))); + await clock.advance(Duration.millis(1000)); await waitFor(token.grant, (g) => g?.publish.equals(patterns("a")) === true); expect(streams.length).toBe(2); expect(abandoned).toBeInstanceOf(Error); @@ -380,7 +380,7 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("%s", (protocol) => { const third = await nextRoute(announced); expect(third?.kind).toBe("start"); - expect(await settlesWithin(transport.closed, clock, Milli(10))).toBe(false); + expect(await settlesWithin(transport.closed, clock, Duration.millis(10))).toBe(false); announced.close(); client.abort(); @@ -465,7 +465,7 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("%s", (protocol) => { const track = wireOf(client).consume(Path.from("room/x")).track("video").subscribe(); await yieldNow(); expect(track.closed.peek()).toBeUndefined(); - clock.jump(Nano.fromMilli(Milli(7))); + clock.jump(Duration.millis(7)); const firstGrant = unanswered.accept(grant([], ["room"])); const first = await adding; expect(await track.recvGroup()).toBeDefined(); @@ -655,7 +655,7 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("%s", (protocol) => { expect( await withTimeout( Promise.resolve(issued.closed), - Nano.fromMilli(Milli(1000)), + Duration.millis(1000), "the grant stream never closed", ), ).toBeNull(); @@ -727,17 +727,17 @@ test("lite-07 presents a transiently refused token again after a backoff", async }; /** The token presented again, exactly once `backoff` passes. */ - const after = async (backoff: Milli) => { + const after = async (backoff: Duration) => { let presented = false; const next = requests.next().then((request) => { presented = true; return request; }); - await clock.advance(Nano.fromMilli(Milli(backoff - 1))); + await clock.advance(backoff.sub(Duration.millis(1))); for (let i = 0; i < 10; i++) await yieldNow(); expect(presented).toBe(false); expect(added).toBe(false); - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); return await next; }; @@ -758,9 +758,9 @@ test("lite-07 presents a transiently refused token again after a backoff", async .then((value) => { ready = value; }); - await refuse(await after(Milli(1000))); + await refuse(await after(Duration.millis(1000))); expect(ready).toBeUndefined(); - const accepted = await after(Milli(2000)); + const accepted = await after(Duration.millis(2000)); if (!accepted) throw new Error("the token was not presented again"); issued.push(accepted.accept(grant(["a"], []))); const token = await adding; @@ -805,12 +805,12 @@ test("lite-07 presents a shared token again when its retry stream is reset", asy read = spyOn(LiteAuthWire.prototype, "read").mockRejectedValue( new StreamError(StreamCode.Cancel, { message: "reset" }), ); - await clock.advance(Nano.fromMilli(Milli(1000))); + await clock.advance(Duration.millis(1000)); await settles(() => logged("auth token ended") > 0); for (let i = 0; i < 10; i++) await yieldNow(); expect(rejected).toBeUndefined(); - await clock.advance(Nano.fromMilli(Milli(2000))); + await clock.advance(Duration.millis(2000)); await settles(() => logged("auth token ended") > 1); expect(rejected).toBeUndefined(); } finally { @@ -874,7 +874,7 @@ test("lite-07 refuses a token added to a session's own handle after a GOAWAY", a await settles(() => !wireOf(client).auth.active); try { - const late = withTimeout(client.auth.add("late"), Nano.fromMilli(Milli(1000)), "add after GOAWAY hung"); + const late = withTimeout(client.auth.add("late"), Duration.millis(1000), "add after GOAWAY hung"); await expect(late).rejects.toBeInstanceOf(StreamError); } finally { client.abort(); @@ -985,7 +985,7 @@ test("lite-07 ignores a draining session's late refusal while its successor retr expect(ended).toBe(false); const retried = successorRequests.next(); - await clock.advance(Nano.fromMilli(Milli(1000))); + await clock.advance(Duration.millis(1000)); const again = await retried; if (!again) throw new Error("the successor did not present the token again"); issued.push(again.accept(grant(["third"], []))); @@ -1453,8 +1453,7 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("AUTH violations %s", (pro await waitFor(pair.server.auth.grant, (g) => g !== undefined); await streams[0]?.writer.u53(0); expect( - (await withTimeout(pair.transport.closed, Nano.fromMilli(Milli(100)), "second AUTH did not close")) - .closeCode, + (await withTimeout(pair.transport.closed, Duration.millis(100), "second AUTH did not close")).closeCode, ).toBe(SessionCode.ProtocolViolation); } finally { spy.mockRestore(); @@ -1480,7 +1479,7 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("AUTH violations %s", (pro const added = pair.client.auth.add("bad").catch(() => undefined); try { expect( - (await withTimeout(pair.transport.closed, Nano.fromMilli(Milli(100)), "malformed AUTH did not close")) + (await withTimeout(pair.transport.closed, Duration.millis(100), "malformed AUTH did not close")) .closeCode, ).toBe(SessionCode.ProtocolViolation); } finally { @@ -1537,13 +1536,8 @@ describe.each([Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])("AUTH violations %s", (pro else await IetfMessage.encode(stream.writer, body, id); } expect( - ( - await withTimeout( - pair.transport.closed, - Nano.fromMilli(Milli(100)), - "malformed AUTH did not close", - ) - ).closeCode, + (await withTimeout(pair.transport.closed, Duration.millis(100), "malformed AUTH did not close")) + .closeCode, ).toBe(SessionCode.ProtocolViolation); } finally { spy.mockRestore(); @@ -1576,7 +1570,7 @@ describe.each([Ietf.ALPN.DRAFT_22])("AUTH request IDs %s", (protocol) => { ( await withTimeout( pair.transport.closed, - Nano.fromMilli(Milli(100)), + Duration.millis(100), "invalid AUTH ID left session open", ) ).closeCode, diff --git a/js/net/src/auth.ts b/js/net/src/auth.ts index b823668d440..27c352e4392 100644 --- a/js/net/src/auth.ts +++ b/js/net/src/auth.ts @@ -18,6 +18,7 @@ * @module */ +import type { Wall } from "@moq/clock"; import type { Getter } from "@moq/signals"; import type { SessionCode } from "./error.ts"; import type * as Path from "./path.ts"; @@ -34,8 +35,8 @@ export interface Grant { publish: Path.Patterns; /** The broadcasts this side may subscribe to from the peer. */ subscribe: Path.Patterns; - /** When the grant lapses, as `@moq/clock` wall time in Unix milliseconds, or undefined for never. */ - expires?: number; + /** When the grant lapses on the `@moq/clock` wall clock, or undefined for never. */ + expires?: Wall; } /** diff --git a/js/net/src/auth_session.ts b/js/net/src/auth_session.ts index e2871d95149..5dc21d3e3a5 100644 --- a/js/net/src/auth_session.ts +++ b/js/net/src/auth_session.ts @@ -1,4 +1,4 @@ -import { Instant, Milli, Nano, now, sleep, wall, yieldNow } from "@moq/clock"; +import { Duration, type Instant, now, sleep, type Wall, wall, yieldNow } from "@moq/clock"; import { type Dispose, type Getter, Once, race, Signal } from "@moq/signals"; import type { Credential, Grant, Issued, Request, Requests } from "./auth.ts"; import { closeReason, error, ProtocolViolation, SessionCode, SessionError, StreamCode, StreamError } from "./error.ts"; @@ -29,7 +29,9 @@ export async function decodePatterns(r: Reader): Promise { /** Whether two grants allow the same paths and lapse together. */ function grantsEqual(a: Grant | undefined, b: Grant | undefined): boolean { if (a === undefined || b === undefined) return a === b; - return a.publish.equals(b.publish) && a.subscribe.equals(b.subscribe) && a.expires === b.expires; + const expires = + a.expires === undefined || b.expires === undefined ? a.expires === b.expires : a.expires.eq(b.expires); + return a.publish.equals(b.publish) && a.subscribe.equals(b.subscribe) && expires; } /** The session or peer carries no AUTH exchange, or takes no tokens in band. */ @@ -57,8 +59,8 @@ export class Duplicate extends Error { * * @internal */ -export const RETRY_INITIAL = Milli(1000); -const RETRY_MAX = Milli(30_000); +export const RETRY_INITIAL = Duration.millis(1000); +const RETRY_MAX = Duration.millis(30_000); // Whether a refusal is the acceptor failing to decide rather than its verdict on the token, // such as an unreachable auth server or a full verification queue. @@ -114,12 +116,13 @@ export interface AuthWire { function union(grants: Iterable): Grant { const publish: Path.Pattern[] = []; const subscribe: Path.Pattern[] = []; - let expires: number | undefined; + let expires: Wall | undefined; for (const grant of grants) { for (const pattern of grant.publish) publish.push(pattern); for (const pattern of grant.subscribe) subscribe.push(pattern); // The earliest expiry is when the union next shrinks. - if (grant.expires !== undefined) expires = Math.min(expires ?? grant.expires, grant.expires); + if (grant.expires !== undefined && (expires === undefined || grant.expires.lt(expires))) + expires = grant.expires; } return { publish: new Path.Patterns(publish), subscribe: new Path.Patterns(subscribe), expires }; } @@ -514,7 +517,7 @@ class IssuedGrant implements Issued { const grant = this.#queued; this.#queued = undefined; if (grant === undefined) return; - const expires = grant.expires === undefined ? undefined : grant.expires - wall(); + const expires = grant.expires?.since(wall()).asMillis(); await this.#wire.grant(this.#stream, { publish: grant.publish, subscribe: grant.subscribe, expires }); }); } @@ -790,9 +793,7 @@ export class AuthSession { return true; } finally { if (started !== undefined) { - console.debug( - `request waited for authorization: path=${path} waited=${Nano.toMilli(Instant.durationSince(now(), started))}ms`, - ); + console.debug(`request waited for authorization: path=${path} waited=${now().since(started)}`); } } } @@ -873,7 +874,7 @@ export class AuthSession { let granted = false; // The peer replied to an earlier attempt, so it knows AUTH. let replied = false; - let delay: Milli | undefined; + let delay: Duration | undefined; for (;;) { refused = false; // Whether the peer answered this token, so a close is not the peer predating AUTH: @@ -906,7 +907,10 @@ export class AuthSession { break; } if ("grant" in reply) { - const expires = reply.grant.expires === undefined ? undefined : wall() + reply.grant.expires; + const expires = + reply.grant.expires === undefined + ? undefined + : wall().add(Duration.millis(reply.grant.expires)); presented.grant = { publish: reply.grant.publish, subscribe: reply.grant.subscribe, expires }; answered = granted = replied = true; delay = undefined; @@ -969,9 +973,9 @@ export class AuthSession { // might cover waits for the retry's verdict rather than being judged without it. this.#unsettle(presented); this.#recompute(); - delay = delay === undefined ? RETRY_INITIAL : Milli(Math.min(delay * 2, RETRY_MAX)); + delay = delay === undefined ? RETRY_INITIAL : delay.mul(2).min(RETRY_MAX); presented.retry = new AbortController(); - await sleep(Nano.fromMilli(delay), { signal: presented.retry.signal }).catch(() => void 0); + await sleep(delay, { signal: presented.retry.signal }).catch(() => void 0); presented.retry = undefined; if (this.#closed || presented.withdrawn || presented.ended) { refused = false; diff --git a/js/net/src/broadcast.test.ts b/js/net/src/broadcast.test.ts index b8511cf68c4..4522f30ef07 100644 --- a/js/net/src/broadcast.test.ts +++ b/js/net/src/broadcast.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Manual, Milli, Nano, yieldNow } from "@moq/clock"; +import { Duration, Manual, yieldNow } from "@moq/clock"; import { Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts"; import { NotFound, StreamCode } from "./error.ts"; import { hooks } from "./internal.ts"; @@ -320,19 +320,19 @@ test("a request exposes the aggregate subscription options", async () => { consumer.track("video").subscribe({ priority: 3, - delay: { max: Milli(100) }, + delay: { max: Duration.millis(100) }, ranges: [{ start: { absolute: 10n }, end: { absolute: 20n } }], }); consumer.track("video").subscribe({ priority: 7, - delay: { max: Milli(250) }, + delay: { max: Duration.millis(250) }, ranges: [{ start: { absolute: 0n }, end: { absolute: 30n } }], }); const request = await pendingRequest(consumer); expect(request?.subscription).toEqual({ priority: 7, - delay: { min: Milli.zero, max: Milli(250) }, + delay: { min: Duration.ZERO, max: Duration.millis(250) }, order: "descending", ranges: [{ start: { absolute: 0n }, end: { absolute: 30n } }], }); @@ -444,11 +444,11 @@ test("two subscribers to one inserted track each get a full copy", async () => { const a = broadcast .track("video") - .subscribe({ delay: { max: Milli(5000) } }) + .subscribe({ delay: { max: Duration.millis(5000) } }) .ordered(); const b = broadcast .track("video") - .subscribe({ delay: { max: Milli(5000) } }) + .subscribe({ delay: { max: Duration.millis(5000) } }) .ordered(); producer.writeFrame(textFrame("hello")); @@ -480,7 +480,7 @@ test("a read throws Evicted at a shed front, then resyncs to the next group", as const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); const sub = broadcast .track("video") - .subscribe({ delay: { max: Milli(5000) } }) + .subscribe({ delay: { max: Duration.millis(5000) } }) .ordered(); // Group 0 sheds its front without aborting the writer. @@ -502,7 +502,7 @@ test("a stalled consumer does not pin evicted groups", async () => { const clock = new Manual(); const installed = clock.install(); try { - clock.jump(Nano.fromMilli(Milli(10_000))); + clock.jump(Duration.millis(10_000)); const broadcast = new BroadcastProducer(); const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); @@ -515,7 +515,7 @@ test("a stalled consumer does not pin evicted groups", async () => { // Advance past the cache window and write again, which scans for idle groups. The old // (closed, aged-out) group is dropped from the stalled sink, not retained. - clock.jump(Nano.fromMilli(Milli(30_000 + 1_000))); + clock.jump(Duration.millis(30_000 + 1_000)); producer.writeFrame(textFrame("fresh")); // The next group in arrival order is the fresh one (seq 1): the old (seq 0) group @@ -535,11 +535,15 @@ test("a stalled consumer does not pin evicted groups", async () => { test("createTrack commits info up front", async () => { const broadcast = new BroadcastProducer(); - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: Milli(2000), priority: 3 }); + const producer = broadcast.createTrack("video", { + timescale: Timescale.MILLI, + maxAge: Duration.millis(2000), + priority: 3, + }); expect(producer.name).toBe("video"); const info = await broadcast.track("video").info(); - expect(info.maxAge).toBe(Milli(2000)); + expect(info.maxAge).toEqual(Duration.millis(2000)); expect(info.priority).toBe(3); }); @@ -560,7 +564,7 @@ test("a finished track is still served from its cache", async () => { const late = broadcast .consume() .track("track1") - .subscribe({ delay: { max: Milli(5000) } }) + .subscribe({ delay: { max: Duration.millis(5000) } }) .ordered(); expect(await late.readString()).toBe("last"); expect(await late.nextGroup()).toBeUndefined(); @@ -647,7 +651,7 @@ test("a fetch of a group still to come asks the request handler, and the write a test("fetch maxDelay tightens the publisher's maxAge without changing omission", async () => { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: Milli(2000) }); + const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: Duration.millis(2000) }); for (const millis of [0, 1000]) { const group = track.appendGroup(); @@ -662,7 +666,9 @@ test("fetch maxDelay tightens the publisher's maxAge without changing omission", expect(omitted.sequence).toBe(0n); omitted.close(); - await expect(wireOf(broadcast).fetchGroup("video", 0n, { maxDelay: Milli(0) })).rejects.toBeInstanceOf(NotFound); + await expect(wireOf(broadcast).fetchGroup("video", 0n, { maxDelay: Duration.millis(0) })).rejects.toBeInstanceOf( + NotFound, + ); broadcast.close(); }); diff --git a/js/net/src/cache.test.ts b/js/net/src/cache.test.ts index 7885e62b300..393fd3cdd67 100644 --- a/js/net/src/cache.test.ts +++ b/js/net/src/cache.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Manual, Milli, Nano, yieldNow } from "@moq/clock"; +import { Duration, Manual, yieldNow } from "@moq/clock"; import * as cache from "./cache.ts"; import { StreamCode, TooFarBehind } from "./error.ts"; import { hooks } from "./internal.ts"; @@ -10,7 +10,7 @@ async function withClock(fn: (clock: { advance: (ms: number) => Promise }) const clock = new Manual(); const installed = clock.install(); try { - await fn({ advance: (ms) => clock.advance(Nano.fromMilli(Milli(ms))) }); + await fn({ advance: (ms) => clock.advance(Duration.millis(ms)) }); } finally { installed.close(); } @@ -147,7 +147,7 @@ test("a read group outlives a later unread one", async () => { // it almost a window later. Mirrors Rust `delivery_restarts_the_expiry_clock`. test("delivery restarts a group's idle window", async () => { await withClock(async (clock) => { - const pool = new cache.Pool({ expiry: Milli(10_000) }); + const pool = new cache.Pool({ expiry: Duration.millis(10_000) }); const producer = pooled(pool); const subscriber = producer.subscribe({ delay: { max: null } }); finished(producer, 1); // seq 0 @@ -204,7 +204,7 @@ test("a shared capacity spares a fresher track and evicts a staler one's oldest" // excepted, and leaves only what those still bill. Mirrors Rust `pool_sweep_expires_without_a_write`. test("the sweep expires idle groups across tracks without a write", async () => { await withClock(async (clock) => { - const pool = new cache.Pool({ expiry: Milli(1_000) }); + const pool = new cache.Pool({ expiry: Duration.millis(1_000) }); const tracks = [pooled(pool, "a"), pooled(pool, "b")]; const stalled = tracks.map((track) => { const group = track.appendGroup(); // left open @@ -225,7 +225,7 @@ test("the sweep expires idle groups across tracks without a write", async () => // Every byte a group bills, its subscribers' mirrors included, goes back once it leaves. test("the pool is billed only for what is cached", async () => { await withClock(async (clock) => { - const pool = new cache.Pool({ expiry: Milli(1_000) }); + const pool = new cache.Pool({ expiry: Duration.millis(1_000) }); const producer = pooled(pool); const subscriber = producer.subscribe({ delay: { max: null } }); finished(producer, 100); diff --git a/js/net/src/cache.ts b/js/net/src/cache.ts index de7b9b80bb1..1dc82003142 100644 --- a/js/net/src/cache.ts +++ b/js/net/src/cache.ts @@ -18,10 +18,10 @@ * * @module */ -import { Instant, Milli, Nano, now, sleepUntil } from "@moq/clock"; +import { Duration, Instant, now, sleepUntil } from "@moq/clock"; /** How long a group nobody reads or writes stays cached by default, matching Rust `cache::DEFAULT_EXPIRY`. */ -export const DEFAULT_EXPIRY = Milli(30_000); +export const DEFAULT_EXPIRY = Duration.millis(30_000); // Bun 1.4's heap (bun:jsc `heapStats`) grows about 2.9 KB per cached single-frame group with no // subscriber, and 3.9 KB more per subscriber, whose sink holds its own mirror of every cached @@ -32,7 +32,7 @@ export const ENTRY_OVERHEAD = 3 * 1024; export const MIRROR_OVERHEAD = 4 * 1024; // The coarse clock behind access stamps, as Rust's: the expiry window rounds up to it. -const TICK = Nano.fromMilli(Milli(100)); +const TICK = Duration.millis(100); // Sub-tick boosts break ties within one tick: a write outranks a merely inserted group, and a // read outranks both, so a same-tick access still reads as newer than the mean of weaker ones. @@ -59,7 +59,7 @@ export interface Config { /** The byte target usage converges toward; unbounded when omitted. */ capacity?: number; /** How long a group nobody reads or writes stays cached; never reclaimed for idleness when omitted. */ - expiry?: Milli; + expiry?: Duration; } /** @@ -85,7 +85,7 @@ export class Pool { constructor(config: Config = {}) { this.#capacity = config.capacity ?? Number.POSITIVE_INFINITY; - if (config.expiry !== undefined) this.#expiry = Math.max(1, Math.ceil(Nano.fromMilli(config.expiry) / TICK)); + if (config.expiry !== undefined) this.#expiry = Math.max(1, Math.ceil(config.expiry.divDuration(TICK))); } /** The byte target, or undefined when unbounded. */ @@ -99,8 +99,8 @@ export class Pool { } /** The idle window, rounded up to the pool's 100 ms tick, or undefined when idle groups stay. */ - get expiry(): Milli | undefined { - return this.#expiry === undefined ? undefined : Nano.toMilli(Nano(this.#expiry * TICK)); + get expiry(): Duration | undefined { + return this.#expiry === undefined ? undefined : TICK.mul(this.#expiry); } /** Change the byte target; undefined makes it unbounded. Writes pay a shrink down as they go. */ @@ -112,7 +112,7 @@ export class Pool { now(): number { const at = now(); this.#epoch ??= at; - this.#tick = Math.max(this.#tick, Math.floor((at - this.#epoch) / TICK)); + this.#tick = Math.max(this.#tick, Math.floor(at.since(this.#epoch).divDuration(TICK))); return this.#tick; } @@ -191,7 +191,7 @@ export class Pool { if (this.#sweep !== undefined || this.#expiry === undefined || this.#tracks.size === 0) return; const sweep = new AbortController(); this.#sweep = sweep; - const at = Instant.add(now(), Nano((this.#expiry * TICK) / 2)); + const at = now().add(TICK.mul(this.#expiry / 2)); void sleepUntil(at, { signal: sweep.signal, ref: false }).then( () => { if (this.#sweep !== sweep) return; diff --git a/js/net/src/connection/accept.ts b/js/net/src/connection/accept.ts index a0b5ad99254..a1170f3fdb9 100644 --- a/js/net/src/connection/accept.ts +++ b/js/net/src/connection/accept.ts @@ -1,4 +1,4 @@ -import { Milli, Nano } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { race } from "@moq/signals"; import { ConnectTimeout, error, fromClose, ProtocolViolation } from "../error.ts"; import * as Ietf from "../ietf/index.ts"; @@ -21,7 +21,7 @@ export interface AcceptProps { url: URL; /** Bound SETUP in milliseconds (default: 30000; zero waits until aborted). Throws ConnectTimeout. */ - timeout?: Milli; + timeout?: Duration; /** Abort the handshake and release the transport; ignored after acceptance completes. */ signal?: AbortSignal; @@ -71,10 +71,9 @@ export async function accept({ transport, url, ...props }: AcceptProps): Promise if ("discovery" in props) throw new TypeError(DISCOVERY_REMOVED); props.signal?.throwIfAborted(); const limit = props.timeout ?? DEFAULT_TIMEOUT; - const duration = Nano.fromMilli(Milli(limit)); const deadline = new AbortController(); const signal = props.signal ? AbortSignal.any([props.signal, deadline.signal]) : deadline.signal; - const disarm = limit > 0 ? after(duration, () => deadline.abort(new ConnectTimeout(limit))) : () => {}; + const disarm = limit.isZero() ? () => {} : after(limit, () => deadline.abort(new ConnectTimeout(limit))); const pending = acceptInner(transport, url, props); // As on connect, a dead transport must end a SETUP whose peer sends nothing more. const terminal = transport.closed.then(fromClose, error).then((cause) => { diff --git a/js/net/src/connection/bandwidth.test.ts b/js/net/src/connection/bandwidth.test.ts index 50081cccbc0..eebe2c65296 100644 --- a/js/net/src/connection/bandwidth.test.ts +++ b/js/net/src/connection/bandwidth.test.ts @@ -1,5 +1,5 @@ import { afterEach, expect, spyOn, test } from "bun:test"; -import { Instant, Manual, Milli, Nano, now, yieldNow } from "@moq/clock"; +import { Duration, Manual, now, yieldNow } from "@moq/clock"; import * as Lite from "../lite/index.ts"; import { createMockTransportPair, type MockTransport } from "../mock.ts"; import { Producer as TrackProducer } from "../track.ts"; @@ -17,10 +17,10 @@ async function settle() { } async function waitUntil(pred: () => boolean, ms = 1000): Promise { - const deadline = Instant.add(now(), Nano.fromMilli(Milli(ms))); + const deadline = now().add(Duration.millis(ms)); for (;;) { if (pred()) return; - if (now() > deadline) throw new Error("timed out waiting for condition"); + if (now().gt(deadline)) throw new Error("timed out waiting for condition"); await settle(); } } @@ -131,7 +131,7 @@ test("a connection samples the transport only while a reservation reads the esti return pair.client; }; globalThis.WebTransport = stub as unknown as typeof WebTransport; - const advance = (ms: number) => clock.advance(Nano.fromMilli(Milli(ms))); + const advance = (ms: number) => clock.advance(Duration.millis(ms)); // Snapshots taken over 350 ms of manual time, enough for three 100 ms ticks. const sampled = async () => { const before = calls; @@ -203,7 +203,7 @@ for (const kind of silent) { const connection = new Connection({ url }); try { - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(connection.status.peek()).toBe("connected"); const allocator = connection.allocator.peek(); if (!allocator) throw new Error("missing allocator"); @@ -211,7 +211,7 @@ for (const kind of silent) { const track = new TrackProducer("video").accept({ priority: 60 }); track.subscribe(); const reservation = allocator.reserve(track.demand(), 4_000_000); - await clock.advance(Nano.fromMilli(Milli(350))); + await clock.advance(Duration.millis(350)); expect(snapshots).toHaveBeenCalledTimes(0); // The estimate stays unknown, so the sender holds its rate. expect(reservation.peek()).toBeUndefined(); diff --git a/js/net/src/connection/close.test.ts b/js/net/src/connection/close.test.ts index d15c7c770bf..b592496faad 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 { type Installed, Manual, Nano, Second } from "@moq/clock"; +import { Duration, type Installed, Manual } from "@moq/clock"; import * as Ietf from "../ietf/index.ts"; import * as Lite from "../lite/index.ts"; import { createMockTransportPair, type MockTransport } from "../mock.ts"; @@ -83,7 +83,7 @@ for (const protocol of [Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_18]) { if (outcome === "timeout") { // bun's `rejects` blocks on a pending promise, so catch first and advance. const timedOut = closing.catch((err: unknown) => err); - await clock.advance(Nano.fromSecond(Second(1))); + await clock.advance(Duration.secs(1)); expect(await timedOut).toHaveProperty("message", "session close timed out"); } else { fin.release(); diff --git a/js/net/src/connection/connect.test.ts b/js/net/src/connection/connect.test.ts index 50c8e320676..a0c99b17b40 100644 --- a/js/net/src/connection/connect.test.ts +++ b/js/net/src/connection/connect.test.ts @@ -1,5 +1,5 @@ -import { expect, spyOn, test } from "bun:test"; -import { Manual, Milli, Nano, sleep, yieldNow } from "@moq/clock"; +import { expect, test } from "bun:test"; +import { Duration, Instant, Manual, sleep, yieldNow } from "@moq/clock"; import { hostTime } from "@moq/clock/test"; import Qmux, { selectSubprotocol, type WebSocketLike } from "@moq/qmux"; import { ConnectTimeout, SessionCode, SessionError } from "../error.ts"; @@ -141,7 +141,7 @@ function fingerprintServer(respond: (request: Request) => Response | Promise boolean) { - for (let i = 0; i < 200 && !ready(); i++) await sleep(Nano.fromMilli(Milli(5))); + for (let i = 0; i < 200 && !ready(); i++) await sleep(Duration.millis(5)); } test("an http:// URL pins the fetched fingerprint and dials https", async () => { @@ -197,7 +197,7 @@ test("a fingerprint fetch slower than the hedge starts no second dial", async () try { const connecting = connect(server.url, { websocket: { enabled: false } }); await requested.promise; - await clock.advance(Nano.fromMilli(Milli(1_000))); + await clock.advance(Duration.millis(1_000)); // The hedge logs inside its timer callback, so this catches it as deterministically as the // clock; the dial/request counts below race connect() cancelling the hedge once one dial wins. expect(captured.lines.filter((line) => line.includes("dialing a second"))).toEqual([]); @@ -496,7 +496,7 @@ test("SETUP preserves a delayed session close code", async () => { (cause: unknown) => cause, ); try { - await clock.advance(Nano.fromMilli(Milli(1_000))); + await clock.advance(Duration.millis(1_000)); expect(localCloses).toBe(0); closed.resolve({ closeCode: SessionCode.Unauthorized, reason: "unauthorized" }); const cause = await result; @@ -882,13 +882,13 @@ test("a dial nothing answers fails with ConnectTimeout after the default timeout const silent = silentWebTransport(); try { const attempt = track(connect(url, { websocket: { enabled: false } })); - await clock.advance(Nano.fromMilli(Milli(29_999))); + await clock.advance(Duration.millis(29_999)); expect(attempt.outcome()).toBeUndefined(); - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); await settle(); expect(attempt.outcome()).toBeInstanceOf(ConnectTimeout); - expect((attempt.outcome() as ConnectTimeout).timeout).toBe(Milli(30_000)); + expect((attempt.outcome() as ConnectTimeout).timeout).toEqual(Duration.millis(30_000)); // The dial and its hedge. expect(silent.closes()).toBe(2); } finally { @@ -904,9 +904,9 @@ test("a timeout of 0 waits for the caller", async () => { try { const controller = new AbortController(); const attempt = track( - connect(url, { websocket: { enabled: false }, timeout: Milli(0), signal: controller.signal }), + connect(url, { websocket: { enabled: false }, timeout: Duration.millis(0), signal: controller.signal }), ); - await clock.advance(Nano.fromMilli(Milli(600_000))); + await clock.advance(Duration.millis(600_000)); expect(attempt.outcome()).toBeUndefined(); const reason = new Error("teardown"); @@ -926,13 +926,13 @@ test("the caller's abort wins over the timeout and disarms it", async () => { try { const controller = new AbortController(); const attempt = track(connect(url, { websocket: { enabled: false }, signal: controller.signal })); - await clock.advance(Nano.fromMilli(Milli(10_000))); + await clock.advance(Duration.millis(10_000)); const reason = new Error("teardown"); controller.abort(reason); await settle(); expect(attempt.outcome()).toBe(reason); - await clock.advance(Nano.fromMilli(Milli(60_000))); + await clock.advance(Duration.millis(60_000)); expect(attempt.outcome()).toBe(reason); // The dial and its hedge. expect(silent.closes()).toBe(2); @@ -954,11 +954,11 @@ test("a handshake the peer never answers times out on a supplied transport too", () => (transportClosed = true), ); - const attempt = track(connect(url, { transport: pair.client, timeout: Milli(5_000) })); - await clock.advance(Nano.fromMilli(Milli(4_999))); + const attempt = track(connect(url, { transport: pair.client, timeout: Duration.millis(5_000) })); + await clock.advance(Duration.millis(4_999)); expect(attempt.outcome()).toBeUndefined(); - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); await settle(); expect(attempt.outcome()).toBeInstanceOf(ConnectTimeout); expect(transportClosed).toBe(true); @@ -967,7 +967,7 @@ test("a handshake the peer never answers times out on a supplied transport too", } }); -type Dial = "hang" | "ok" | { failAfter: Milli } | { openWhen: Promise }; +type Dial = "hang" | "ok" | { failAfter: Duration } | { openWhen: Promise }; // Stub WebTransport so each dial behaves as `plan` says, recording when it was dialed (on // the Manual clock) and how often it was closed. @@ -976,14 +976,14 @@ function webTransportPlan(clock: Manual, plan: (dial: number) => Dial) { const dials: { at: number; closes: number }[] = []; globalThis.WebTransport = function StubWebTransport() { const index = dials.length; - const record = { at: Nano.toMilli(Nano(clock.now())), closes: 0 }; + const record = { at: clock.now().since(Instant.ZERO).asMillis(), closes: 0 }; dials.push(record); const dial = plan(index); if (dial === "hang" || (typeof dial === "object" && "failAfter" in dial)) { const ready = dial === "hang" ? new Promise(() => {}) - : sleep(Nano.fromMilli(dial.failAfter)).then(() => { + : sleep(dial.failAfter).then(() => { throw new Error(`refused ${index}`); }); ready.catch(() => {}); @@ -1013,10 +1013,10 @@ test("a dial still unopened after 500 ms is hedged, and the hedge wins when the const plan = webTransportPlan(clock, (dial) => (dial === 0 ? "hang" : "ok")); try { const attempt = connect(url, { websocket: { enabled: false } }); - await clock.advance(Nano.fromMilli(Milli(499))); + await clock.advance(Duration.millis(499)); expect(plan.dials.length).toBe(1); - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); const connection = await attempt; expect(plan.dials.map((dial) => dial.at)).toEqual([0, 500]); await settle(); @@ -1034,7 +1034,7 @@ test("a dial that opens within 500 ms is not hedged", async () => { const plan = webTransportPlan(clock, () => "ok"); try { const connection = await connect(url, { websocket: { enabled: false } }); - await clock.advance(Nano.fromMilli(Milli(5_000))); + await clock.advance(Duration.millis(5_000)); expect(plan.dials.length).toBe(1); connection.abort(); } finally { @@ -1046,10 +1046,10 @@ test("a dial that opens within 500 ms is not hedged", async () => { test("a dial that fails outright is not hedged", async () => { const clock = new Manual(); const installed = clock.install(); - const plan = webTransportPlan(clock, () => ({ failAfter: Milli(100) })); + const plan = webTransportPlan(clock, () => ({ failAfter: Duration.millis(100) })); try { const attempt = track(connect(url, { websocket: { enabled: false } })); - await clock.advance(Nano.fromMilli(Milli(5_000))); + await clock.advance(Duration.millis(5_000)); await settle(); expect(plan.dials.length).toBe(1); expect((attempt.outcome() as Error).message).toBe("no transport connected: refused 0"); @@ -1063,10 +1063,10 @@ test("when a dial and its hedge both fail, the first dial's reason is reported", const clock = new Manual(); const installed = clock.install(); // The hedge dials at 500 ms and fails at 600 ms; the first fails at 1.5 s. - const plan = webTransportPlan(clock, (dial) => ({ failAfter: Milli(dial === 0 ? 1_500 : 100) })); + const plan = webTransportPlan(clock, (dial) => ({ failAfter: Duration.millis(dial === 0 ? 1_500 : 100) })); try { const attempt = track(connect(url, { websocket: { enabled: false } })); - await clock.advance(Nano.fromMilli(Milli(2_000))); + await clock.advance(Duration.millis(2_000)); await settle(); expect(plan.dials.length).toBe(2); expect((attempt.outcome() as Error).message).toBe("no transport connected: refused 0"); @@ -1089,7 +1089,7 @@ test("when a dial and its hedge open in the same turn, one wins and the other is }); try { const attempt = connect(url, { websocket: { enabled: false } }); - await clock.advance(Nano.fromMilli(Milli(500))); + await clock.advance(Duration.millis(500)); const connection = await attempt; await settle(); expect(plan.dials.length).toBe(2); @@ -1106,11 +1106,11 @@ test("a hedge that opens after the first dial failed still wins", async () => { const installed = clock.install(); // The hedge dials at 500 ms and opens at 2 s; the first fails at 1.5 s in between. const plan = webTransportPlan(clock, (dial) => - dial === 0 ? { failAfter: Milli(1_500) } : { openWhen: sleep(Nano.fromMilli(Milli(1_500))) }, + dial === 0 ? { failAfter: Duration.millis(1_500) } : { openWhen: sleep(Duration.millis(1_500)) }, ); try { const attempt = connect(url, { websocket: { enabled: false } }); - await clock.advance(Nano.fromMilli(Milli(2_000))); + await clock.advance(Duration.millis(2_000)); const connection = await attempt; expect(plan.dials.map((dial) => dial.at)).toEqual([0, 500]); connection.abort(); @@ -1129,7 +1129,7 @@ test("when the WebSocket wins, every WebTransport dial is closed", async () => { const originalStream = native.WebSocketStream; native.WebSocketStream = class { url: string; - opened = sleep(Nano.fromMilli(Milli(100))).then(qmuxStreams); + opened = sleep(Duration.millis(100)).then(qmuxStreams); closed = new Promise(() => {}); constructor(url: string) { this.url = url; @@ -1140,7 +1140,7 @@ test("when the WebSocket wins, every WebTransport dial is closed", async () => { try { // Its own host: a WebSocket win drops WebTransport's head start for that host and port afterwards. const pending = connect(new URL("https://websocket-wins.example.com/"), { signal: controller.signal }); - await clock.advance(Nano.fromMilli(Milli(700))); + await clock.advance(Duration.millis(700)); expect(plan.dials.map((dial) => dial.at)).toEqual([0, 500]); expect(plan.dials.map((dial) => dial.closes)).toEqual([1, 1]); @@ -1179,7 +1179,7 @@ test("when WebTransport and WebSocket open in the same turn, the one not chosen try { // Its own host: a WebSocket win drops WebTransport's head start for that host and port afterwards. const pending = connect(new URL("https://same-turn.example.com/"), { - websocket: { delay: Milli(0) }, + websocket: { delay: Duration.millis(0) }, signal: controller.signal, }); await settle(); @@ -1210,7 +1210,7 @@ test("the caller's abort wins over a timeout that fires in the same turn", async await settle(); const reason = new Error("teardown"); // Fire the timeout without running any task, then abort before one runs. - clock.jump(Nano.fromMilli(Milli(30_000))); + clock.jump(Duration.millis(30_000)); controller.abort(reason); await settle(); expect(attempt.outcome()).toBe(reason); @@ -1227,8 +1227,8 @@ test("a connected session outlives its connect timeout", async () => { const pair = createMockTransportPair(ALPN_06); let closed = false; void pair.client.closed.then(() => (closed = true)); - const connection = await connect(url, { transport: pair.client, timeout: Milli(1_000) }); - await clock.advance(Nano.fromMilli(Milli(2_000))); + const connection = await connect(url, { transport: pair.client, timeout: Duration.millis(1_000) }); + await clock.advance(Duration.millis(2_000)); await settle(); expect(closed).toBe(false); connection.abort(); @@ -1249,13 +1249,13 @@ test("timeout race never returns a closed connection", async () => { void pair.client.closed.then(() => { transportClosed = true; }); - const outcome = connect(url, { transport: pair.client, timeout: Milli(1) }).then( + const outcome = connect(url, { transport: pair.client, timeout: Duration.millis(1) }).then( (connection) => ({ connection }), (err: unknown) => ({ err }), ); void (async () => { for (let i = 0; i < hops; i++) await Promise.resolve(); - clock.jump(Nano.fromMilli(Milli(1))); + clock.jump(Duration.millis(1)); })(); const result = await outcome; await settle(); @@ -1272,19 +1272,6 @@ test("timeout race never returns a closed connection", async () => { } }); -test("an invalid timeout throws before touching the caller's signal", async () => { - const controller = new AbortController(); - const added = spyOn(controller.signal, "addEventListener"); - for (const timeout of [-1, Number.NaN, Number.POSITIVE_INFINITY]) { - await expect( - connect(url, { websocket: { enabled: false }, timeout: timeout as Milli, signal: controller.signal }), - ).rejects.toThrow(RangeError); - } - expect(added).not.toHaveBeenCalled(); - // In the caller's unit, not the nanoseconds it is converted to. - await expect(connect(url, { timeout: -1 as Milli })).rejects.toThrow("invalid time: -1"); -}); - /** An opened WebSocketStream whose QMux server sent only its TRANSPORT_PARAMETERS (all * defaults), which a session's `ready` waits for. */ function qmuxStreams() { @@ -1299,7 +1286,7 @@ function qmuxStreams() { }; } -type WebSocketDial = "hang" | "open" | { failAfter: Milli } | { openAfter: Milli }; +type WebSocketDial = "hang" | "open" | { failAfter: Duration } | { openAfter: Duration }; // Their own host: a WebSocket that wins drops WebTransport's head start for its host and port afterwards. const websocketUrl = new URL("https://websocket-only.example.com/"); @@ -1322,16 +1309,16 @@ function webSocketPlan(clock: Manual, plan: (dial: number) => WebSocketDial) { constructor(url: string) { this.url = url; const index = dials.length; - this.#record = { at: Nano.toMilli(Nano(clock.now())), closes: 0 }; + this.#record = { at: clock.now().since(Instant.ZERO).asMillis(), closes: 0 }; dials.push(this.#record); const dial = plan(index); if (dial === "hang") this.opened = new Promise(() => {}); else if (dial === "open") this.opened = Promise.resolve(streams()); else if ("failAfter" in dial) - this.opened = sleep(Nano.fromMilli(dial.failAfter)).then(() => { + this.opened = sleep(dial.failAfter).then(() => { throw new Error(`refused ${index}`); }); - else this.opened = sleep(Nano.fromMilli(dial.openAfter)).then(streams); + else this.opened = sleep(dial.openAfter).then(streams); this.opened.catch(() => {}); } close() { @@ -1354,13 +1341,13 @@ test("a WebSocket dial still unopened after 10 s is closed and dialed again", as const controller = new AbortController(); try { const pending = connect(websocketUrl, { signal: controller.signal }); - await clock.advance(Nano.fromMilli(Milli(9_999))); + await clock.advance(Duration.millis(9_999)); expect(plan.dials.length).toBe(1); - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); expect(plan.dials.map((dial) => dial.at)).toEqual([0, 10_000]); // The session flushes its close for 100 ms before closing the socket. - await clock.advance(Nano.fromMilli(Milli(100))); + await clock.advance(Duration.millis(100)); expect(plan.dials.map((dial) => dial.closes)).toEqual([1, 0]); // The second dial opened; its SETUP is never answered. @@ -1378,8 +1365,8 @@ test("each WebSocket redial within an attempt waits twice as long", async () => const plan = webSocketPlan(clock, () => "hang"); const controller = new AbortController(); try { - const pending = connect(websocketUrl, { timeout: Milli(0), signal: controller.signal }); - await clock.advance(Nano.fromMilli(Milli(75_000))); + const pending = connect(websocketUrl, { timeout: Duration.millis(0), signal: controller.signal }); + await clock.advance(Duration.millis(75_000)); expect(plan.dials.map((dial) => dial.at)).toEqual([0, 10_000, 30_000, 70_000]); expect(plan.dials.map((dial) => dial.closes)).toEqual([1, 1, 1, 0]); @@ -1394,10 +1381,10 @@ test("each WebSocket redial within an attempt waits twice as long", async () => test("a WebSocket dial that fails outright is not redialed", async () => { const clock = new Manual(); const installed = clock.install(); - const plan = webSocketPlan(clock, () => ({ failAfter: Milli(100) })); + const plan = webSocketPlan(clock, () => ({ failAfter: Duration.millis(100) })); try { const attempt = track(connect(websocketUrl, {})); - await clock.advance(Nano.fromMilli(Milli(20_000))); + await clock.advance(Duration.millis(20_000)); await settle(); expect(plan.dials.length).toBe(1); expect((attempt.outcome() as Error).message).toBe("no transport connected: refused 0"); @@ -1410,11 +1397,11 @@ test("a WebSocket dial that fails outright is not redialed", async () => { test("a WebSocket dial that opens within 10 s is not redialed", async () => { const clock = new Manual(); const installed = clock.install(); - const plan = webSocketPlan(clock, () => ({ openAfter: Milli(5_000) })); + const plan = webSocketPlan(clock, () => ({ openAfter: Duration.millis(5_000) })); const controller = new AbortController(); try { const pending = connect(websocketUrl, { signal: controller.signal }); - await clock.advance(Nano.fromMilli(Milli(15_000))); + await clock.advance(Duration.millis(15_000)); expect(plan.dials.length).toBe(1); controller.abort(); @@ -1431,7 +1418,7 @@ test("with the default timeout, a silent WebSocket is redialed once and the atte const plan = webSocketPlan(clock, () => "hang"); try { const attempt = track(connect(websocketUrl, {})); - await clock.advance(Nano.fromMilli(Milli(30_100))); + await clock.advance(Duration.millis(30_100)); await settle(); expect(attempt.outcome()).toBeInstanceOf(ConnectTimeout); expect(plan.dials.map((dial) => dial.at)).toEqual([0, 10_000]); @@ -1454,11 +1441,11 @@ async function raceOnce( // `webSocketPlan` removes WebTransport; `webTransportPlan` puts a stub back over it. const sockets = webSocketPlan(clock, () => websocket); const transports = webTransportPlan(clock, () => webtransport); - const start = Nano.toMilli(Nano(clock.now())); + const start = clock.now().since(Instant.ZERO).asMillis(); const controller = new AbortController(); try { const pending = connect(target, { signal: controller.signal, ...props }); - await clock.advance(Nano.fromMilli(Milli(600))); + await clock.advance(Duration.millis(600)); // A WebSocket winner is still in SETUP, which nothing answers; a WebTransport one connected. controller.abort(); const connection = await pending.catch(() => undefined); @@ -1511,7 +1498,7 @@ test("a WebTransport win restores the head start", async () => { try { expect(await raceOnce(clock, target, "hang", "open")).toEqual([500]); // WebSocket won last, so it dials at once, but WebTransport opens first and wins. - expect(await raceOnce(clock, target, { openWhen: sleep(Nano.fromMilli(Milli(100))) }, "hang")).toEqual([0]); + expect(await raceOnce(clock, target, { openWhen: sleep(Duration.millis(100)) }, "hang")).toEqual([0]); expect(await raceOnce(clock, target, "hang", "open")).toEqual([500]); } finally { installed.close(); diff --git a/js/net/src/connection/connect.ts b/js/net/src/connection/connect.ts index 3310bcc156f..3aa7c822e79 100644 --- a/js/net/src/connection/connect.ts +++ b/js/net/src/connection/connect.ts @@ -1,4 +1,4 @@ -import { Elapsed, Milli, Nano, sleep, timeout } from "@moq/clock"; +import { Duration, Elapsed, sleep, timeout } from "@moq/clock"; import Session, { type SessionOptions as QmuxOptions, type Version as QmuxVersion } from "@moq/qmux"; import { type Getter, race } from "@moq/signals"; import type * as Auth from "../auth.ts"; @@ -22,19 +22,19 @@ import { inspect } from "./stats.ts"; import { credential, fallback, hold, type Presentation } from "./tokens.ts"; // Default head start for WebTransport before attempting the WebSocket fallback. -const DEFAULT_WEBSOCKET_DELAY_MS = Milli(500); +const DEFAULT_WEBSOCKET_DELAY = Duration.millis(500); // How long the first WebTransport dial may stay unopened before a second one dials alongside // it. The same moment as the WebSocket's default head start, so a fresh WebTransport flow // races the fallback rather than losing to it, which would leave the session on WebSocket for // good. A healthy open is about two round trips, so this spares round trips up to about // 250 ms, and it is inside the 2 s ceiling RFC 8305 recommends for staggered attempts. -const WEBTRANSPORT_HEDGE = DEFAULT_WEBSOCKET_DELAY_MS; +const WEBTRANSPORT_HEDGE = DEFAULT_WEBSOCKET_DELAY; // How long a WebSocket dial may stay unopened before it is closed and dialed again. Generous, // since script cannot tell a silent connect from a slow one; Firefox and socket.io give a // WebSocket 20 s to open. -const WEBSOCKET_REDIAL = Milli(10_000); +const WEBSOCKET_REDIAL = Duration.millis(10_000); // MoQ holds a stream open per subscription and per live group, far past qmux's default of // 100 each way, where the peer's opens are refused or wait on credit forever. Matches @@ -47,7 +47,7 @@ const DEFAULT_STREAM_RECEIVE_WINDOW = 1 << 20; // RESET_STREAM and CONNECTION_CLOSE are separate transport notifications. Give the latter // time to surface its authoritative code without letting a reset-only peer stall SETUP forever. -const SETUP_CLOSE_GRACE = Nano.fromMilli(Milli(100)); +const SETUP_CLOSE_GRACE = Duration.millis(100); /** Tuning for the WebSocket fallback used when WebTransport is unavailable or loses the connect race. */ export interface WebSocketProps { @@ -62,7 +62,7 @@ export interface WebSocketProps { * It is 0 while WebSocket holds the last win against the host and port the fallback dials, * until WebTransport wins a race there again. */ - delay?: Milli; + delay?: Duration; /** * How many streams the server may hold open at once, applied to bidirectional and @@ -295,7 +295,7 @@ export interface ConnectProps { * deadline of its own (default: 30000ms). `0` waits forever. Past it, the connect rejects * with {@link ConnectTimeout} and closes whatever it had opened. */ - timeout?: Milli; + timeout?: Duration; /** * Aborts the connection attempt with the signal's reason. An already-aborted @@ -353,8 +353,6 @@ export async function connect({ url, ...props }: ConnectProps): Promise(); @@ -362,13 +360,12 @@ export async function connect({ url, ...props }: ConnectProps): Promise 0 - ? after(deadline, () => { - expired = new ConnectTimeout(limit); - resolve(); - }) - : () => {}; + const disarm = !limit.isZero() + ? after(limit, () => { + expired = new ConnectTimeout(limit); + resolve(); + }) + : () => {}; const tokens = props.tokens ?? []; const pending = connectInner(url, tokens, props, abort); @@ -433,7 +430,7 @@ async function connectInner( const websocketUrl = fallbackDial?.url ?? url; const server = websocketKey(websocketUrl); const headstart = - !webtransport || websocketWon.has(server) ? 0 : (props.websocket?.delay ?? DEFAULT_WEBSOCKET_DELAY_MS); + !webtransport || websocketWon.has(server) ? Duration.ZERO : (props.websocket?.delay ?? DEFAULT_WEBSOCKET_DELAY); const maxStreams = BigInt(props.websocket?.maxStreams ?? DEFAULT_MAX_STREAMS); const websocket = props.websocket?.enabled !== false @@ -708,7 +705,7 @@ async function hedgeWebTransport( const first = dialWebTransport(target, cancel); // The first dial opening, failing, or being cancelled settles this before the delay does. - const hedge = await timeout(Nano.fromMilli(WEBTRANSPORT_HEDGE), first).then( + const hedge = await timeout(WEBTRANSPORT_HEDGE, first).then( () => false, (err: unknown) => err instanceof Elapsed, ); @@ -863,16 +860,16 @@ async function fetchFingerprint(url: URL, cancel: Promise): Promise, options: QmuxOptions, ): Promise { - const timer = sleep(Nano.fromMilli(Milli(delay))); + const timer = sleep(delay); const active = await Promise.race([cancel, timer.then(() => true)]); if (!active) return undefined; - for (let wait = WEBSOCKET_REDIAL; ; wait = Milli(wait * 2)) { + for (let wait = WEBSOCKET_REDIAL; ; wait = wait.mul(2)) { const quic = new Session(url, options); // Wait for the WebSocket to connect, for the cancel promise to resolve, or for the @@ -885,12 +882,12 @@ async function connectWebSocket( const outcome = await race([ quic.ready.then(() => "open" as const), cancel, - sleep(Nano.fromMilli(wait), { signal: disarm.signal }).then(() => "redial" as const), + sleep(wait, { signal: disarm.signal }).then(() => "redial" as const), ]); if (outcome === "open") return quic; quic.close(); if (outcome !== "redial") return undefined; - console.debug(show(parse(url)), `WebSocket not open after ${wait}ms; dialing again`); + console.debug(show(parse(url)), `WebSocket not open after ${wait}; dialing again`); } finally { disarm.abort(); } diff --git a/js/net/src/connection/forward.test.ts b/js/net/src/connection/forward.test.ts index 70d9eab1d16..1c4c8d98678 100644 --- a/js/net/src/connection/forward.test.ts +++ b/js/net/src/connection/forward.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, expect, jest, spyOn, test } from "bun:test"; -import { type Installed, Manual, Milli, Nano } from "@moq/clock"; +import { Duration, type Installed, Manual } from "@moq/clock"; import * as Announce from "../announced.ts"; import { AuthSession } from "../auth_session.ts"; import { type Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "../broadcast.ts"; @@ -30,12 +30,12 @@ afterEach(() => { /** Drain the reactive work without moving time. */ function settle(): Promise { - return clock.advance(Nano.zero); + return clock.advance(Duration.ZERO); } /** Move time forward, draining the reactive work at each deadline on the way. */ function advance(ms: number): Promise { - return clock.advance(Nano.fromMilli(Milli(ms))); + return clock.advance(Duration.millis(ms)); } /** diff --git a/js/net/src/connection/forward.ts b/js/net/src/connection/forward.ts index 7f290064a14..bff0c118465 100644 --- a/js/net/src/connection/forward.ts +++ b/js/net/src/connection/forward.ts @@ -4,7 +4,7 @@ * @module */ -import { Milli, Nano } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { type Dispose, race } from "@moq/signals"; import type * as Announce from "../announced.ts"; import { routesEqual, type WireRoute } from "../hop.ts"; @@ -20,7 +20,7 @@ export const DISCOVERY_REMOVED = "the discovery option is removed: a session asks only about watched prefixes and turns blind if the relay refuses"; /** How long an announce request outlives its last watcher, so a watcher torn down and rebuilt reuses it. */ -const LINGER = Milli(2000); +const LINGER = Duration.millis(2000); /** One announce request open on the session, and the routes it currently reports. */ interface Interest { @@ -240,7 +240,7 @@ export function forwardAnnounced(conn: Established, origin: OriginProducer): voi return; } interest.linger?.(); - interest.linger = after(Nano.fromMilli(LINGER), () => { + interest.linger = after(LINGER, () => { // Forgotten now rather than once its stream winds down, so a watch arriving // meanwhile opens a fresh request instead of reviving this one. interests.delete(prefix); diff --git a/js/net/src/connection/goaway.test.ts b/js/net/src/connection/goaway.test.ts index c0dd7191132..1899d8f17e5 100644 --- a/js/net/src/connection/goaway.test.ts +++ b/js/net/src/connection/goaway.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { RefusedRedirect } from "../error.ts"; import { dialed, handover, pinnedTransport, type Redirect, target } from "./goaway.ts"; @@ -88,9 +88,9 @@ test("a certificate pin holds only the WebTransport session that used it", () => }); test("the handover is the cap, lowered only by a positive peer deadline", () => { - const cap = Milli(10_000); + const cap = Duration.millis(10_000); expect(handover(cap)).toBe(cap); - expect(handover(cap, Milli(0))).toBe(cap); - expect(handover(cap, Milli(3_000))).toBe(Milli(3_000)); - expect(handover(cap, Milli(3_600_000))).toBe(cap); + expect(handover(cap, Duration.millis(0))).toBe(cap); + expect(handover(cap, Duration.millis(3_000))).toEqual(Duration.millis(3_000)); + expect(handover(cap, Duration.millis(3_600_000))).toBe(cap); }); diff --git a/js/net/src/connection/goaway.ts b/js/net/src/connection/goaway.ts index 8c4f062ed4d..b08f0fc27f5 100644 --- a/js/net/src/connection/goaway.ts +++ b/js/net/src/connection/goaway.ts @@ -5,7 +5,7 @@ * @module */ -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { RefusedRedirect } from "../error.ts"; import { type Endpoint, isLocal, parse, sameHost } from "./endpoint.ts"; import type { Transport } from "./transport.ts"; @@ -15,7 +15,7 @@ export interface Drain { /** Where to reconnect, including any credentials it needs. Empty means the same endpoint. */ readonly uri: string; /** When the peer force-closes the session. Undefined when the wire carried none. */ - readonly timeout?: Milli; + readonly timeout?: Duration; } /** @@ -42,11 +42,11 @@ export interface GoawayProps { * (default: 10000ms). A cap: a shorter deadline from the peer wins, a longer one does not * extend it. */ - handover?: Milli; + handover?: Duration; } /** The handover cap when the caller names none. */ -export const DEFAULT_HANDOVER = Milli(10_000); +export const DEFAULT_HANDOVER = Duration.millis(10_000); /** * How long a drained session may keep serving: the cap, lowered to the peer's deadline when @@ -54,8 +54,8 @@ export const DEFAULT_HANDOVER = Milli(10_000); * * @internal */ -export function handover(cap: Milli, timeout?: Milli): Milli { - return timeout !== undefined && timeout > 0 ? Milli(Math.min(cap, timeout)) : cap; +export function handover(cap: Duration, timeout?: Duration): Duration { + return timeout !== undefined && !timeout.isZero() ? cap.min(timeout) : cap; } /** diff --git a/js/net/src/connection/handshake.ts b/js/net/src/connection/handshake.ts index 4255dae080c..c6ef948f1bc 100644 --- a/js/net/src/connection/handshake.ts +++ b/js/net/src/connection/handshake.ts @@ -1,4 +1,4 @@ -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { closeReason, ProtocolViolation, SessionCode, StreamError } from "../error.ts"; import { type Hop, randomHop } from "../hop.ts"; import * as Ietf from "../ietf/index.ts"; @@ -8,7 +8,7 @@ import { acceptBudget, Reader, Stream, UnexpectedEnd, Writer } from "../stream.t import * as Extensions from "./extensions.ts"; /** Default bound on a connection attempt, including its SETUP exchange. @internal */ -export const DEFAULT_TIMEOUT = Milli(30_000); +export const DEFAULT_TIMEOUT = Duration.millis(30_000); /** * Draft-18+ SETUP exchange. Each side opens a uni stream, writes its Setup diff --git a/js/net/src/connection/migrate.test.ts b/js/net/src/connection/migrate.test.ts index eede71cf3e2..8f3b238de2a 100644 --- a/js/net/src/connection/migrate.test.ts +++ b/js/net/src/connection/migrate.test.ts @@ -1,5 +1,5 @@ import { afterEach, expect, spyOn, test } from "bun:test"; -import { Instant, Manual, Milli, Nano, now, yieldNow } from "@moq/clock"; +import { Duration, Manual, now, yieldNow } from "@moq/clock"; import { RefusedRedirect } from "../error.ts"; import * as Lite from "../lite/index.ts"; import { createMockTransportPair } from "../mock.ts"; @@ -23,10 +23,10 @@ async function settle() { // Polls until `pred` holds, so a regression fails the test instead of hanging it. async function waitUntil(pred: () => boolean, ms = 2000): Promise { - const deadline = Instant.add(now(), Nano.fromMilli(Milli(ms))); + const deadline = now().add(Duration.millis(ms)); for (;;) { if (pred()) return; - if (now() > deadline) throw new Error("timed out waiting for condition"); + if (now().gt(deadline)) throw new Error("timed out waiting for condition"); await settle(); } } @@ -73,7 +73,7 @@ async function goaway(server: WebTransport, uri: string): Promise { const url = new URL("https://relay.example/room"); // Short enough to watch, long enough that a handover visibly overlaps the replacement. -const handover = Milli(200); +const handover = Duration.millis(200); test("an empty GOAWAY migrates the follower to the replacement session", async () => { const clock = new Manual(); @@ -89,7 +89,7 @@ test("an empty GOAWAY migrates the follower to the replacement session", async ( consume, goaway: { handover }, // A session younger than this counts as redirected immediately and backs off first. - delay: { initial: Milli(1) }, + delay: { initial: Duration.millis(1) }, }); const watched = consume.follow(Path.from("cam")); @@ -135,7 +135,7 @@ test("a GOAWAY without a timeout hands over at the configured cap", async () => url, websocket: { enabled: false }, goaway: { handover }, - delay: { initial: Milli(1) }, + delay: { initial: Duration.millis(1) }, }); try { @@ -149,7 +149,7 @@ test("a GOAWAY without a timeout hands over at the configured cap", async () => // Lite carries no deadline, which must read as "the cap", never as a zero handover. await elapse(clock, () => drained.closed); - expect(Nano.toMilli(Instant.durationSince(clock.now(), sent))).toBeGreaterThanOrEqual(handover); + expect(clock.now().since(sent).ge(handover)).toBe(true); } finally { reload.close(); installed.close(); @@ -162,7 +162,7 @@ test("a refused redirect ends the connection instead of reconnecting", async () const clock = new Manual(); const installed = clock.install(); const { dials } = fleet(); - const reload = new Reload({ url, websocket: { enabled: false }, delay: { initial: Milli(1) } }); + const reload = new Reload({ url, websocket: { enabled: false }, delay: { initial: Duration.millis(1) } }); try { await waitUntil(() => reload.status.peek() === "connected"); @@ -176,7 +176,7 @@ test("a refused redirect ends the connection instead of reconnecting", async () await waitUntil(() => drained.closed); // Nothing redials: not the original URL, not anything else. - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); expect(dials.length, uri).toBe(1); } finally { reload.close(); @@ -192,7 +192,7 @@ test("a certificate pin refuses a redirect to another host even under follow", a websocket: { enabled: false }, webtransport: { serverCertificateHashes: [{ value: "00".repeat(32) }] }, goaway: { redirect: "follow" }, - delay: { initial: Milli(1) }, + delay: { initial: Duration.millis(1) }, }); try { @@ -297,7 +297,7 @@ test("the connection's tokens ride every session across a GOAWAY", async () => { const until = async (done: () => boolean) => { for (let i = 0; i < 100 && !done(); i++) { await yieldNow(); - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); } expect(done()).toBe(true); }; @@ -333,7 +333,7 @@ test("the connection's tokens ride every session across a GOAWAY", async () => { websocket: { enabled: false }, versions: [Lite.ALPN_07_WIP], goaway: { handover }, - delay: { initial: Milli(1) }, + delay: { initial: Duration.millis(1) }, }); try { const token = await reload.auth.add("token"); @@ -368,15 +368,15 @@ test("the connection's tokens ride every session across a GOAWAY", async () => { }); // How long each session on the bouncing fleet lives before its peer redirects it away. -const life = Milli(40); +const life = Duration.millis(40); /** Fire `clock` timer by timer until `pred` holds, and return the time that took. */ -async function elapse(clock: Manual, pred: () => boolean): Promise { +async function elapse(clock: Manual, pred: () => boolean): Promise { const start = clock.now(); for (;;) { // Let the mock sessions run before deciding that time has to pass. for (let i = 0; i < 10 && !pred(); i++) await settle(); - if (pred()) return Nano.toMilli(Instant.durationSince(clock.now(), start)); + if (pred()) return clock.now().since(start).asMillis(); await clock.fire(); } } @@ -404,7 +404,7 @@ async function bounce( next.password = `secret-${hop}`; } const other = next.href; - await clock.advance(Nano.fromMilli(life)); + await clock.advance(life); await goaway(dial.server, other); await waitUntil(() => reload.redirect.peek()?.href === other); return other; @@ -423,7 +423,12 @@ test.each([ websocket: { enabled: false }, goaway: { handover }, // Every session outlives the healthy bar, so the immediate-redirect damping never applies. - delay: { initial: Milli(10), multiplier: 4, max: Milli(1000), healthy: Milli(10) }, + delay: { + initial: Duration.millis(10), + multiplier: 4, + max: Duration.millis(1000), + healthy: Duration.millis(10), + }, }); try { @@ -456,12 +461,12 @@ test("redirect endpoint keys omit userinfo without changing the dial URL", async url: from, websocket: { enabled: false }, goaway: { handover }, - delay: { initial: Milli(10) }, + delay: { initial: Duration.millis(10) }, }); try { await waitUntil(() => reload.status.peek() === "connected"); - await clock.advance(Nano.fromMilli(life)); + await clock.advance(life); await goaway(dials[0]?.server as WebTransport, to.href); await elapse(clock, () => dials.length === 2); expect(moves.mock.calls).toEqual([["https://relay.example/room", "https://relay.example:5443/room"]]); @@ -483,7 +488,13 @@ test("a redirect loop stops at the retry window", async () => { url, websocket: { enabled: false }, goaway: { handover }, - delay: { initial: Milli(10), multiplier: 4, max: Milli(1000), healthy: Milli(10), timeout: Milli(150) }, + delay: { + initial: Duration.millis(10), + multiplier: 4, + max: Duration.millis(1000), + healthy: Duration.millis(10), + timeout: Duration.millis(150), + }, }); try { @@ -509,13 +520,13 @@ test("a loop no faster than the capped delay migrates without backing off", asyn websocket: { enabled: false }, goaway: { handover }, // Each session lives exactly the cap, so it already redials no faster than the backoff would. - delay: { initial: Milli(10), max: life, healthy: Milli(10) }, + delay: { initial: Duration.millis(10), max: life, healthy: Duration.millis(10) }, }); try { for (let hop = 0; hop < 6; hop++) { await bounce(clock, reload, dials, hop); - expect(await elapse(clock, () => dials.length === hop + 2), `hop ${hop}`).toBe(Milli(0)); + expect(await elapse(clock, () => dials.length === hop + 2), `hop ${hop}`).toBe(0); } } finally { reload.close(); @@ -532,15 +543,15 @@ test("a one-way rolling restart migrates without backing off", async () => { websocket: { enabled: false }, goaway: { handover }, // Long enough that any backoff would be visible. - delay: { initial: Milli(1000) }, + delay: { initial: Duration.millis(1000) }, }); try { await waitUntil(() => reload.status.peek() === "connected"); // Outlive the default healthy bar (1000ms) so only loop detection could slow this down. - await clock.advance(Nano.fromMilli(Milli(1100))); + await clock.advance(Duration.millis(1100)); await goaway(dials[0]?.server as WebTransport, moved.href); - expect(await elapse(clock, () => dials.length === 2)).toBe(Milli(0)); + expect(await elapse(clock, () => dials.length === 2)).toBe(0); } finally { reload.close(); installed.close(); @@ -556,16 +567,16 @@ test("repeated GOAWAYs back to the same place are restarts, not a loop", async ( websocket: { enabled: false }, goaway: { handover }, // Long enough that any backoff would be visible. - delay: { initial: Milli(300), healthy: Milli(300) }, + delay: { initial: Duration.millis(300), healthy: Duration.millis(300) }, }); try { for (let i = 1; i <= 3; i++) { await waitUntil(() => dials.length === i && reload.status.peek() === "connected"); // Outlive the healthy bar so only loop detection could slow this down. - await clock.advance(Nano.fromMilli(Milli(350))); + await clock.advance(Duration.millis(350)); await goaway(dials[i - 1]?.server as WebTransport, ""); - expect(await elapse(clock, () => dials.length === i + 1), `restart ${i}`).toBe(Milli(0)); + expect(await elapse(clock, () => dials.length === i + 1), `restart ${i}`).toBe(0); } } finally { reload.close(); @@ -584,7 +595,12 @@ test("a peer restarting through immediate GOAWAYs escalates the backoff but neve websocket: { enabled: false }, goaway: { handover }, // The waits add up to far more than the window, which a restart restarts after each one. - delay: { initial: Milli(10), multiplier: 2, max: Milli(1000), timeout: Milli(25) }, + delay: { + initial: Duration.millis(10), + multiplier: 2, + max: Duration.millis(1000), + timeout: Duration.millis(25), + }, }); try { diff --git a/js/net/src/connection/pool.test.ts b/js/net/src/connection/pool.test.ts index 101114ca703..6d3c9983c25 100644 --- a/js/net/src/connection/pool.test.ts +++ b/js/net/src/connection/pool.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, expect, test } from "bun:test"; -import { type Installed, Manual, Milli, Nano } from "@moq/clock"; +import { Duration, type Installed, Manual } from "@moq/clock"; import { Signal } from "@moq/signals"; import { SessionCode, SessionError } from "../error.ts"; import * as Lite from "../lite/index.ts"; @@ -27,10 +27,10 @@ let clock: Manual; let installed: Installed; function advance(ms = 0): Promise { - return clock.advance(Nano.fromMilli(Milli(ms))); + return clock.advance(Duration.millis(ms)); } -const linger = Milli(2000); +const linger = 2000; const original = globalThis.WebTransport; const originalWebSocket = globalThis.WebSocket; @@ -301,8 +301,8 @@ test("connection-specific options infer a private loop and origin", async () => const options = [ { webtransport: { congestionControl: "throughput" as const } }, { websocket: { enabled: false } }, - { delay: { timeout: Milli(0) } }, - { timeout: Milli(10_000) }, + { delay: { timeout: Duration.millis(0) } }, + { timeout: Duration.millis(10_000) }, { publish: origin.consume() }, { consume: origin }, ]; @@ -336,8 +336,8 @@ test("explicit share: true refuses connection-specific options", () => { /share: false/, ); expect(() => new Connection({ share: true, websocket: { enabled: false } })).toThrow(/share: false/); - expect(() => new Connection({ share: true, delay: { timeout: Milli(0) } })).toThrow(/share: false/); - expect(() => new Connection({ share: true, timeout: Milli(10_000) })).toThrow(/share: false/); + expect(() => new Connection({ share: true, delay: { timeout: Duration.millis(0) } })).toThrow(/share: false/); + expect(() => new Connection({ share: true, timeout: Duration.millis(10_000) })).toThrow(/share: false/); } finally { origin.close(); } @@ -438,7 +438,7 @@ test("exhausted retries then a new URL recovers a private handle", async () => { url, share: false, websocket: { enabled: false }, - delay: { initial: Milli(1), multiplier: 1, max: Milli(1), timeout: Milli(1) }, + delay: { initial: Duration.millis(1), multiplier: 1, max: Duration.millis(1), timeout: Duration.millis(1) }, }); try { await advance(2); @@ -467,7 +467,7 @@ test("a private partial delay keeps the unlimited retry timeout", async () => { url, share: false, websocket: { enabled: false }, - delay: { initial: Milli(1000), multiplier: 1, max: Milli(1000) }, + delay: { initial: Duration.millis(1000), multiplier: 1, max: Duration.millis(1000) }, }); try { await advance(60_000); @@ -845,8 +845,8 @@ test("a private handle's timeout bounds each attempt", async () => { url, share: false, websocket: { enabled: false }, - timeout: Milli(50), - delay: { initial: Milli(10), multiplier: 1, max: Milli(10) }, + timeout: Duration.millis(50), + delay: { initial: Duration.millis(10), multiplier: 1, max: Duration.millis(10) }, }); try { // Each hung dial is cut at 50 ms and redialed after the backoff; the default 30 s @@ -857,7 +857,3 @@ test("a private handle's timeout bounds each attempt", async () => { handle.close(); } }); - -test("an invalid timeout is refused when a private handle is built", () => { - expect(() => new Connection({ url, share: false, timeout: Number.NaN as Milli })).toThrow(RangeError); -}); diff --git a/js/net/src/connection/pool.ts b/js/net/src/connection/pool.ts index 4ca50528787..5165448925b 100644 --- a/js/net/src/connection/pool.ts +++ b/js/net/src/connection/pool.ts @@ -4,7 +4,7 @@ * @module */ -import { Milli, Nano } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { Effect, type GetPromise, type Getter, Once, Signal } from "@moq/signals"; import type * as Announce from "../announce.ts"; import { Producer as AnnounceProducer, list, type Routes } from "../announced.ts"; @@ -36,7 +36,7 @@ import type { Probe as ProbeType, Stats as StatsType } from "./stats.ts"; import type { Transport as TransportType } from "./transport.ts"; /** How long an unreferenced shared connection lingers before it actually closes. */ -const LINGER_MS = Milli(2000); +const LINGER = Duration.millis(2000); /** Options for {@link Connection}. */ export interface ConnectionProps { @@ -85,7 +85,7 @@ export interface ConnectionProps { * 30000ms; `0` waits forever). An attempt that outlives it is retried like any other * failure. The same bound as the `timeout` option of {@link Connection.connect}. */ - timeout?: Milli; + timeout?: Duration; /** * How to react to the relay's GOAWAY; an unset field uses its default. Every connection @@ -249,8 +249,6 @@ export class Connection { // A plain list is checked and copied now, so a bad name throws here and mutating the array // later changes nothing. A live list is checked as it changes, failing on `error`. const fixed = normalizeVersions({ ...props, versions: Array.isArray(given) ? given : undefined }); - // Likewise a bad timeout, before anything below exists to leak. - if (props?.timeout !== undefined) Milli(props.timeout); refuse(props); this.#signals = new Effect(); @@ -589,7 +587,7 @@ function acquire(url: string, versions?: readonly string[]): Entry & { release: // Don't hold a Node process open for a connection nobody is using. taken.timer = after( - Nano.fromMilli(LINGER_MS), + LINGER, () => { if (pool.get(taken.key) === taken) pool.delete(taken.key); taken.connection.close(); diff --git a/js/net/src/connection/reload.test.ts b/js/net/src/connection/reload.test.ts index fb144cd4a93..f807edf2a47 100644 --- a/js/net/src/connection/reload.test.ts +++ b/js/net/src/connection/reload.test.ts @@ -1,5 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { Instant, Manual, Milli, Nano, now, yieldNow } from "@moq/clock"; +import { Duration, Manual, now, yieldNow } from "@moq/clock"; import { Effect, type Getter, Signal } from "@moq/signals"; import * as Announce from "../announced.ts"; import { Viewers } from "../bandwidth.ts"; @@ -153,7 +153,12 @@ test("a peer that severs immediately keeps escalating the backoff", async () => enabled: true, url, websocket: { enabled: false }, - delay: { initial: Milli(1000), multiplier: 2, max: Milli(1000), timeout: Milli(1) }, + delay: { + initial: Duration.millis(1000), + multiplier: 2, + max: Duration.millis(1000), + timeout: Duration.millis(1), + }, }); try { await clock.drive(waitFor(reload.error, (error) => error !== undefined)); @@ -195,10 +200,10 @@ test("an explicitly undefined delay field falls back to its default", async () = enabled: true, url, websocket: { enabled: false }, - delay: { initial: undefined, multiplier: undefined, max: undefined, timeout: Milli(0) }, + delay: { initial: undefined, multiplier: undefined, max: undefined, timeout: Duration.millis(0) }, }); try { - await clock.advance(Nano.fromMilli(Milli(100))); + await clock.advance(Duration.millis(100)); // The default initial delay is 1000ms, so the first retry is still pending. expect(dials).toBe(1); } finally { @@ -225,8 +230,8 @@ function present(routes: Announce.Routes): Getter> { // Polls until `pred` holds, so a regression fails the test instead of hanging it. async function waitUntil(pred: () => boolean): Promise { - const deadline = Instant.add(now(), Nano.fromMilli(Milli(1000))); - while (now() <= deadline) { + const deadline = now().add(Duration.millis(1000)); + while (now().le(deadline)) { if (pred()) return; await settle(); } @@ -258,7 +263,7 @@ test("a follower follows the reconnect on the same handle", async () => { enabled: true, url, websocket: { enabled: false }, - delay: { initial: Milli(10), multiplier: 1, max: Milli(10) }, + delay: { initial: Duration.millis(10), multiplier: 1, max: Duration.millis(10) }, consume: clientOrigin, }); const watched = clientOrigin.follow(Path.from("late")); @@ -297,7 +302,7 @@ test("an ended auth handle gives up instead of retrying", async () => { const until = async (done: () => boolean) => { for (let i = 0; i < 100 && !done(); i++) { await yieldNow(); - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); } expect(done()).toBe(true); }; @@ -307,7 +312,7 @@ test("an ended auth handle gives up instead of retrying", async () => { enabled: true, url, websocket: { enabled: false }, - delay: { initial: Milli(1), multiplier: 2, max: Milli(1), timeout: Milli(0) }, + delay: { initial: Duration.millis(1), multiplier: 2, max: Duration.millis(1), timeout: Duration.millis(0) }, }); const warned = spyOn(console, "warn").mockImplementation(() => {}); try { @@ -351,7 +356,7 @@ test("a page hide after give-up does not retry the refused URL", async () => { enabled: true, url, websocket: { enabled: false }, - delay: { initial: Milli(1), multiplier: 1, max: Milli(1), timeout: Milli(0) }, + delay: { initial: Duration.millis(1), multiplier: 1, max: Duration.millis(1), timeout: Duration.millis(0) }, }); try { @@ -396,7 +401,7 @@ for (const code of [SessionCode.Unauthorized, SessionCode.MalformedAuthToken, Se enabled: true, url, websocket: { enabled: false }, - delay: { initial: Milli(1), multiplier: 2, max: Milli(1), timeout: Milli(0) }, + delay: { initial: Duration.millis(1), multiplier: 2, max: Duration.millis(1), timeout: Duration.millis(0) }, }); const watch = new Effect(); watch.run((effect) => { @@ -465,7 +470,7 @@ test("a refused credential replaced since its dial redials with the new one", as versions: ["moq-lite-06"], websocket: { enabled: false }, tokens, - delay: { initial: Milli(1), multiplier: 2, max: Milli(1), timeout: Milli(0) }, + delay: { initial: Duration.millis(1), multiplier: 2, max: Duration.millis(1), timeout: Duration.millis(0) }, }); try { await clock.drive(waitFor(reload.established, (established) => established !== undefined)); @@ -493,7 +498,7 @@ test("new tokens redial a URL that stopped on refusing the old ones", async () = versions: ["moq-lite-06"], websocket: { enabled: false }, tokens, - delay: { initial: Milli(1), multiplier: 2, max: Milli(1), timeout: Milli(0) }, + delay: { initial: Duration.millis(1), multiplier: 2, max: Duration.millis(1), timeout: Duration.millis(0) }, }); try { await clock.drive(waitFor(reload.error, (error) => error !== undefined)); @@ -536,7 +541,7 @@ test("an unauthorized session close during setup stops retrying", async () => { url, websocket: { enabled: false }, // Unlimited retries prove that `closed` settles only because the rejection is terminal. - delay: { initial: Milli(1), multiplier: 1, max: Milli(1), timeout: Milli(0) }, + delay: { initial: Duration.millis(1), multiplier: 1, max: Duration.millis(1), timeout: Duration.millis(0) }, }); try { @@ -587,7 +592,7 @@ test("a setup stream reset is not mistaken for an unauthorized session", async ( websocket: { enabled: false }, // Unlimited retries, so a second attempt can only happen because the first failure // was treated as retryable rather than terminal. - delay: { initial: Milli(1), multiplier: 1, max: Milli(1), timeout: Milli(0) }, + delay: { initial: Duration.millis(1), multiplier: 1, max: Duration.millis(1), timeout: Duration.millis(0) }, }); try { @@ -631,7 +636,7 @@ test("origins span reconnects: local re-announces, remote re-populates", async ( enabled: true, url, websocket: { enabled: false }, - delay: { initial: Milli(10), multiplier: 1, max: Milli(10) }, + delay: { initial: Duration.millis(10), multiplier: 1, max: Duration.millis(10) }, publish: publishOrigin.consume(), consume: subscribeOrigin, }); @@ -703,35 +708,35 @@ const teardowns = { "release of the last handle": { drains: true, goaway: false, - linger: Milli(2000), + linger: Duration.millis(2000), hide: false, end: (handle: Connection) => handle.close(), }, disable: { drains: true, goaway: false, - linger: Milli(2000), + linger: Duration.millis(2000), hide: false, end: (handle: Connection) => handle.enabled.set(false), }, "release after a GOAWAY": { drains: true, goaway: true, - linger: Milli(0), + linger: Duration.millis(0), hide: false, end: (handle: Connection) => handle.close(), }, pagehide: { drains: false, goaway: false, - linger: Milli(0), + linger: Duration.millis(0), hide: false, end: (_: Connection, win: EventTarget) => win.dispatchEvent(new Event("pagehide")), }, "pagehide during a release's drain": { drains: false, goaway: false, - linger: Milli(2000), + linger: Duration.millis(2000), hide: true, end: (handle: Connection) => handle.close(), }, @@ -769,7 +774,9 @@ for (const [name, teardown] of Object.entries(teardowns)) { // GOAWAY tuning takes a private loop; the rest share the pool, closing when the linger ends. const handle = new Connection( - teardown.goaway ? { url, delay: { initial: Milli(0) }, goaway: { handover: Milli(60_000) } } : { url }, + teardown.goaway + ? { url, delay: { initial: Duration.millis(0) }, goaway: { handover: Duration.millis(60_000) } } + : { url }, ); await waitUntil(() => handle.origin.peek() !== undefined); const origin = handle.origin.peek(); @@ -802,14 +809,14 @@ for (const [name, teardown] of Object.entries(teardowns)) { producer.finish(); producer.close(); teardown.end(handle, win); - await clock.advance(Nano.fromMilli(teardown.linger)); + await clock.advance(teardown.linger); if (teardown.hide) win.dispatchEvent(new Event("pagehide")); if (teardown.drains) { expect(await (await track.nextGroup())?.readString()).toBe("last"); await fin.hold?.reached; // Just short of the close deadline, the session still waits for the FIN. - await clock.advance(Nano.fromMilli(Milli(999))); + await clock.advance(Duration.millis(999)); expect(fin.closed).toBe(false); fin.hold?.release(); } @@ -833,7 +840,7 @@ for (const [name, teardown] of Object.entries(teardowns)) { // active session at a time, so the closing one must give it up for the replacement to dial. // The page going away mid-drain aborts it too, since nothing would run to finish it. const drainEnds = { - "the close deadline": (clock: Manual, _: EventTarget) => clock.advance(Nano.fromMilli(Milli(1000))), + "the close deadline": (clock: Manual, _: EventTarget) => clock.advance(Duration.millis(1000)), pagehide: async (_: Manual, win: EventTarget) => { win.dispatchEvent(new Event("pagehide")); }, @@ -928,8 +935,8 @@ test("a retired GOAWAY predecessor still closes by its handover cap", async () = url: new URL("https://example.com/"), websocket: { enabled: false }, publish: origin.consume(), - delay: { initial: Milli(0) }, - goaway: { handover: Milli(100) }, + delay: { initial: Duration.millis(0) }, + goaway: { handover: Duration.millis(100) }, }); await waitUntil(() => dials.length > 0); @@ -947,11 +954,11 @@ test("a retired GOAWAY predecessor still closes by its handover cap", async () = await new Lite.Goaway("").encode(stream.writer, Lite.Version.DRAFT_06); await waitUntil(() => dials.length === 2 && reload.status.peek() === "connected"); - await clock.advance(Nano.fromMilli(Milli(90))); + await clock.advance(Duration.millis(90)); reload.close(); - await clock.advance(Nano.fromMilli(Milli(9))); + await clock.advance(Duration.millis(9)); expect(first.closed).toBe(false); - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); await waitUntil(() => first.closed); } finally { track.close(); @@ -1025,7 +1032,7 @@ test("closing the loop keeps the tokens until the session drains", async () => { expect(await (await track.nextGroup())?.readString()).toBe("last"); await fin.hold?.reached; - await clock.advance(Nano.fromMilli(Milli(999))); + await clock.advance(Duration.millis(999)); expect(fin.closed).toBe(false); fin.hold?.release(); await waitUntil(() => fin.closed); @@ -1119,7 +1126,7 @@ test("a watcher syncs with the server's initial set, and again after a reconnect enabled: true, url, websocket: { enabled: false }, - delay: { initial: Milli(10), multiplier: 1, max: Milli(10) }, + delay: { initial: Duration.millis(10), multiplier: 1, max: Duration.millis(10) }, }; const reload = viaOrigin ? new Reload({ ...props, consume: clientOrigin }) : undefined; const connection = viaOrigin ? undefined : new Connection({ ...props, share: false }); @@ -1217,7 +1224,7 @@ async function elapse(clock: Manual, pred: () => boolean): Promise { const start = clock.now(); for (;;) { for (let i = 0; i < 3 && !pred(); i++) await settle(); - if (pred()) return Nano.toMilli(Instant.durationSince(clock.now(), start)); + if (pred()) return clock.now().since(start).asMillis(); await clock.fire(); } } @@ -1263,8 +1270,8 @@ test("an attempt that outlives the connect timeout is retried after the backoff" const reload = new Reload({ url, websocket: { enabled: false }, - timeout: Milli(50), - delay: { initial: Milli(20) }, + timeout: Duration.millis(50), + delay: { initial: Duration.millis(20) }, }); const unsubscribe = reload.status.subscribe((status) => statuses.push(status)); try { @@ -1290,9 +1297,19 @@ test("an attempt that outlives the connect timeout is retried after the backoff" // moq-tokio's does, and no attempt starts once it has passed. const windows: [string, ReloadDelay, number, number][] = [ // Dials at 0, 40, and 80; the last runs past the window and gives up when it fails. - ["an attempt under way finishes past the window", { initial: Milli(10), timeout: Milli(100) }, 110, 3], + [ + "an attempt under way finishes past the window", + { initial: Duration.millis(10), timeout: Duration.millis(100) }, + 110, + 3, + ], // The first failure at 30 ms leaves 30 ms, less than the 50 ms wait, so it gives up at the deadline. - ["a wait that reaches the deadline gives up there", { initial: Milli(50), timeout: Milli(60) }, 60, 1], + [ + "a wait that reaches the deadline gives up there", + { initial: Duration.millis(50), timeout: Duration.millis(60) }, + 60, + 1, + ], ]; for (const [name, delay, gaveUp, dials] of windows) { test(`retry window: ${name}`, async () => { @@ -1306,8 +1323,8 @@ for (const [name, delay, gaveUp, dials] of windows) { const reload = new Reload({ url, websocket: { enabled: false }, - timeout: Milli(30), - delay: { multiplier: 1, max: Milli(1000), ...delay }, + timeout: Duration.millis(30), + delay: { multiplier: 1, max: Duration.millis(1000), ...delay }, }); try { await waitUntil(() => plan.dials() === 1); @@ -1325,26 +1342,18 @@ for (const [name, delay, gaveUp, dials] of windows) { }); } -test("an invalid timeout is refused when the loop is built, not by every attempt", () => { - for (const timeout of [-1, Number.NaN, Number.POSITIVE_INFINITY]) { - expect(() => new Reload({ url: new URL("https://example.com/"), timeout: timeout as Milli })).toThrow( - RangeError, - ); - } -}); - // Each session lives 100 ms, so the backoff between them shows how `healthy` scores its end and // how `max` caps the delay, matching moq-tokio's `connect.backoff`. const backoffs: [string, ReloadDelay, number[]][] = [ // Past `initial` but short of the default bar, so each end is a failed attempt. ["a session short of the default healthy bar escalates", {}, [10, 20, 40]], - ["a session past the healthy bar resets", { healthy: Milli(50) }, [10, 10, 10]], + ["a session past the healthy bar resets", { healthy: Duration.millis(50) }, [10, 10, 10]], [ "a zero max leaves the delay uncapped", - { initial: Milli(1000), multiplier: 4, max: Milli(0) }, + { initial: Duration.millis(1000), multiplier: 4, max: Duration.millis(0) }, [1000, 4000, 16000], ], - ["a max below initial caps the first delay too", { max: Milli(5) }, [5, 5, 5]], + ["a max below initial caps the first delay too", { max: Duration.millis(5) }, [5, 5, 5]], ["a zero multiplier keeps the delay constant", { multiplier: 0 }, [10, 10, 10]], ["a fractional multiplier below 1 keeps the delay constant", { multiplier: 0.5 }, [10, 10, 10]], ]; @@ -1366,13 +1375,13 @@ for (const [name, delay, gaps] of backoffs) { const reload = new Reload({ url, websocket: { enabled: false }, - delay: { initial: Milli(10), multiplier: 2, max: Milli(1000), ...delay }, + delay: { initial: Duration.millis(10), multiplier: 2, max: Duration.millis(1000), ...delay }, }); try { const waited: number[] = []; for (let session = 0; session < gaps.length; session++) { await waitUntil(() => reload.status.peek() === "connected"); - await clock.advance(Nano.fromMilli(Milli(100))); + await clock.advance(Duration.millis(100)); (await servers[session])?.abort(); waited.push(await elapse(clock, () => servers.length === session + 2)); } @@ -1406,7 +1415,7 @@ test("backoff: an uncapped delay saturates instead of overflowing", async () => const reload = new Reload({ url, websocket: { enabled: false }, - delay: { initial: Milli(10), multiplier: 1e300, max: Milli(0) }, + delay: { initial: Duration.millis(10), multiplier: 1e300, max: Duration.millis(0) }, }); try { for (let session = 0; session < 2; session++) { @@ -1428,17 +1437,14 @@ test("backoff: an uncapped delay saturates instead of overflowing", async () => }); test("a delay field with no meaning is refused when the loop is built", () => { - const bad = [-1, Number.NaN, Number.POSITIVE_INFINITY] as Milli[]; const invalid: ReloadDelay[] = [ // Zero would count every session as healthy. - { healthy: Milli(0) }, - // Zero `max` is uncapped and zero `timeout` unlimited, so infinity has no spelling here. - ...bad.flatMap((value) => [{ initial: value }, { max: value }, { healthy: value }, { timeout: value }]), + { healthy: Duration.ZERO }, { multiplier: Number.NaN }, { multiplier: Number.POSITIVE_INFINITY }, ]; for (const delay of invalid) { - expect(() => new Reload({ url: new URL("https://example.com/"), delay }), JSON.stringify(delay)).toThrow( + expect(() => new Reload({ url: new URL("https://example.com/"), delay }), String(Object.keys(delay))).toThrow( RangeError, ); } diff --git a/js/net/src/connection/reload.ts b/js/net/src/connection/reload.ts index 6ca7327d64c..9c454653f4d 100644 --- a/js/net/src/connection/reload.ts +++ b/js/net/src/connection/reload.ts @@ -1,4 +1,4 @@ -import { Instant, Milli, Nano, now, sleep } from "@moq/clock"; +import { Duration, Instant, now, sleep } from "@moq/clock"; import { Derived, Effect, type GetPromise, type Getter, Once, Signal } from "@moq/signals"; import type * as Announce from "../announced.ts"; import { Handle as AuthHandle } from "../auth.ts"; @@ -45,13 +45,13 @@ function sameTokens(a: readonly string[], b: readonly string[]): boolean { */ export type ReloadDelay = { /** The delay before reconnecting (default: 1000ms; zero retries at once). */ - initial?: Milli; + initial?: Duration; /** The multiplier for the delay after each failure (default: 2; below 1 keeps it constant). */ multiplier?: number; /** The maximum delay (default: 5000ms; zero leaves it uncapped). A cap below `initial` caps the first delay too. */ - max?: Milli; + max?: Duration; /** * How long a session must stay up to count as healthy (default: 1000ms; must be positive). @@ -60,7 +60,7 @@ export type ReloadDelay = { * failed attempt, so a peer that accepts and then drops every session still escalates the * delay and exhausts the timeout. */ - healthy?: Milli; + healthy?: Duration; /** * Maximum total time to spend retrying the current URL before giving up @@ -70,7 +70,7 @@ export type ReloadDelay = { * longer than the window; {@link ConnectProps.timeout} bounds each attempt. A peer that * restarts, draining each session with a GOAWAY naming no URI, restarts it too. */ - timeout?: Milli; + timeout?: Duration; }; /** @@ -122,11 +122,11 @@ export type ReloadProps = Omit< * dispose the loop, and a new URL or a disable/re-enable starts another sequence. */ const DEFAULT_DELAY: Required = { - initial: Milli(1000), + initial: Duration.millis(1000), multiplier: 2, - max: Milli(5000), - healthy: Milli(1000), - timeout: Milli(0), + max: Duration.millis(5000), + healthy: Duration.millis(1000), + timeout: Duration.ZERO, }; /** @@ -137,21 +137,21 @@ const DEFAULT_DELAY: Required = { * optional value passes an explicit undefined, which a spread would take as the answer. */ function pacing(delay: ReloadDelay) { - const initial = Milli(delay.initial ?? DEFAULT_DELAY.initial); - const max = Milli(delay.max ?? DEFAULT_DELAY.max); - const cap = max > 0 ? max : undefined; + const initial = delay.initial ?? DEFAULT_DELAY.initial; + const max = delay.max ?? DEFAULT_DELAY.max; + const cap = max.isZero() ? undefined : max; const multiplier = delay.multiplier ?? DEFAULT_DELAY.multiplier; if (!Number.isFinite(multiplier)) throw new RangeError(`invalid delay.multiplier: ${multiplier}`); // Zero would count every session as healthy, resetting the retry window forever under a // peer that drops each one on sight. - const healthy = Milli(delay.healthy ?? DEFAULT_DELAY.healthy); - if (healthy === 0) throw new RangeError("delay.healthy must be positive"); - const timeout = Milli(delay.timeout ?? DEFAULT_DELAY.timeout); + const healthy = delay.healthy ?? DEFAULT_DELAY.healthy; + if (healthy.isZero()) throw new RangeError("delay.healthy must be positive"); + const timeout = delay.timeout ?? DEFAULT_DELAY.timeout; // A multiplier below 1 means no growth, not a delay that shrinks to nothing. const growth = Math.max(multiplier, 1); return { - initial: cap === undefined ? initial : Milli(Math.min(initial, cap)), + initial: cap === undefined ? initial : initial.min(cap), healthy, timeout, // How long a session must last to start a new run of redirects. One that outlived the @@ -159,16 +159,16 @@ function pacing(delay: ReloadDelay) { // healthy bar is the only rate the config names. settled: cap ?? healthy, /** The delay after one that waited `delay`. */ - next(delay: Milli): Milli { - const next = Math.min(delay * growth, cap ?? Number.POSITIVE_INFINITY); - // Saturates, as Rust's Duration does, rather than overflowing the wait in nanoseconds. - return Number.isFinite(next * 1_000_000) ? Milli(next) : delay; + next(delay: Duration): Duration { + const next = Math.min(delay.asNanos() * growth, cap?.asNanos() ?? Number.POSITIVE_INFINITY); + // Saturates, as Rust's Duration does, rather than overflowing the wait. + return Number.isFinite(next) ? Duration.nanos(next) : delay; }, }; } /** How often the send-rate estimate is sampled from the live transport while a reservation reads it. */ -const BANDWIDTH_POLL = Nano.fromMilli(Milli(100)); +const BANDWIDTH_POLL = Duration.millis(100); /** Current state of a reconnecting connection. */ export type ReloadStatus = "connecting" | "connected" | "disconnected"; @@ -262,7 +262,7 @@ export class Reload { websocket: WebSocketProps | undefined; /** The bound on each connection attempt. See {@link ConnectProps.timeout}. */ - readonly timeout?: Milli; + readonly timeout?: Duration; /** * The origin whose broadcasts are served, spanning reconnects (not reactive). @@ -334,8 +334,9 @@ export class Reload { // The current wait between attempts, doubling per failure, and when the retry window expires. // Both are undefined between sequences, so a later edit to `delay` applies to the next one. - #delay: Milli | undefined; - #deadline: number | undefined; + #delay: Duration | undefined; + // When the retry window expires, or null when it never does. + #deadline: Instant | null | undefined; // The URL the current retry sequence is for. Cleared when disabled, URL-less, or given // up, so the next attempt starts a fresh backoff window. @@ -376,7 +377,7 @@ export class Reload { this.webtransport = props?.webtransport; this.websocket = props?.websocket; // Validated here, like the versions, rather than by every attempt. - this.timeout = props?.timeout === undefined ? undefined : Milli(props.timeout); + this.timeout = props?.timeout; this.publish = props?.publish; this.consume = props?.consume; @@ -623,8 +624,8 @@ export class Reload { // backoff would allow, so it starts a new run: rolling restarts days apart // never add up to a loop. const { settled, healthy } = this.#pacing(); - const lived = Instant.durationSince(now(), connected); - if (lived >= Nano.fromMilli(settled)) this.#redirects.reset(); + const lived = now().since(connected); + if (lived.ge(settled)) this.#redirects.reset(); // Only a redirect this GOAWAY named is a move. An empty or ignored one reconnects // in place, even when that reruns the race a WebSocket fallback won. const from = destination(at); @@ -638,7 +639,7 @@ export class Reload { // migrates, but through the backoff, so two peers bouncing us between them // escalate to the capped delay. An empty URI is a peer restarting, which drains // each new session until it goes; every one serves, so that is no failure either. - if (lived < Nano.fromMilli(healthy)) { + if (lived.lt(healthy)) { if (ended.uri === "") this.#restart(effect); else this.#retry(effect, connected, new Error("peer redirected immediately")); return; @@ -738,9 +739,9 @@ export class Reload { } // When a retry window starting `at` expires. - #window(at: Instant): number { + #window(at: Instant): Instant | null { const { timeout } = this.#pacing(); - return timeout > 0 ? Instant.add(at, Nano.fromMilli(timeout)) : Number.POSITIVE_INFINITY; + return timeout.isZero() ? null : at.add(timeout); } /** @@ -755,15 +756,15 @@ export class Reload { effect.timer(() => { this.#deadline = undefined; this.#tick.update((prev) => Math.max(prev, tick)); - }, Nano(wait)); + }, wait); } // The jittered wait before the next attempt, escalating the delay for the one after. // Equal jitter, so a fleet of tabs knocked offline together doesn't reconnect on the same tick. - #backoff(): number { + #backoff(): Duration { const pacing = this.#pacing(); this.#delay ??= pacing.initial; - const wait = Nano.fromMilli(this.#delay) * (0.5 + Math.random() / 2); + const wait = this.#delay.mul(0.5 + Math.random() / 2); this.#delay = pacing.next(this.#delay); return wait; } @@ -781,10 +782,7 @@ export class Reload { // A healthy session's end clears the backoff and starts a fresh retry window: a one-off // drop should reconnect promptly. Anything shorter is a peer that accepts and soon // severs, which has to keep escalating or we hammer it forever at the initial delay. - if ( - connected !== undefined && - Instant.durationSince(now(), connected) >= Nano.fromMilli(this.#pacing().healthy) - ) { + if (connected !== undefined && now().since(connected).ge(this.#pacing().healthy)) { this.#delay = undefined; this.#deadline = undefined; } @@ -821,21 +819,21 @@ export class Reload { // No attempt starts once the window has passed: a wait that reaches the deadline gives up // there instead of dialing. - const left = this.#deadline - at; - if (wait >= left) { + const left = this.#deadline === null ? undefined : this.#deadline.since(at); + if (left !== undefined && wait.ge(left)) { // A graceful close has no error, so report the timeout itself. const failure = cause === undefined ? new Error("reconnect timed out") : error(cause); const giveUp = () => { console.warn("reconnect timed out"); this.#giveUp(failure); }; - if (left > 0) effect.timer(giveUp, Nano(left)); + if (!left.isZero()) effect.timer(giveUp, left); else giveUp(); return; } const tick = this.#tick.peek() + 1; - effect.timer(() => this.#tick.update((prev) => Math.max(prev, tick)), Nano(wait)); + effect.timer(() => this.#tick.update((prev) => Math.max(prev, tick)), wait); } #giveUp(cause: Error): void { @@ -936,10 +934,10 @@ class Draining { #onRetire: () => void; #retired = false; - constructor(connection: Established, handover: Milli, onRetire: () => void) { + constructor(connection: Established, handover: Duration, onRetire: () => void) { this.#connection = connection; this.#onRetire = onRetire; - void sleep(Nano.fromMilli(handover), { signal: this.#timer.signal }).then( + void sleep(handover, { signal: this.#timer.signal }).then( () => { if (this.retire()) console.warn("old session did not drain in time; closing"); connection.abort(); diff --git a/js/net/src/connection/scope.test.ts b/js/net/src/connection/scope.test.ts index 8c6e0b204c3..2244b0225d7 100644 --- a/js/net/src/connection/scope.test.ts +++ b/js/net/src/connection/scope.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Milli, Nano } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { announcedView } from "../announced.test-util"; import * as Ietf from "../ietf/index.ts"; import * as Lite from "../lite/index.ts"; @@ -36,7 +36,7 @@ for (const protocol of [Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_18]) { for (let index = 0; index < 3; index++) { const update = await withTimeout( announced.next(), - Nano.fromMilli(Milli(1000)), + Duration.millis(1000), "scoped announcement did not arrive", ); if (update?.kind !== "start") throw new Error(`expected an announcement, got ${update?.kind}`); diff --git a/js/net/src/connection/stats.test.ts b/js/net/src/connection/stats.test.ts index cd3a56f3ff6..e8ad8a79b57 100644 --- a/js/net/src/connection/stats.test.ts +++ b/js/net/src/connection/stats.test.ts @@ -1,5 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { Manual, Milli, Nano, yieldNow } from "@moq/clock"; +import { Duration, Manual, yieldNow } from "@moq/clock"; import QmuxSession from "@moq/qmux"; import { Effect } from "@moq/signals"; import * as Ietf from "../ietf/index.ts"; @@ -34,7 +34,7 @@ test("transportStats maps the W3C dictionary and normalizes a null send rate", a packetsLost: 6, }), ); - expect(stats.rtt).toBe(Milli(25)); + expect(stats.rtt).toEqual(Duration.millis(25)); expect(stats.estimatedSendRate).toBeUndefined(); expect(stats.bytesSent).toBe(1); expect(stats.bytesReceived).toBe(2); @@ -211,7 +211,7 @@ test("Reload exposes its established session stats and probe only while connecte test("a lite connection probes only while its estimate is observed", async () => { const clock = new Manual(); const installed = clock.install(); - const drain = () => clock.advance(Nano.zero); + const drain = () => clock.advance(Duration.ZERO); const pair = createMockTransportPair(Lite.ALPN_06, { stats: { estimatedSendRate: 1_000_000 } }); const open = pair.client.createBidirectionalStream.bind(pair.client); let finished = 0; @@ -246,7 +246,7 @@ test("a lite connection probes only while its estimate is observed", async () => values.push(effect.get(client.probe)); }); await drain(); - await clock.advance(Nano.fromMilli(Milli(100))); + await clock.advance(Duration.millis(100)); expect(values.at(-1)).toMatchObject({ estimatedRecvRate: 1_000_000 }); // A reactive one-shot listener reattaches without dropping demand between updates. expect(pair.client.sendStreams.bidi).toHaveLength(1); diff --git a/js/net/src/connection/stats.ts b/js/net/src/connection/stats.ts index 764c117b066..22b0decfaa2 100644 --- a/js/net/src/connection/stats.ts +++ b/js/net/src/connection/stats.ts @@ -1,4 +1,4 @@ -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import type { Established } from "./established.ts"; import { transportOf } from "./transport.ts"; /** @@ -31,7 +31,7 @@ export interface Stats { * Usually absent: browsers don't report an RTT yet even though the W3C dictionary * has the field. Use {@link Probe.rtt}, which the peer measures. */ - rtt?: Milli; + rtt?: Duration; /** Estimated send bandwidth from the congestion controller, in bits per second. */ estimatedSendRate?: number; @@ -80,7 +80,7 @@ export interface Probe { * Measured through the peer's application layer, so it reads higher than a * transport-level RTT would. */ - rtt?: Milli; + rtt?: Duration; /** The peer's send-rate estimate toward us, so our receive rate, in bits per second. */ estimatedRecvRate?: number; @@ -150,7 +150,7 @@ export async function transportStats(quic: WebTransport): Promise { try { const stats = await getStats(); return { - rtt: stats.smoothedRtt !== undefined ? Milli(stats.smoothedRtt) : undefined, + rtt: stats.smoothedRtt !== undefined ? Duration.millis(stats.smoothedRtt) : undefined, estimatedSendRate: stats.estimatedSendRate ?? undefined, bytesSent: stats.bytesSent, bytesReceived: stats.bytesReceived, diff --git a/js/net/src/connection/ticker.test.ts b/js/net/src/connection/ticker.test.ts index 80af62977ad..9e9e4f74025 100644 --- a/js/net/src/connection/ticker.test.ts +++ b/js/net/src/connection/ticker.test.ts @@ -1,18 +1,18 @@ import { expect, test } from "bun:test"; -import { Manual, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { tick } from "./ticker.ts"; test("subscribers share one tick and the loop stops with the last", async () => { const clock = new Manual(); const installed = clock.install(); try { - const period = Nano.fromMilli(Milli(100)); + const period = Duration.millis(100); const ticks: string[] = []; const a = tick(period, () => ticks.push("a")); - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); // Joins the running loop rather than starting its own out of phase. const b = tick(period, () => ticks.push("b")); - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); expect(ticks).toEqual(["a", "b"]); a(); @@ -21,7 +21,7 @@ test("subscribers share one tick and the loop stops with the last", async () => b(); b(); - await clock.advance(Nano.fromMilli(Milli(500))); + await clock.advance(Duration.millis(500)); expect(ticks).toEqual(["a", "b", "b"]); // A stopped loop restarts for a later subscriber, rather than leaving the page unsampled. diff --git a/js/net/src/connection/ticker.ts b/js/net/src/connection/ticker.ts index 67be719faad..b5452b86eeb 100644 --- a/js/net/src/connection/ticker.ts +++ b/js/net/src/connection/ticker.ts @@ -1,4 +1,4 @@ -import { Instant, type Nano, now, sleepUntil } from "@moq/clock"; +import { type Duration, now, sleepUntil } from "@moq/clock"; /** * One page-wide ticker shared by every caller with the same period. @@ -8,11 +8,11 @@ import { Instant, type Nano, now, sleepUntil } from "@moq/clock"; * loops ticking out of phase. The loop runs only while a subscriber is registered. */ class Ticker { - readonly #period: Nano; + readonly #period: Duration; readonly #subscribers = new Set<() => void>(); #abort?: AbortController; - constructor(period: Nano) { + constructor(period: Duration) { this.#period = period; } @@ -33,7 +33,7 @@ class Ticker { const abort = new AbortController(); this.#abort = abort; void (async () => { - let next = Instant.add(now(), this.#period); + let next = now().add(this.#period); for (;;) { await sleepUntil(next, { signal: abort.signal }).catch(() => {}); if (abort.signal.aborted) return; @@ -45,21 +45,22 @@ class Ticker { console.error("ticker callback error", err); } } - next = Instant.add(now(), this.#period); + next = now().add(this.#period); } })(); } } -const tickers = new Map(); +// Keyed by nanoseconds, since equal durations are distinct objects. +const tickers = new Map(); /** Subscribes `fn` to the page-wide ticker for `period`; returns its dispose. */ -export function tick(period: Nano, fn: () => void): () => void { - if (period <= 0) throw new RangeError("ticker period must be positive"); - let ticker = tickers.get(period); +export function tick(period: Duration, fn: () => void): () => void { + if (period.isZero()) throw new RangeError("ticker period must be positive"); + let ticker = tickers.get(period.asNanos()); if (!ticker) { ticker = new Ticker(period); - tickers.set(period, ticker); + tickers.set(period.asNanos(), ticker); } return ticker.subscribe(fn); } diff --git a/js/net/src/error.ts b/js/net/src/error.ts index 9a5f3ae0c31..48ee48fabfd 100644 --- a/js/net/src/error.ts +++ b/js/net/src/error.ts @@ -4,7 +4,7 @@ * @module */ -import type { Milli } from "@moq/clock"; +import type { Duration } from "@moq/clock"; import { sharedStreamCode } from "./ietf/error.ts"; import type { IetfVersion } from "./ietf/version.ts"; import { TimeoutError } from "./util/timeout.ts"; @@ -314,10 +314,10 @@ export class RefusedRedirect extends Error { */ export class ConnectTimeout extends Error { /** The timeout that elapsed. */ - readonly timeout: Milli; + readonly timeout: Duration; - constructor(timeout: Milli) { - super(`connect timed out after ${timeout}ms`); + constructor(timeout: Duration) { + super(`connect timed out after ${timeout}`); this.name = "ConnectTimeout"; this.timeout = timeout; } diff --git a/js/net/src/fill.test.ts b/js/net/src/fill.test.ts index ac9e8a627f4..e70e3d1a5a1 100644 --- a/js/net/src/fill.test.ts +++ b/js/net/src/fill.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Manual, Milli, Nano, yieldNow } from "@moq/clock"; +import { Duration, Manual, yieldNow } from "@moq/clock"; import { Producer as BroadcastProducer } from "./broadcast.ts"; import { accept as acceptSession, connect as connectSession } from "./connection/index.ts"; import { NotFound, StreamCode, StreamError, toStreamCode } from "./error.ts"; @@ -309,13 +309,13 @@ test("fill: a refusal fails the readers waiting now, and a later reader asks aga test("fill: a fill names the most urgent priority and loosest budget among its readers", async () => { const { broadcast, track } = resumed(5n); const requests = track.requests(); - const low = track.subscribe({ ...history, priority: 1, delay: { max: Milli(60_000) } }); + const low = track.subscribe({ ...history, priority: 1, delay: { max: Duration.millis(60_000) } }); void drain(low); const fill = await requests.requestedFill(); if (!fill) throw new Error("no fill"); expect([fill.start, fill.end]).toEqual([0n, 5n]); expect(fill.priority).toBe(1); - expect(fill.maxDelay).toBe(Milli(60_000)); + expect(fill.maxDelay).toEqual(Duration.millis(60_000)); expect(fill.order).toBe("ascending"); const high = track.subscribe({ ...history, priority: 7, order: "descending" }); @@ -391,7 +391,7 @@ test("fill: an ordered reader stops waiting on an unanswered fill once its budge const requests = track.requests(); const reader = track.subscribe({ ranges: [{ start: { absolute: 0n } }], - delay: { max: Milli(1000) }, + delay: { max: Duration.millis(1000) }, order: "ascending", }); const next = reader.ordered().nextGroup(); @@ -400,7 +400,7 @@ test("fill: an ordered reader stops waiting on an unanswered fill once its budge expect([fill?.start, fill?.end]).toEqual([0n, 5n]); // Group 5 arrived when the reader asked, so its budget gives up the holes below a second on. - await clock.advance(Nano.fromMilli(Milli(1001))); + await clock.advance(Duration.millis(1001)); expect((await next)?.sequence).toBe(5n); fill?.close(); @@ -419,14 +419,17 @@ test("fill: an arrival-order reader stops waiting on an unanswered fill once its const { broadcast, track } = resumed(5n); track.finish(); const requests = track.requests(); - const reader = track.subscribe({ ranges: [{ start: { absolute: 0n } }], delay: { max: Milli(1000) } }); + const reader = track.subscribe({ + ranges: [{ start: { absolute: 0n } }], + delay: { max: Duration.millis(1000) }, + }); expect((await reader.recvGroup())?.sequence).toBe(5n); const next = reader.recvGroup(); const fill = await requests.requestedFill(); expect([fill?.start, fill?.end]).toEqual([0n, 5n]); // The fill never answers; the holes go past the budget, and the finished track ends the read. - await clock.advance(Nano.fromMilli(Milli(1001))); + await clock.advance(Duration.millis(1001)); expect(await next).toBeUndefined(); // The reader gave the stale holes up, so the handler hears it no longer waits on them. expect(fill?.wanted()).toBeUndefined(); @@ -448,7 +451,7 @@ test("fill: a handler hears that a reader stopped wanting what it handed out pas const requests = track.requests(); const reader = track.subscribe({ ranges: [{ start: { absolute: 0n } }], - delay: { max: Milli(1000) }, + delay: { max: Duration.millis(1000) }, order: "ascending", }); const next = reader.ordered().nextGroup(); @@ -459,7 +462,7 @@ test("fill: a handler hears that a reader stopped wanting what it handed out pas const unwanted = fill.unwanted(0n); // Past the budget the reader takes group 5, leaving the holes below it for good. - await clock.advance(Nano.fromMilli(Milli(1001))); + await clock.advance(Duration.millis(1001)); expect((await next)?.sequence).toBe(5n); expect(await changed).toBeUndefined(); await unwanted; @@ -487,12 +490,12 @@ test("fill: a bounded reader keeps waiting on a fresh fill once an older one goe }; // Holes 0-1 wait on group 2, which arrives first; holes 3-4 on group 5, half a second later. write(2n); - await clock.advance(Nano.fromMilli(Milli(500))); + await clock.advance(Duration.millis(500)); write(5n); const requests = track.requests(); const reader = track.subscribe({ ranges: [{ start: { absolute: 0n }, end: { absolute: 6n } }], - delay: { max: Milli(1000) }, + delay: { max: Duration.millis(1000) }, }); expect((await reader.recvGroup())?.sequence).toBe(2n); expect((await reader.recvGroup())?.sequence).toBe(5n); @@ -508,7 +511,7 @@ test("fill: a bounded reader keeps waiting on a fresh fill once an older one goe ]); // Holes 0-1 are past the budget now, but 3-4 are not: the read waits on them. - await clock.advance(Nano.fromMilli(Milli(600))); + await clock.advance(Duration.millis(600)); const late = fills[1].accept(3n); late.writeFrame({ payload: enc.encode("old 3") }); late.finish(); @@ -762,7 +765,7 @@ test("fill: a stale run that does not settle the reader is still asked for", asy hooks.dropTrackGroups(track, 0n, 2n, staleHole(60_000)); const reader = track.subscribe({ ranges: [{ start: { absolute: 0n }, end: { absolute: 2n } }], - delay: { max: Milli(500) }, + delay: { max: Duration.millis(500) }, }); void drain(reader); const fill = await Promise.race([requests.requestedFill(), yieldNow().then(() => undefined)]); @@ -789,7 +792,7 @@ function judgedTwice() { const reader = (ranges: [bigint, bigint][]) => track.subscribe({ ranges: ranges.map(([start, end]) => ({ start: { absolute: start }, end: { absolute: end } })), - delay: { max: Milli(500) }, + delay: { max: Duration.millis(500) }, }); return { broadcast, requests, reader }; } diff --git a/js/net/src/fill.ts b/js/net/src/fill.ts index c866f1f3520..438cba65066 100644 --- a/js/net/src/fill.ts +++ b/js/net/src/fill.ts @@ -10,7 +10,7 @@ * * @module */ -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { type GetPromise, type Getter, Signal } from "@moq/signals"; import { NotFound } from "./error.ts"; import type { Producer as GroupProducer } from "./group.ts"; @@ -463,10 +463,10 @@ export class Fill { * The most tolerant age budget among the readers waiting on it now, or `null` for none: the * publisher's {@link Info.maxAge} alone bounds it. Each reader still enforces its own. */ - get maxDelay(): Milli | null { + get maxDelay(): Duration | null { let max = 0; for (const asker of this.#pending.askers) max = Math.max(max, asker.maxDelay()); - return max < NO_MAX_DELAY ? Milli(max) : null; + return max < NO_MAX_DELAY ? Duration.millis(max) : null; } /** Which end to fill first now: `"descending"`, newest first, if any reader asks it. */ diff --git a/js/net/src/goaway-requests.test.ts b/js/net/src/goaway-requests.test.ts index fb869add6ca..88c67681168 100644 --- a/js/net/src/goaway-requests.test.ts +++ b/js/net/src/goaway-requests.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Instant, Manual, Milli, Nano, now, yieldNow } from "@moq/clock"; +import { Duration, Manual, now, yieldNow } from "@moq/clock"; import { Once } from "@moq/signals"; import { accept } from "./connection/accept.ts"; import { connect } from "./connection/connect.ts"; @@ -29,10 +29,10 @@ async function settle() { } async function waitUntil(pred: () => boolean): Promise { - const deadline = Instant.add(now(), Nano.fromMilli(Milli(2000))); + const deadline = now().add(Duration.millis(2000)); for (;;) { if (pred()) return; - if (now() > deadline) throw new Error("timed out waiting for condition"); + if (now().gt(deadline)) throw new Error("timed out waiting for condition"); await settle(); } } @@ -357,7 +357,7 @@ async function routeDeath(kind: "lite" | "ietf", after: boolean): Promise // A draining close of a session still serving a live track gives up after its drain. const closing = server.close().catch(() => {}); - await clock.advance(Nano.fromMilli(Milli(1000))); + await clock.advance(Duration.millis(1000)); await closing; await expect( (async () => { diff --git a/js/net/src/group.test.ts b/js/net/src/group.test.ts index d4d99aa3b4e..2762a8eb27c 100644 --- a/js/net/src/group.test.ts +++ b/js/net/src/group.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Manual, Milli, Nano, yieldNow } from "@moq/clock"; +import { Duration, Manual, yieldNow } from "@moq/clock"; import { Signal } from "@moq/signals"; import { FrameTooLarge, StreamCode, StreamError } from "./error.ts"; import { encodable } from "./flate/group.ts"; @@ -78,23 +78,23 @@ test("a frame read late keeps the instant it landed, plain, compressed, or resum hooks.bindGroupCompression(compressed, true); const first = clock.now(); plain.writeFrame(textFrame("a")); - clock.jump(Nano.fromMilli(Milli(10))); + clock.jump(Duration.millis(10)); const second = clock.now(); plain.writeFrame(textFrame("b")); compressed.writeFrame(textFrame("b")); - clock.jump(Nano.fromMilli(Milli(1000))); + clock.jump(Duration.millis(1000)); const reader = plain.consume(); - expect(reader.tryReadFrame()?.arrived).toBe(first); - expect((await reader.readFrameSequence())?.arrived).toBe(second); + expect(reader.tryReadFrame()?.arrived).toEqual(first); + expect((await reader.readFrameSequence())?.arrived).toEqual(second); const stored = compressed.consume(); - expect((await hooks.readGroupFrame(stored, true))?.frame.arrived).toBe(first); - expect((await stored.readFrame())?.arrived).toBe(second); + expect((await hooks.readGroupFrame(stored, true))?.frame.arrived).toEqual(first); + expect((await stored.readFrame())?.arrived).toEqual(second); // A frame written in with a stamp of its own still gets this node's. const forwarded = new Producer(0n); forwarded.writeFrame({ payload: new Uint8Array([1]), arrived: first }); - expect(forwarded.consume().tryReadFrame()?.arrived).toBe(clock.now()); + expect(forwarded.consume().tryReadFrame()?.arrived).toEqual(clock.now()); // A resumed read takes the stamp the replacement copy holds, not when it was adopted. const failing = new Producer(0n); @@ -115,9 +115,9 @@ test("a frame read late keeps the instant it landed, plain, compressed, or resum }); failing.writeFrame(textFrame("a")); await resumed.readFrame(); - clock.jump(Nano.fromMilli(Milli(1000))); + clock.jump(Duration.millis(1000)); failing.abort(new Error("copy failed")); - expect((await resumed.readFrame())?.arrived).toBe(landed); + expect((await resumed.readFrame())?.arrived).toEqual(landed); for (const producer of [plain, compressed, forwarded, replacement]) producer.finish(); } finally { @@ -135,16 +135,16 @@ test("a group read late keeps the instant it joined, alone, on a track, or resum const subscriber = track.subscribe(); const live = track.createGroup(0n); live.writeFrame(textFrame("a")); - clock.jump(Nano.fromMilli(Milli(1000))); + clock.jump(Duration.millis(1000)); - expect(alone.consume().arrived).toBe(created); - expect((await subscriber.recvGroup())?.arrived).toBe(created); + expect(alone.consume().arrived).toEqual(created); + expect((await subscriber.recvGroup())?.arrived).toEqual(created); // A resumed read keeps the original group's arrival, not the replacement copy's. const original = clock.now(); const failing = new Producer(0n); const resumed = failing.mirror(); - clock.jump(Nano.fromMilli(Milli(1000))); + clock.jump(Duration.millis(1000)); const replacement = new Producer(0n); replacement.writeFrame(textFrame("a")); replacement.writeFrame(textFrame("b")); @@ -162,7 +162,7 @@ test("a group read late keeps the instant it joined, alone, on a track, or resum await resumed.readFrame(); failing.abort(new Error("copy failed")); expect((await resumed.readFrame())?.payload).toEqual(textFrame("b").payload); - expect(resumed.arrived).toBe(original); + expect(resumed.arrived).toEqual(original); for (const producer of [alone, live, replacement]) producer.finish(); subscriber.close(); diff --git a/js/net/src/ietf/aliases.test.ts b/js/net/src/ietf/aliases.test.ts index ec0eebad6a5..36d904bb2b2 100644 --- a/js/net/src/ietf/aliases.test.ts +++ b/js/net/src/ietf/aliases.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Manual, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { DuplicateTrackAlias, RetiredTrackAlias, SharedTrackAlias, TrackAliases } from "./aliases.ts"; test("waits for the control message that establishes an alias", async () => { @@ -111,7 +111,7 @@ test("retired aliases are capped", async () => { // The oldest tombstones are forgotten, so they fall back to the unknown-alias wait. const forgotten = aliases.get(0n).catch((error: unknown) => error); - await clock.advance(Nano.fromMilli(Milli(1000))); + await clock.advance(Duration.millis(1000)); expect(await forgotten).toHaveProperty("message", "unknown track alias: 0"); await expect(aliases.get(73n)).rejects.toBeInstanceOf(RetiredTrackAlias); }); diff --git a/js/net/src/ietf/aliases.ts b/js/net/src/ietf/aliases.ts index 4f87c2a51dd..f74cf9b80e2 100644 --- a/js/net/src/ietf/aliases.ts +++ b/js/net/src/ietf/aliases.ts @@ -1,6 +1,6 @@ -import { Elapsed, Milli, Nano, timeout } from "@moq/clock"; +import { Duration, Elapsed, timeout } from "@moq/clock"; -const TRACK_ALIAS_TIMEOUT = Nano.fromMilli(Milli(1000)); +const TRACK_ALIAS_TIMEOUT = Duration.millis(1000); /** * How many cancelled aliases to remember. Objects keep arriving for about a round trip diff --git a/js/net/src/ietf/connection.ts b/js/net/src/ietf/connection.ts index c332e1c41b9..d0560146f34 100644 --- a/js/net/src/ietf/connection.ts +++ b/js/net/src/ietf/connection.ts @@ -1,4 +1,4 @@ -import { Nano, Second } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { type GetPromise, type Getter, Once, race, Signal } from "@moq/signals"; import * as announce from "../announced.ts"; import type * as Auth from "../auth.ts"; @@ -245,11 +245,9 @@ export class Connection implements Established { /** Withdraw announcements and wait up to one second for delivery before closing. */ close(): Promise { - this.#closing ??= withTimeout( - this.#publisher.withdraw(), - Nano.fromSecond(Second(1)), - "session close timed out", - ).finally(() => this.abort()); + this.#closing ??= withTimeout(this.#publisher.withdraw(), Duration.secs(1), "session close timed out").finally( + () => this.abort(), + ); return this.#closing; } diff --git a/js/net/src/ietf/datagram.test.ts b/js/net/src/ietf/datagram.test.ts index 951390840ea..8474a81ced2 100644 --- a/js/net/src/ietf/datagram.test.ts +++ b/js/net/src/ietf/datagram.test.ts @@ -1,5 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { Milli, yieldNow } from "@moq/clock"; +import { Duration, yieldNow } from "@moq/clock"; import { accept, connect } from "../connection/index.ts"; import { ProtocolViolation, SessionCode } from "../error.ts"; import { createMockTransportPair, type MockTransport, manual, settlesWithin } from "../mock.ts"; @@ -116,7 +116,7 @@ test("a defined object status does not close the session", async () => { }).encode(version); const writer = writable.getWriter(); await writer.write(bytes); - expect(await settlesWithin(pair.server.closed, clock, Milli(50))).toBe(false); + expect(await settlesWithin(pair.server.closed, clock, Duration.millis(50))).toBe(false); } finally { connection.abort(); } diff --git a/js/net/src/ietf/fetch.test.ts b/js/net/src/ietf/fetch.test.ts index bf0cbc5b5fd..59579224d60 100644 --- a/js/net/src/ietf/fetch.test.ts +++ b/js/net/src/ietf/fetch.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Manual, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { Signal } from "@moq/signals"; import type { Grant } from "../auth.ts"; import { DEFAULT_EXPIRY } from "../cache.ts"; @@ -43,7 +43,7 @@ const INVALID_JOINING_REQUEST_ID = 0x32; /** A publisher serving the `room` broadcast, with its `video` track and the client's uni streams. */ // `maxAge` is the track's publisher max age: omitted is the authored zero, and a test that fills // superseded history passes `null`, since the publisher fills only groups still fresh. -function serve(version: IetfVersion, grant?: Signal, priority?: number, maxAge?: Milli | null) { +function serve(version: IetfVersion, grant?: Signal, priority?: number, maxAge?: Duration | null) { const pair = createMockTransportPair(ALPNS[version]); const origin = new OriginProducer(); const pub = new Publisher({ @@ -139,8 +139,8 @@ function manual(): Manual & Disposable { return Object.assign(clock, { [Symbol.dispose]: () => installed.close() }); } -function ms(value: number): Nano { - return Nano.fromMilli(Milli(value)); +function ms(value: number): Duration { + return Duration.millis(value); } /** Let every pending promise chain run. */ @@ -276,7 +276,7 @@ test("FETCH and FETCH_OK round trip on every draft", async () => { type, subscriberPriority: 3, groupOrder: "descending", - fillTimeout: Milli(250), + fillTimeout: 250, }); const decoded = await Fetch.decode(await encode(msg, version), version); expect(decoded).toEqual(msg); @@ -436,7 +436,7 @@ test("a FETCH fills never-cached and evicted history, then reuses the cache", as using fx = serve(version, undefined, undefined, null); if (evicted) { writeGroup(fx.track, 1n, ["1-0", "1-1", "1-2"]); - await clock.advance(ms(DEFAULT_EXPIRY * 2)); + await clock.advance(DEFAULT_EXPIRY.mul(2)); } writeGroup(fx.track, 3n, ["live"]); const cache = fx.track.subscribe({ ranges: [] }); @@ -608,7 +608,7 @@ test("a FETCH outside the grant is refused", async () => { // The requester leaving while the answer waits on an open group is owed nothing, budget or not. test("a cancelled FETCH stops waiting", async () => { for (const version of VERSIONS) { - for (const fillTimeout of [undefined, Milli(10_000)]) { + for (const fillTimeout of [undefined, 10_000]) { using _clock = manual(); using fx = serve(version); publishPairs(fx.track, 2); @@ -630,7 +630,7 @@ test("a cancelled FETCH stops waiting", async () => { // FILL_TIMEOUT is accepted without truncating a one-group answer, including zero. test("FILL_TIMEOUT is ignored while a group finishes", async () => { for (const version of VERSIONS) { - for (const fillTimeout of [Milli(0), Milli(100)]) { + for (const fillTimeout of [0, 100]) { using clock = manual(); using fx = serve(version); const live = writeGroup(fx.track, 4n, ["4-0"], false); diff --git a/js/net/src/ietf/fetch.ts b/js/net/src/ietf/fetch.ts index 5202dca454b..2de7aefc5f8 100644 --- a/js/net/src/ietf/fetch.ts +++ b/js/net/src/ietf/fetch.ts @@ -1,4 +1,3 @@ -import type { Milli } from "@moq/clock"; import type * as Path from "../path.ts"; import { type Reader, Writer } from "../stream.ts"; import type { Order } from "../track.ts"; @@ -96,7 +95,7 @@ export class Fetch { * FILL_TIMEOUT: the total wait for objects not yet available before they are reported as * a gap, zero for only what is cached. Absent waits as long as the publisher chooses. */ - fillTimeout?: Milli; + fillTimeout?: number; /** Whether the requester wants Track Properties in FETCH_OK (INCLUDE_PROPERTIES, draft-22). */ propertiesWanted: boolean; @@ -115,7 +114,7 @@ export class Fetch { subscriberPriority?: number; groupOrder?: Order; rangeFilters?: boolean; - fillTimeout?: Milli; + fillTimeout?: number; propertiesWanted?: boolean; }) { this.requestId = requestId; diff --git a/js/net/src/ietf/filter.test.ts b/js/net/src/ietf/filter.test.ts index be2a5d0dd1d..3a9860689f2 100644 --- a/js/net/src/ietf/filter.test.ts +++ b/js/net/src/ietf/filter.test.ts @@ -1,5 +1,4 @@ import { expect, test } from "bun:test"; -import { Milli } from "@moq/clock"; import { ProtocolViolation } from "../error.ts"; import * as Path from "../path.ts"; import { Reader, Writer } from "../stream.ts"; @@ -193,9 +192,9 @@ test("fill round trips", () => { // An omitted filter inherits the subscription's, which is a different request from an // explicit unfiltered one. { filter: undefined, rangeFilters: false }, - { fillTimeout: Milli(0), filter: undefined, rangeFilters: false }, + { fillTimeout: 0, filter: undefined, rangeFilters: false }, { - fillTimeout: Milli(250), + fillTimeout: 250, filter: { kind: "relative", groups: 1n }, groupOrder: "ascending", rangeFilters: false, @@ -212,7 +211,7 @@ test("fill round trips", () => { // FILL_TIMEOUT sorts first, so the parameters after it are deltas from its id. test("fill encodes its FILL_TIMEOUT first", () => { const fill: Filter.Fill = { - fillTimeout: Milli(100), + fillTimeout: 100, filter: { kind: "relative", groups: 1n }, rangeFilters: false, }; diff --git a/js/net/src/ietf/filter.ts b/js/net/src/ietf/filter.ts index 427e594a24a..964b74dad2c 100644 --- a/js/net/src/ietf/filter.ts +++ b/js/net/src/ietf/filter.ts @@ -4,7 +4,6 @@ * @module */ -import { Milli } from "@moq/clock"; import { ProtocolViolation } from "../error.ts"; import { concat, type Reader } from "../stream.ts"; import type { Order } from "../track.ts"; @@ -358,7 +357,7 @@ export interface Fill { groupOrder?: Order; /** FILL_TIMEOUT, bounding the fill's wait as it does a FETCH's; see {@link Parameters.fillTimeout}. */ - fillTimeout?: Milli; + fillTimeout?: number; /** * The range to fill. `undefined` means the Location Filter was omitted, which inherits @@ -440,7 +439,7 @@ export function decodeFill(data: Uint8Array, version: IetfVersion): Fill { let rest = afterCount; let filter: Filter | undefined; let groupOrder: Order | undefined; - let fillTimeout: Milli | undefined; + let fillTimeout: number | undefined; let rangeFilters = false; let prev = 0n; for (let i = 0n; i < count; i++) { @@ -469,7 +468,7 @@ export function decodeFill(data: Uint8Array, version: IetfVersion): Fill { let value: bigint; [value, rest] = unvarint(rest); // The clock API holds exact numeric milliseconds. - fillTimeout = Milli(toNumber(value)); + fillTimeout = toNumber(value); continue; } diff --git a/js/net/src/ietf/goaway.test.ts b/js/net/src/ietf/goaway.test.ts index d74804f3964..47f37b94a56 100644 --- a/js/net/src/ietf/goaway.test.ts +++ b/js/net/src/ietf/goaway.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { SessionCode, StreamCode, StreamError } from "../error.ts"; import { createMockTransportPair, manual, settlesWithin } from "../mock.ts"; import { Producer as OriginProducer } from "../origin.ts"; @@ -41,9 +41,9 @@ for (const [version, alpn, requestId] of [ const drain = await connection.draining; expect(drain.uri).toBe(""); - expect(drain.timeout).toBe(Milli(5000)); + expect(drain.timeout).toEqual(Duration.millis(5000)); - expect(await settlesWithin(connection.closed, clock, Milli(20))).toBe(false); + expect(await settlesWithin(connection.closed, clock, Duration.millis(20))).toBe(false); } finally { connection.abort(); } @@ -69,7 +69,7 @@ test("a server rejects a client GOAWAY that names a redirect", async () => { try { await peer.writer.u53(GoAway.id); await new GoAway({ newSessionUri: "https://other.example/", timeout: 0n }).encode(peer.writer, version); - expect(await settlesWithin(connection.closed, clock, Milli(50))).toBe(true); + expect(await settlesWithin(connection.closed, clock, Duration.millis(50))).toBe(true); } finally { connection.abort(); } diff --git a/js/net/src/ietf/goaway.ts b/js/net/src/ietf/goaway.ts index f09daef2d54..787aedece22 100644 --- a/js/net/src/ietf/goaway.ts +++ b/js/net/src/ietf/goaway.ts @@ -1,4 +1,4 @@ -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import type { Drain } from "../connection/goaway.ts"; import { ProtocolViolation } from "../error.ts"; import type { Reader, Writer } from "../stream.ts"; @@ -48,7 +48,7 @@ export class GoAway { drain(): Drain { return { uri: this.newSessionUri, - timeout: this.timeout > 0n ? Milli(toNumber(this.timeout)) : undefined, + timeout: this.timeout > 0n ? Duration.millis(toNumber(this.timeout)) : undefined, }; } diff --git a/js/net/src/ietf/ietf.test.ts b/js/net/src/ietf/ietf.test.ts index 13ecd8d4a2e..fb9ed0c0084 100644 --- a/js/net/src/ietf/ietf.test.ts +++ b/js/net/src/ietf/ietf.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Milli } from "@moq/clock"; + import { ProtocolViolation } from "../error.ts"; import * as Path from "../path.ts"; import { type Cursor, Reader, Writer } from "../stream.ts"; @@ -1021,7 +1021,7 @@ test("Fetch draft-22: decodes every legal parameter", async () => { const msg = await decodeVersioned(body, Fetch.decode, Version.DRAFT_22); expect(msg.requestId).toBe(1n); - expect(msg.fillTimeout).toBe(Milli(100)); + expect(msg.fillTimeout).toBe(100); }); // Draft-22's LOCATION_FILTER is a Location Filter Type with no Length, so Next Object is the diff --git a/js/net/src/ietf/join.test.ts b/js/net/src/ietf/join.test.ts index 6692127cc15..b051e4fa13a 100644 --- a/js/net/src/ietf/join.test.ts +++ b/js/net/src/ietf/join.test.ts @@ -1,5 +1,5 @@ import { expect, jest, onTestFinished, test } from "bun:test"; -import { Instant, Manual, Milli, Nano, now } from "@moq/clock"; +import { Duration, Manual, now } from "@moq/clock"; import * as Connection from "../connection/index.ts"; import { StreamCode } from "../error.ts"; import { hooks } from "../internal.ts"; @@ -51,7 +51,7 @@ async function nextStream(transport: WebTransport, version: IetfVersion = VERSIO } /** Whether the subscriber opens a bidi stream before `clock` advances `duration`. */ -async function opens(transport: WebTransport, clock: Manual, duration = Milli(200)): Promise { +async function opens(transport: WebTransport, clock: Manual, duration = Duration.millis(200)): Promise { const reader = transport.incomingBidirectionalStreams.getReader(); try { return await settlesWithin(reader.read(), clock, duration); @@ -312,7 +312,7 @@ test("a joining FETCH has no deadline of its own", async () => { const tail = subscriber.handleGroup(...liveStream(GROUP, 2, ["t2"])); // Well past any request deadline: the FETCH is still out, and nothing else was sent. - expect(await opens(client, clock, Milli(60_000))).toBe(false); + expect(await opens(client, clock, Duration.millis(60_000))).toBe(false); await accept(fetching); await subscriber.handleFetch(await head(fetch.requestId, ["h0", "h1"])); @@ -342,7 +342,7 @@ test("a joining FETCH reset after FETCH_OK costs only the head", async () => { expect(group?.sequence).toBe(GROUP + 1n); expect(await consumer.recvGroup()).toBeUndefined(); expect(await consumer.closed).toBeNull(); - expect(Nano.toMilli(Instant.durationSince(now(), started))).toBeLessThan(GRACE); + expect(now().since(started).lt(GRACE)).toBe(true); }); test("SUBSCRIPTION_ENDED cancels a head nothing claimed", async () => { @@ -553,7 +553,7 @@ for (const version of VERSIONS) { expect(await frames(group)).toEqual(["catalog"]); expect(await consumer.recvGroup()).toBeUndefined(); expect(await consumer.closed).toBeNull(); - expect(Nano.toMilli(Instant.durationSince(now(), started))).toBeLessThan(GRACE); + expect(now().since(started).lt(GRACE)).toBe(true); }); } @@ -654,7 +654,7 @@ test("an evicted joined group is fetched again as standalone history", async () first?.close(); await subscriber.handleGroup(...liveStream(GROUP + 1n, 0, ["new"])); // Twice the model's 30-second idle cache window, with deterministic time. - await clock.advance(Nano.fromMilli(Milli(60_000))); + await clock.advance(Duration.millis(60_000)); expect(hooks.cachedGroup(consumer, GROUP)).toBeUndefined(); const broadcast = subscriber.consume(Path.from("room")); onTestFinished(() => broadcast.close()); diff --git a/js/net/src/ietf/malformed.test.ts b/js/net/src/ietf/malformed.test.ts index ddf7c90449e..de11d7d619e 100644 --- a/js/net/src/ietf/malformed.test.ts +++ b/js/net/src/ietf/malformed.test.ts @@ -1,5 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { type Manual, Milli, Nano } from "@moq/clock"; +import { Duration, type Manual } from "@moq/clock"; import { offered } from "../connection/extensions.ts"; import { exchangeSetup } from "../connection/handshake.ts"; import { ProtocolViolation, SessionCode, StreamCode, StreamError } from "../error.ts"; @@ -52,7 +52,7 @@ async function closeCode(quic: WebTransport, clock: Manual): Promise { code = info.closeCode; }); - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); return code; } diff --git a/js/net/src/ietf/parameters.ts b/js/net/src/ietf/parameters.ts index 9846ddcf1a4..acfc9d9fe29 100644 --- a/js/net/src/ietf/parameters.ts +++ b/js/net/src/ietf/parameters.ts @@ -1,4 +1,3 @@ -import { Milli } from "@moq/clock"; import { ProtocolViolation } from "../error.ts"; import type * as Path from "../path.ts"; import type { Reader, Writer } from "../stream.ts"; @@ -395,13 +394,13 @@ export class Parameters { /** * FILL_TIMEOUT: the total wait in safe numeric milliseconds for objects not yet available. */ - get fillTimeout(): Milli | undefined { + get fillTimeout(): number | undefined { const v = this.vars.get(MSG_PARAM_FILL_TIMEOUT); if (v === undefined) return undefined; - return Milli(toNumber(v)); + return toNumber(v); } - set fillTimeout(v: Milli | undefined) { + set fillTimeout(v: number | undefined) { if (v === undefined) this.vars.delete(MSG_PARAM_FILL_TIMEOUT); else this.vars.set(MSG_PARAM_FILL_TIMEOUT, BigInt(v)); } diff --git a/js/net/src/ietf/publisher.test.ts b/js/net/src/ietf/publisher.test.ts index 4e00bb0a26d..36dc27a100f 100644 --- a/js/net/src/ietf/publisher.test.ts +++ b/js/net/src/ietf/publisher.test.ts @@ -1,5 +1,5 @@ import { expect, onTestFinished, spyOn, test } from "bun:test"; -import { Manual, Milli, Nano, yieldNow } from "@moq/clock"; +import { Duration, Manual, yieldNow } from "@moq/clock"; import { Signal } from "@moq/signals"; import type { Credential, Grant } from "../auth.ts"; import { Producer as BroadcastProducer } from "../broadcast.ts"; @@ -69,8 +69,8 @@ async function opens(read: Promise<{ done: boolean }>, clock: Manual): Promise {}, ); - await clock.advance(Nano.zero); - await clock.advance(Nano.fromMilli(Milli(STREAM_WAIT))); + await clock.advance(Duration.ZERO); + await clock.advance(Duration.millis(STREAM_WAIT)); return opened; } @@ -235,7 +235,7 @@ test("TRACK_STATUS is answered on every draft without subscribing", async () => const broadcast = publish(origin, Path.from("room")); const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, - maxAge: Milli(5000), + maxAge: Duration.millis(5000), priority: 2, }); const group = track.createGroup(4n); @@ -862,7 +862,7 @@ test("a blocked group header is reset when the group expires", async () => { const { pub, origin } = publisher(pair.server); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: Milli(5000) }); + const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); const client = await Stream.open(pair.client, { version: VERSION }); const server = await Stream.accept(pair.server, VERSION); if (!server) throw new Error("publisher never accepted the subscribe stream"); @@ -936,7 +936,7 @@ test("a group stream whose FIN never completes is reset when the group expires", }); spyOn(pair.server, "createUnidirectionalStream").mockImplementationOnce(async () => stalled); - const budget = Milli(5000); + const budget = Duration.millis(5000); const { pub, origin } = publisher(pair.server); const broadcast = publish(origin, Path.from("test")); // No subscriber max age, so the track's caps the budget. @@ -965,7 +965,7 @@ test("a group stream whose FIN never completes is reset when the group expires", write(0n); await closeStarted; // The newest group is never stale, however long its FIN takes. - await clock.advance(Nano.fromMilli(Milli(budget * 2))); + await clock.advance(budget.mul(2)); expect(reset).toBe(false); // Its successor presents no further, so only the wall clock since it arrived convicts @@ -973,9 +973,9 @@ test("a group stream whose FIN never completes is reset when the group expires", write(1n); track.finish(); track.close(); - await clock.advance(Nano.fromMilli(Milli(budget - 1))); + await clock.advance(budget.sub(Duration.millis(1))); expect(reset).toBe(false); - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); await streamReset; } finally { client.close(); @@ -1018,7 +1018,7 @@ test("a group stream whose FIN never completes is reset after the cache evicts i spyOn(pair.server, "createUnidirectionalStream").mockImplementationOnce(async () => stalled); // Twice the cache's idle window. - const budget = Milli(60_000); + const budget = Duration.millis(60_000); const { pub, origin } = publisher(pair.server); const broadcast = publish(origin, Path.from("test")); const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: budget }); @@ -1050,15 +1050,15 @@ test("a group stream whose FIN never completes is reset after the cache evicts i await closeStarted; write(1n); // A later group, so a verdict that forgot group 1 would wait for this one's deadline. - const later = Milli(10_000); - await clock.advance(Nano.fromMilli(later)); + const later = Duration.millis(10_000); + await clock.advance(later); write(2n); track.finish(); track.close(); - await clock.advance(Nano.fromMilli(Milli(budget - later - 1))); + await clock.advance(budget.sub(later).sub(Duration.millis(1))); expect(reset).toBe(false); - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); await streamReset; await running; @@ -1108,7 +1108,7 @@ test("a group that goes stale while its stream opens writes nothing", async () = const { pub, origin } = publisher(pair.server); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: Milli(5000) }); + const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); const client = await Stream.open(pair.client, { version: VERSION }); const server = await Stream.accept(pair.server, VERSION); if (!server) throw new Error("publisher never accepted the subscribe stream"); @@ -1174,7 +1174,7 @@ test("a broadcast published mid-advertisement is still announced", async () => { // Publish while the loop is parked on that reply. publish(origin, Path.from("second")); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); await acceptPublishNamespace(one); @@ -1435,7 +1435,7 @@ test("republishing a path clears a refusal without unannouncing first", async () const declined = await nextStream(pair.client); expect(await readPublishNamespace(declined)).toBe(Path.from("recycled")); await declinePublishNamespace(declined, 0n); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); // A new broadcast takes the path over outright: no close, no gap. publish(origin, Path.from("recycled")); @@ -1464,7 +1464,7 @@ test("a new instance at the same path clears a refusal", async () => { const declined = await nextStream(pair.client); expect(await readPublishNamespace(declined)).toBe(Path.from("restarted")); await declinePublishNamespace(declined, 0n); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); wireOf(broadcast).update({ ...wireOf(broadcast).info, instance: Instance.random() }); @@ -1496,7 +1496,7 @@ test("re-announcing a path clears a refusal that forbade retrying", async () => // The broadcast goes away, taking the refusal with it, and a new one takes its place. first.close(); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); publish(origin, Path.from("recycled")); const retried = await nextStream(pair.client); @@ -1572,7 +1572,7 @@ test("an advertisement carries our hop id once the peer declared one", async () async function advanceUntil(clock: Manual, done: () => boolean, limit: number, step = 50) { for (let elapsed = 0; !done(); elapsed += step) { if (elapsed >= limit) throw new Error(`still waiting after ${limit}ms`); - await clock.advance(Nano.fromMilli(Milli(step))); + await clock.advance(Duration.millis(step)); } } @@ -1610,7 +1610,7 @@ function accepted(transport: WebTransport): Stream[] { /** Take the next stream the publisher opened, failing if it has not opened one. */ async function take(clock: Manual, queue: Stream[]): Promise { - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); const stream = queue.shift(); if (!stream) throw new Error("expected the publisher to open a stream"); return stream; @@ -1675,7 +1675,7 @@ test("a price change on a held namespace is one REQUEST_UPDATE, not a withdrawal // Still the one request, still open: nothing was withdrawn or advertised again. const more = watch(stream.reader.done()); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(more.state).toBe("pending"); expect(streams).toHaveLength(0); } finally { @@ -1698,7 +1698,7 @@ test("a hop path change behind the same publisher is one REQUEST_UPDATE carrying await acceptPublishNamespace(stream); const more = watch(stream.reader.done()); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(more.state).toBe("pending"); expect(streams).toHaveLength(0); } finally { @@ -1743,7 +1743,7 @@ test.each([ }); const more = watch(subscription.reader.u53()); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(more.state).toBe("pending"); subscription.close(); } finally { @@ -1770,7 +1770,7 @@ test("a first-hop change is one REQUEST_UPDATE carrying HOP_PATH, not a withdraw await acceptPublishNamespace(stream); const more = watch(stream.reader.done()); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(more.state).toBe("pending"); expect(streams).toHaveLength(0); } finally { @@ -1878,7 +1878,7 @@ test("a foreign route token is not carried", async () => { await acceptClustered(stream); wireOf(broadcast).update({ hops: [VIA], cost: 4n, auth: foreign.issue("second") }); const more = watch(stream.reader.u53()); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(more.state).toBe("pending"); expect(sent).toEqual([undefined]); } finally { @@ -2013,11 +2013,11 @@ test.each([ expect(await stream.reader.done().catch(error)).toMatchObject({ code: StreamCode.Cancel }); // Well past our own backoff, but inside the interval the peer asked for. - await clock.advance(Nano.fromMilli(Milli(9_000))); + await clock.advance(Duration.millis(9_000)); expect(streams).toHaveLength(0); if (retryInterval === 0n) { - await clock.advance(Nano.fromMilli(Milli(20_000))); + await clock.advance(Duration.millis(20_000)); expect(streams).toHaveLength(0); return; } @@ -2082,12 +2082,12 @@ test("a change while an update is unanswered waits for its answer", async () => wireOf(broadcast).update({ hops: [VIA], cost: 12n }); const second = watch(stream.reader.u53()); - await clock.advance(Nano.fromMilli(Milli(1_000))); + await clock.advance(Duration.millis(1_000)); expect(second.state).toBe("pending"); expect(streams).toHaveLength(0); await acceptPublishNamespace(stream); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(second.state).toBe("resolved"); expect(second.value).toBe(PublishNamespaceUpdate.id); expect((await PublishNamespaceUpdate.decode(stream.reader, VERSION)).update).toEqual({ @@ -2115,10 +2115,10 @@ test("an advertisement the peer keeps ending comes back on a growing backoff", a for (const wait of [100, 200, 400, 800]) { await acceptClustered(stream); stream.writer.close(); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); // Just short of the wait, nothing has been offered yet. - await clock.advance(Nano.fromMilli(Milli(wait - 50))); + await clock.advance(Duration.millis(wait - 50)); expect(streams).toHaveLength(0); await advanceUntil(clock, () => streams.length > 0, 10_000); @@ -2147,12 +2147,12 @@ test("an unanswered update drops the request and re-offers the namespace fresh", await readUpdate(stream); const reset = watch(stream.reader.u53()); - await clock.advance(Nano.fromMilli(Milli(9_900))); + await clock.advance(Duration.millis(9_900)); expect(reset.state).toBe("pending"); expect(streams).toHaveLength(0); // The timeout resets the request, then the retry offers it on a new one. - await clock.advance(Nano.fromMilli(Milli(100))); + await clock.advance(Duration.millis(100)); expect(reset.state).toBe("rejected"); await advanceUntil(clock, () => streams.length > 0, 200); const fresh = await take(clock, streams); @@ -3159,7 +3159,7 @@ test.each([0, 1000])("draft-22: FILL_TIMEOUT=%s is ignored for a largest-group f trackName: "video", subscriberPriority: 0, filter: { kind: "nextObject" }, - fill: { filter: { kind: "relative", groups: 1n }, fillTimeout: Milli(timeout), rangeFilters: false }, + fill: { filter: { kind: "relative", groups: 1n }, fillTimeout: timeout, rangeFilters: false }, }), ); try { @@ -3254,7 +3254,7 @@ for (const synchronous of [true, false]) { try { writeGroup(track, 1); await attempted.promise; - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); writeGroup(track, 1); const next = await fx.uni.read(); @@ -3266,7 +3266,7 @@ for (const synchronous of [true, false]) { } finally { client.close(); fx.close(); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); } }); } @@ -3308,7 +3308,7 @@ test("draft-22: PUBLISH_DONE waits for a queued group and counts every stream", // Nothing ends the subscription while the group waits for its slot. const response = client.reader.u53(); - expect(await settlesWithin(response, clock, Milli(20))).toBe(false); + expect(await settlesWithin(response, clock, Duration.millis(20))).toBe(false); slot.resolve(); const served = await nextUni(fx.uni); @@ -3529,7 +3529,7 @@ test("REQUEST_UPDATE applies priority and preserves it when omitted", async () = await RequestOk.decode(client.reader, fx.version); expect(track.subscription.peek()?.priority).toBe(117); // Only the priority changes; retention and the group range survive. - expect(track.subscription.peek()?.delay?.max).toBe(before?.delay?.max); + expect(track.subscription.peek()?.delay?.max).toEqual(before?.delay?.max); expect(track.subscription.peek()?.ranges).toEqual(before?.ranges); await client.writer.write(new Uint8Array([0x02, 0, 2, 4, 0])); expect(await client.reader.u53()).toBe(RequestOk.id); @@ -4334,7 +4334,7 @@ test("draft-22: reported Largest survives absent headers, older cache entries, a expect(ok.largest).toEqual({ groupId: 4n, objectId: 3n }); writeGroup(track, 2); const empty = track.appendGroup(); - await clock.advance(Nano.fromMilli(Milli(60_000))); + await clock.advance(Duration.millis(60_000)); expect(hooks.cachedLargest(track)).toBeUndefined(); const parameters = new Parameters(); parameters.subscriptionFilter = { kind: "absolute", startGroup: 6n, startObject: 0n }; @@ -4786,19 +4786,19 @@ test("subscriber max age and REQUEST_UPDATE preserve omitted preferences", async }), ); try { - expect(track.subscription.peek()?.delay?.max).toBe(Milli(250)); + expect(track.subscription.peek()?.delay?.max).toEqual(Duration.millis(250)); const parameters = new Parameters(); parameters.maxAge = 900; await client.writer.u53(SubscribeUpdate.id); await new SubscribeUpdate({ requestId: 2n, parameters }).encode(client.writer, fx.version); expect(await client.reader.u53()).toBe(RequestOk.id); await RequestOk.decode(client.reader, fx.version); - expect(track.subscription.peek()?.delay?.max).toBe(Milli(900)); + expect(track.subscription.peek()?.delay?.max).toEqual(Duration.millis(900)); await client.writer.u53(SubscribeUpdate.id); await new SubscribeUpdate({ requestId: 4n }).encode(client.writer, fx.version); expect(await client.reader.u53()).toBe(RequestOk.id); await RequestOk.decode(client.reader, fx.version); - expect(track.subscription.peek()?.delay?.max).toBe(Milli(900)); + expect(track.subscription.peek()?.delay?.max).toEqual(Duration.millis(900)); } finally { client.close(); track.finish(); diff --git a/js/net/src/ietf/publisher.ts b/js/net/src/ietf/publisher.ts index 7da764fffef..da971b03935 100644 --- a/js/net/src/ietf/publisher.ts +++ b/js/net/src/ietf/publisher.ts @@ -1,4 +1,4 @@ -import { Instant, Milli, Nano, now, sleep } from "@moq/clock"; +import { Duration, type Instant, now, sleep } from "@moq/clock"; import { type Dispose, type Getter, Once, race, Signal } from "@moq/signals"; import type { Credential, Grant } from "../auth.ts"; import { Gate } from "../auth_gate.ts"; @@ -145,14 +145,14 @@ function sameHops(a: Hop[], b: Hop[]): boolean { * loop just as effectively as one it never grants. */ const ADVERTISE_TIMEOUT_MS = REQUEST_TIMEOUT_MS; -const ADVERTISE_TIMEOUT = Nano.fromMilli(Milli(ADVERTISE_TIMEOUT_MS)); +const ADVERTISE_TIMEOUT = Duration.millis(ADVERTISE_TIMEOUT_MS); /** How long a joining FETCH waits for the subscription it names to arrive and resolve. */ -const JOIN_TIMEOUT = Nano.fromMilli(Milli(REQUEST_TIMEOUT_MS)); +const JOIN_TIMEOUT = Duration.millis(REQUEST_TIMEOUT_MS); /** Sleep `delay`, jittered, so a relay's namespaces don't all retry on the same tick. */ function retryAfter(delay: number): Promise { - return sleep(Nano.fromMilli(Milli(delay * (0.5 + Math.random() / 2)))); + return sleep(Duration.millis(delay * (0.5 + Math.random() / 2))); } /** @@ -161,9 +161,9 @@ function retryAfter(delay: number): Promise { * A peer answers a request it declines with a retry interval, and ignoring it is how a * permanent refusal (unauthorized, uninterested) turns into a request every few seconds * for the life of the session. `"never"` is an interval of 0 or a terminal local failure; - * a number is the epoch milliseconds before which we must not come back. + * an instant is when we may come back. */ -type Refused = "never" | number; +type Refused = "never" | Instant; /** * How the peer answered an advertisement or an update: it holds the namespace, it does @@ -543,7 +543,7 @@ export class Publisher { order: msg.groupOrder, // An absent budget preserves everything retained by the producer. // moq-transport has no field for a minimum. - delay: { max: Milli(msg.maxAge ?? Varint.MAX_U53), min: null }, + delay: { max: Duration.millis(msg.maxAge ?? Varint.MAX_U53), min: null }, ranges: fixed.start ? serveRanges(fixed) : undefined, }), ); @@ -817,7 +817,7 @@ export class Publisher { priority, order, // moq-transport has no field for a minimum. - delay: { max: Milli(msg.maxAge ?? Varint.MAX_U53), min: null }, + delay: { max: Duration.millis(msg.maxAge ?? Varint.MAX_U53), min: null }, ranges: serveRanges(range), }); const startGroup = range.start ? range.start.group : hooks.latestSequence(track); @@ -831,7 +831,7 @@ export class Publisher { // asking the broadcast would mint a second producer nobody has accepted. cache = fill && fill.kind !== "empty" - ? track.fork({ priority, order, delay: { max: Milli(Varint.MAX_U53), min: null } }) + ? track.fork({ priority, order, delay: { max: Duration.millis(Varint.MAX_U53), min: null } }) : undefined; const ranked = new Priority(track, info.priority); @@ -969,7 +969,7 @@ export class Publisher { const maxAge = params.maxAge; if (maxAge !== undefined) { const current = track.subscription.peek(); - track.update({ ...current, delay: { ...current?.delay, max: Milli(maxAge) } }); + track.update({ ...current, delay: { ...current?.delay, max: Duration.millis(maxAge) } }); } // A fill holds one cache view. At most this decoded update waits behind // it; request parsing then backpressures any further fill requests. @@ -1039,7 +1039,7 @@ export class Publisher { ? track.fork({ priority: fromWire(msg.subscriberPriority), order: msg.groupOrder, - delay: { max: Milli(Varint.MAX_U53), min: null }, + delay: { max: Duration.millis(Varint.MAX_U53), min: null }, }) : undefined; try { @@ -1843,7 +1843,7 @@ export class Publisher { ns.active.delete(key); const wait = lapses.get(key)?.wait ?? RETRY_BASE; lapses.set(key, { snap, wait: Math.min(wait * 2, RETRY_MAX) }); - ns.refused.set(key, Instant.add(now(), Nano.fromMilli(Milli(wait)))); + ns.refused.set(key, now().add(Duration.millis(wait))); ns.offered.set(key, snap); } @@ -1998,7 +1998,7 @@ export class Publisher { #offerable(key: Path.Valid, refused: Map): boolean { const entry = refused.get(key); if (entry === undefined) return true; - return entry !== "never" && now() >= entry; + return entry !== "never" && now().ge(entry); } /** @@ -2018,9 +2018,7 @@ export class Publisher { * namespace: 0 means the peer does not want this again. */ #refusal(err: RequestError): Answer { - return err.retryInterval === 0n - ? "never" - : Instant.add(now(), Nano.fromMilli(Milli(toNumber(err.retryInterval)))); + return err.retryInterval === 0n ? "never" : now().add(Duration.millis(toNumber(err.retryInterval))); } /** @@ -2047,7 +2045,7 @@ export class Publisher { // leaving this one namespace unadvertised. let request: RequestStream | undefined; try { - const deadline = new Deadline(Milli(ADVERTISE_TIMEOUT_MS)); + const deadline = new Deadline(Duration.millis(ADVERTISE_TIMEOUT_MS)); const answer = await deadline.wait( (async (): Promise => { const opened = await RequestStream.open(this.#session, deadline, { quic: this.#quic }); @@ -2528,7 +2526,7 @@ export class Publisher { const broadcast = await this.#resolve(named.trackNamespace, signal); const priority = fromWire(msg.subscriberPriority); const track = broadcast.track(named.trackName); - const cache = track.subscribe({ priority, delay: { max: Milli(Varint.MAX_U53), min: null } }); + const cache = track.subscribe({ priority, delay: { max: Duration.millis(Varint.MAX_U53), min: null } }); let answer: FetchAnswer | undefined; try { const info = await untilAborted(cache.info(), signal); @@ -2995,7 +2993,7 @@ function trackProperties(info: Info, wanted: boolean): Properties.Properties { priority: toWire(info.priority), // The publisher's default, newest first. groupOrder: Properties.DESCENDING, - maxCacheDuration: info.maxAge === undefined ? undefined : BigInt(info.maxAge), + maxCacheDuration: info.maxAge === undefined ? undefined : BigInt(info.maxAge.asMillis()), }; } diff --git a/js/net/src/ietf/request_stream.test.ts b/js/net/src/ietf/request_stream.test.ts index 121adbba81e..f249dcb1bd5 100644 --- a/js/net/src/ietf/request_stream.test.ts +++ b/js/net/src/ietf/request_stream.test.ts @@ -1,5 +1,5 @@ import { expect, mock, spyOn, test } from "bun:test"; -import { Manual, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { ProtocolViolation, SessionCode, StreamCode, StreamError } from "../error.ts"; import { manual, settlesWithin } from "../mock.ts"; import { Reader, Stream } from "../stream.ts"; @@ -96,7 +96,7 @@ for (const version of [Version.DRAFT_18, Version.DRAFT_20, Version.DRAFT_22]) { expect(await framed?.reader.u16()).toBe(0); expect(await request.next()).toBeUndefined(); // FIN cancels a draft-18 request; a draft-22 one lasts until reset. - expect(await settlesWithin(request.ended, clock, Milli(10))).toBe(version === Version.DRAFT_18); + expect(await settlesWithin(request.ended, clock, Duration.millis(10))).toBe(version === Version.DRAFT_18); expect(closes).toEqual([]); }); @@ -179,10 +179,10 @@ test("a request's deadline ends it through the request, so later ends do nothing }); const aborts = spyOn(stream, "abort"); const session = { version: Version.DRAFT_18, client: true, openBi: () => stream } as unknown as Session; - const deadline = new Deadline(Milli(REQUEST_TIMEOUT_MS)); + const deadline = new Deadline(Duration.millis(REQUEST_TIMEOUT_MS)); const request = await RequestStream.open(session, deadline); const answer = deadline.wait(new Promise(() => {})).catch((e: unknown) => e); - await clock.advance(Nano.fromMilli(Milli(REQUEST_TIMEOUT_MS))); + await clock.advance(Duration.millis(REQUEST_TIMEOUT_MS)); const err = await answer; expect(err).toBeInstanceOf(StreamError); expect((err as StreamError).code).toBe(StreamCode.ControlTimeout); @@ -214,20 +214,20 @@ test("a request waiting for stream credit outlasts its deadline, which runs from client: true, openBi: () => opening.promise, } as unknown as Session; - const deadline = new Deadline(Milli(REQUEST_TIMEOUT_MS)); + const deadline = new Deadline(Duration.millis(REQUEST_TIMEOUT_MS)); const send = mock((request: RequestStream) => request.writer.u8(1)); const sending = RequestStream.open(session, deadline).then(send); let failure: unknown; const answer = deadline.wait(sending.then(() => new Promise(() => {}))).catch((e: unknown) => { failure = e; }); - await clock.advance(Nano.fromMilli(Milli(2 * REQUEST_TIMEOUT_MS))); + await clock.advance(Duration.millis(2 * REQUEST_TIMEOUT_MS)); expect(failure).toBeUndefined(); opening.resolve(stream); await sending; expect(send).toHaveBeenCalledTimes(1); - await clock.advance(Nano.fromMilli(Milli(REQUEST_TIMEOUT_MS))); + await clock.advance(Duration.millis(REQUEST_TIMEOUT_MS)); await answer; expect(failure).toBeInstanceOf(StreamError); expect((failure as StreamError).code).toBe(StreamCode.ControlTimeout); diff --git a/js/net/src/ietf/request_stream.ts b/js/net/src/ietf/request_stream.ts index 7f04a7e4f2f..0c028073ca6 100644 --- a/js/net/src/ietf/request_stream.ts +++ b/js/net/src/ietf/request_stream.ts @@ -45,7 +45,7 @@ async function writeRefusal(w: Writer, version: IetfVersion, kind: RequestKind, const err = new RequestError({ errorCode, reasonPhrase: refusal.reasonPhrase, - retryInterval: refusal.retryInterval ?? (refusal.retryable && open ? BigInt(RETRY_INITIAL) : 0n), + retryInterval: refusal.retryInterval ?? (refusal.retryable && open ? BigInt(RETRY_INITIAL.asMillis()) : 0n), }); await Message.write(w, RequestError.id, err, version); } diff --git a/js/net/src/ietf/subscriber.test.ts b/js/net/src/ietf/subscriber.test.ts index 1935502beaa..d08cfc36402 100644 --- a/js/net/src/ietf/subscriber.test.ts +++ b/js/net/src/ietf/subscriber.test.ts @@ -1,5 +1,5 @@ import { expect, jest, onTestFinished, spyOn, test } from "bun:test"; -import { Manual, Milli, Nano, yieldNow } from "@moq/clock"; +import { Duration, Manual, yieldNow } from "@moq/clock"; import { Once } from "@moq/signals"; import type * as announce from "../announced.ts"; import { ProtocolViolation, StreamCode, Stream as StreamError } from "../error.ts"; @@ -198,7 +198,7 @@ test("an announcement survives the first of its two sources ending", async () => peer.close(); await handler; - expect(await settlesWithin(announced.next(), clock, Milli(250))).toBe(false); + expect(await settlesWithin(announced.next(), clock, Duration.millis(250))).toBe(false); }); test("announced lists literal matches unless covering asks for overlapping routes too", async () => { @@ -312,11 +312,11 @@ test("an entry buffered past a consumer close does not pin the path", async () = subscription.writer.close(); // Whatever the loop managed to attach, the stream gave back on its way out. - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); const fresh = subscriber.routes(); await acceptSubscribeNamespace(pair.client); - expect(await settlesWithin(fresh.next(), clock, Milli(250))).toBe(false); + expect(await settlesWithin(fresh.next(), clock, Duration.millis(250))).toBe(false); }); /** The Hop IDs a cluster-negotiated session declared, ours first. */ @@ -990,7 +990,7 @@ test.each(["acceptance", "refusal"])("returning demand preserves pending setup u const peer = await nextStream(pair.client); expect(await peer.reader.u53()).toBe(Subscribe.id); await Subscribe.decode(peer.reader, VERSION); - await clock.advance(Nano.fromMilli(Milli(6_000))); + await clock.advance(Duration.millis(6_000)); first.close(); await resumed.promise; if (!returned) throw new Error("demand did not return"); @@ -1008,7 +1008,7 @@ test.each(["acceptance", "refusal"])("returning demand preserves pending setup u expect(returned.closed.peek()).toBeUndefined(); } else { // No answer budget: an hour later the same setup still waits for the publisher. - await clock.advance(Nano.fromMilli(Milli(3_600_000))); + await clock.advance(Duration.millis(3_600_000)); expect(returned.closed.peek()).toBeUndefined(); await peer.writer.u53(RequestError.id); await new RequestError({ errorCode: 0x10, reasonPhrase: "not here" }).encode(peer.writer, VERSION); @@ -1421,7 +1421,10 @@ test.each([ [VERSION, true, [3, 4]], ])("draft %s with FIRST_OBJECT=%s: a header-only stream delivers %p", async (version, firstObject, expected) => { // A budget, so the empty group outlives its successor's arrival. - const { subscriber, track } = await subscribeTrack({ version, subscription: { delay: { max: Milli(60_000) } } }); + const { subscriber, track } = await subscribeTrack({ + version, + subscription: { delay: { max: Duration.millis(60_000) } }, + }); await subscriber.handleGroup( new GroupMessage({ @@ -1851,7 +1854,7 @@ for (const negotiated of [false, true]) { const track = subscriber .consume(Path.from("room")) .track("video") - .subscribe({ delay: { max: Milli(250) } }); + .subscribe({ delay: { max: Duration.millis(250) } }); const peer = await nextStream(pair.client); expect(await peer.reader.u53()).toBe(Subscribe.id); const request = await Subscribe.decode(peer.reader, VERSION); @@ -1860,7 +1863,7 @@ for (const negotiated of [false, true]) { await new SubscribeOk({ trackAlias: ALIAS }).encode(peer.writer, VERSION); await track.info(); // The aggregate can change before SUBSCRIBE_OK: the first update must catch it. - const tolerant = track.fork({ delay: { max: Milli(900) }, priority: 9 }); + const tolerant = track.fork({ delay: { max: Duration.millis(900) }, priority: 9 }); expect(await peer.reader.u53()).toBe(SubscribeUpdate.id); const update = await SubscribeUpdate.decode(peer.reader, VERSION); expect(update.parameters.maxAge).toBe(negotiated ? 900 : undefined); diff --git a/js/net/src/ietf/subscriber.ts b/js/net/src/ietf/subscriber.ts index 0368a398cf7..265beaa793b 100644 --- a/js/net/src/ietf/subscriber.ts +++ b/js/net/src/ietf/subscriber.ts @@ -1,4 +1,4 @@ -import { Milli, yieldNow } from "@moq/clock"; +import { Duration, yieldNow } from "@moq/clock"; import { type Dispose, type GetPromise, type Getter, Once, race, Signal } from "@moq/signals"; import * as announce from "../announced.ts"; import type { Grant } from "../auth.ts"; @@ -1097,7 +1097,7 @@ export class Subscriber { timescale: ok.properties.timescale, priority: fromWire(ok.properties.priority ?? DEFAULT_WIRE), // No MAX_CACHE_DURATION sets no publisher limit, not the authored default. - maxAge: cache === undefined ? null : Milli(Number(cache)), + maxAge: cache === undefined ? null : Duration.millis(Number(cache)), ietf: this.#session.version, }); producer = staged.producer; @@ -1632,7 +1632,7 @@ export class Subscriber { timescale: ok.properties.timescale, priority: fromWire(ok.properties.priority ?? DEFAULT_WIRE), // No MAX_CACHE_DURATION sets no publisher limit, not the authored default. - maxAge: maxCacheDuration === undefined ? null : Milli(Number(maxCacheDuration)), + maxAge: maxCacheDuration === undefined ? null : Duration.millis(Number(maxCacheDuration)), // A moq-transport peer may stamp arrival times, and nothing on the wire says it didn't. ietf: version, }); diff --git a/js/net/src/ietf/tail.test.ts b/js/net/src/ietf/tail.test.ts index 958c2e43323..8f1a868e32e 100644 --- a/js/net/src/ietf/tail.test.ts +++ b/js/net/src/ietf/tail.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Instant, Manual, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { ProtocolViolation, StreamCode, StreamError } from "../error.ts"; import type { Consumer as GroupConsumer } from "../group.ts"; import { hooks } from "../internal.ts"; @@ -61,7 +61,7 @@ async function subscribed(largest?: bigint) { const reader = subscriber .consume(Path.from("room")) .track("video") - .subscribe({ ranges: [{ start: { relative: 0n } }], delay: { max: Milli(60_000) } }); + .subscribe({ ranges: [{ start: { relative: 0n } }], delay: { max: Duration.millis(60_000) } }); const peer = await Stream.accept(pair.client, VERSION); if (!peer) throw new Error("the subscriber never opened a subscribe stream"); @@ -118,7 +118,7 @@ test("a group stream that arrives after PUBLISH_DONE is delivered", async () => })(); await clock.drive(read); // The Stream Count was met, so nothing waited out the grace. - expect(Nano.toMilli(Instant.durationSince(clock.now(), started))).toBeLessThan(GRACE); + expect(clock.now().since(started).lt(GRACE)).toBe(true); }); test("a group read across PUBLISH_DONE is delivered whole", async () => { @@ -154,9 +154,9 @@ test("a Stream Count of 0 is a hint, so a late stream within the grace is still const next = reader.recvGroup().finally(() => { ended = true; }); - await clock.advance(Nano.fromMilli(Milli(GRACE - 1))); + await clock.advance(GRACE.sub(Duration.millis(1))); expect(ended).toBe(false); - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); expect(await next).toBeUndefined(); expect(await reader.closed).toBeNull(); }); diff --git a/js/net/src/index.ts b/js/net/src/index.ts index ddc44c05f06..edd36adcf96 100644 --- a/js/net/src/index.ts +++ b/js/net/src/index.ts @@ -5,6 +5,8 @@ * @module */ +/** Re-export of {@link https://www.npmjs.com/package/@moq/clock | @moq/clock}, the durations, instants, and timers this package takes. */ +export * as Clock from "@moq/clock"; /** Re-export of {@link https://www.npmjs.com/package/@moq/signals | @moq/signals}, the reactive primitives used throughout this package. */ export * as Signals from "@moq/signals"; /** Broadcast announcement streams. */ @@ -35,7 +37,7 @@ export * as Origin from "./origin.ts"; export * as Path from "./path.ts"; /** Point-to-point TCP and track sessions through an origin. */ export * as Socket from "./socket.ts"; -/** Presentation timestamps and their timescales; duration units live in `@moq/clock`. */ +/** Presentation timestamps and their timescales; durations live in {@link Clock}. */ export * as Time from "./time.ts"; /** A value paired with the timestamp it was captured at, absent when untimed. */ export type { Timed } from "./timed.ts"; diff --git a/js/net/src/integers.test.ts b/js/net/src/integers.test.ts index f16b52c4c45..b8ad167b0ee 100644 --- a/js/net/src/integers.test.ts +++ b/js/net/src/integers.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Milli } from "@moq/clock"; + import { ObjectDatagram } from "./ietf/datagram.ts"; import * as Filter from "./ietf/filter.ts"; import { GoAway } from "./ietf/goaway.ts"; @@ -127,10 +127,10 @@ for (const version of [Version.DRAFT_18, Version.DRAFT_20, Version.DRAFT_22]) { expect(() => params.fillTimeout).toThrow(RangeError); expect(() => Filter.decodeFill(fields(version, 1, 0x0a, UNSAFE), version)).toThrow(RangeError); const safe = new Parameters(); - safe.fillTimeout = Milli(Number.MAX_SAFE_INTEGER); + safe.fillTimeout = Number.MAX_SAFE_INTEGER; const bytes = await Writer.collect(version, (w) => safe.encode(w, version)); expect((await Parameters.decode(new Reader(undefined, bytes, version), version)).fillTimeout).toBe( - Milli(Number.MAX_SAFE_INTEGER), + Number.MAX_SAFE_INTEGER, ); }); diff --git a/js/net/src/integration.test.ts b/js/net/src/integration.test.ts index 5c37972039c..ccae1128415 100644 --- a/js/net/src/integration.test.ts +++ b/js/net/src/integration.test.ts @@ -1,5 +1,5 @@ import { afterEach, expect, mock, onTestFinished, spyOn, test } from "bun:test"; -import { Instant, Manual, Milli, Nano, now, yieldNow } from "@moq/clock"; +import { Duration, Manual, now, yieldNow } from "@moq/clock"; import type * as Announce from "./announced.ts"; import { type Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts"; import { @@ -203,14 +203,14 @@ test("integration: lite subscription options and updates reach the publisher", a // A floor of group 1, a concrete group on every draft. const subscriber = remote.track("video").subscribe({ priority: 3, - delay: { max: Milli(250) }, + delay: { max: Duration.millis(250) }, ranges: [{ start: { absolute: 1n }, end: { absolute: 9n } }], }); const producer = await accepted; expect(producer.subscription.peek()).toEqual({ priority: 3, // The negotiated lite-06 cannot state a minimum. - delay: { min: null, max: Milli(250) }, + delay: { min: null, max: Duration.millis(250) }, order: "descending", ranges: [{ start: { absolute: 1n }, end: { absolute: 9n } }], }); @@ -218,12 +218,12 @@ test("integration: lite subscription options and updates reach the publisher", a const updated = producer.subscription.changed(); subscriber.update({ priority: 8, - delay: { max: Milli(500) }, + delay: { max: Duration.millis(500) }, ranges: [{ start: { absolute: 2n }, end: { absolute: 12n } }], }); expect(await updated).toEqual({ priority: 8, - delay: { min: null, max: Milli(500) }, + delay: { min: null, max: Duration.millis(500) }, order: "descending", ranges: [{ start: { absolute: 2n }, end: { absolute: 12n } }], }); @@ -253,14 +253,14 @@ test.each([Ietf.ALPN.DRAFT_22])("integration: %s carries the subscriber max age })(); const remote = wireOf(client).consume(Path.from("test")); - const subscriber = remote.track("video").subscribe({ delay: { max: Milli(250) } }); + const subscriber = remote.track("video").subscribe({ delay: { max: Duration.millis(250) } }); const producer = await accepted; // Without the negotiated parameter the publisher keeps its whole backlog instead. - expect(producer.subscription.peek()?.delay?.max).toBe(Milli(250)); + expect(producer.subscription.peek()?.delay?.max).toEqual(Duration.millis(250)); const updated = producer.subscription.changed(); - subscriber.update({ delay: { max: Milli(500) } }); - expect((await updated)?.delay?.max).toBe(Milli(500)); + subscriber.update({ delay: { max: Duration.millis(500) } }); + expect((await updated)?.delay?.max).toEqual(Duration.millis(500)); subscriber.close(); remote.close(); @@ -303,7 +303,7 @@ test("integration: lite carries a fractional delay as a whole millisecond", asyn // nothing resubscribes. The publisher must see the budget rounded up instead. const subscriber = remote .track("video") - .subscribe({ delay: { max: Milli(38.75) }, ranges: [{ start: { absolute: 1n } }] }); + .subscribe({ delay: { max: Duration.millis(38.75) }, ranges: [{ start: { absolute: 1n } }] }); // A failed subscribe never reaches the publisher, so race its closure to report the // encode error rather than block until the suite times out. @@ -312,11 +312,11 @@ test("integration: lite carries a fractional delay as a whole millisecond", asyn }); const producer = await Promise.race([accepted, failed]); - expect(producer.subscription.peek()?.delay?.max).toBe(Milli(39)); + expect(producer.subscription.peek()?.delay?.max).toEqual(Duration.millis(39)); const updated = producer.subscription.changed(); - subscriber.update({ delay: { max: Milli(500.25) }, ranges: [{ start: { absolute: 1n } }] }); - expect((await Promise.race([updated, failed]))?.delay?.max).toBe(Milli(501)); + subscriber.update({ delay: { max: Duration.millis(500.25) }, ranges: [{ start: { absolute: 1n } }] }); + expect((await Promise.race([updated, failed]))?.delay?.max).toEqual(Duration.millis(501)); subscriber.close(); remote.close(); @@ -353,7 +353,7 @@ test("integration: lite applies initial and updated group bounds", async () => { const subscriber = remote .track("video") .subscribe({ - delay: { max: Milli(REPLAY_LATENCY_MS) }, + delay: { max: Duration.millis(REPLAY_LATENCY_MS) }, ranges: [{ start: { absolute: INITIAL_START_GROUP }, end: { absolute: INITIAL_END_GROUP } }], }) .ordered(); @@ -366,11 +366,11 @@ test("integration: lite applies initial and updated group bounds", async () => { // Replacing the ranges reads on from the same reader, the update going upstream. subscriber.update({ - delay: { max: Milli(REPLAY_LATENCY_MS) }, + delay: { max: Duration.millis(REPLAY_LATENCY_MS) }, ranges: [{ start: { absolute: UPDATED_GROUP }, end: { absolute: UPDATED_END_GROUP } }], }); const updated = (pending: Promise) => - withTimeout(pending, Nano.fromMilli(Milli(UPDATE_TIMEOUT_MS)), "updated group bound timed out"); + withTimeout(pending, Duration.millis(UPDATE_TIMEOUT_MS), "updated group bound timed out"); expect(((await updated(subscriber.nextGroup())) as { sequence: bigint } | undefined)?.sequence).toBe( UPDATED_GROUP, ); @@ -378,10 +378,10 @@ test("integration: lite applies initial and updated group bounds", async () => { // An open range parks at the live edge instead. subscriber.update({ - delay: { max: Milli(REPLAY_LATENCY_MS) }, + delay: { max: Duration.millis(REPLAY_LATENCY_MS) }, ranges: [{ start: { absolute: GROUP_COUNT } }], }); - expect(await settlesWithin(subscriber.nextGroup(), clock, Milli(PENDING_ASSERT_MS))).toBe(false); + expect(await settlesWithin(subscriber.nextGroup(), clock, Duration.millis(PENDING_ASSERT_MS))).toBe(false); } finally { subscriber.close(); remote.close(); @@ -413,38 +413,30 @@ test("integration: lite refuses an empty requested range on open and on update", // Bounds that meet cannot go on the wire: the nearest encoding inverts the range. The read // of an empty window ends at once, and the copy is refused. const empty = video.subscribe({ - delay: { max: Milli(REPLAY_LATENCY_MS) }, + delay: { max: Duration.millis(REPLAY_LATENCY_MS) }, ranges: [{ start: { absolute: 2n }, end: { absolute: 2n } }], }); expect(await empty.recvGroup()).toBeUndefined(); expect( - await withTimeout( - Promise.resolve(empty.closed), - Nano.fromMilli(Milli(TIMEOUT_MS)), - "empty open never settled", - ), + await withTimeout(Promise.resolve(empty.closed), Duration.millis(TIMEOUT_MS), "empty open never settled"), ).toHaveProperty("message", "empty subscription range cannot be encoded"); empty.close(); // A live subscription whose demand later collapses to nothing fails the same way. const live = video .subscribe({ - delay: { max: Milli(REPLAY_LATENCY_MS) }, + delay: { max: Duration.millis(REPLAY_LATENCY_MS) }, ranges: [{ start: { absolute: 1n }, end: { absolute: 2n } }], }) .ordered(); expect((await live.nextGroup())?.sequence).toBe(1n); live.update({ - delay: { max: Milli(REPLAY_LATENCY_MS) }, + delay: { max: Duration.millis(REPLAY_LATENCY_MS) }, ranges: [{ start: { absolute: 3n }, end: { absolute: 3n } }], }); expect(await live.nextGroup()).toBeUndefined(); expect( - await withTimeout( - Promise.resolve(live.closed), - Nano.fromMilli(Milli(TIMEOUT_MS)), - "empty update never settled", - ), + await withTimeout(Promise.resolve(live.closed), Duration.millis(TIMEOUT_MS), "empty update never settled"), ).toHaveProperty("message", "empty subscription range cannot be encoded"); live.close(); } finally { @@ -560,7 +552,7 @@ test("integration: lite-07 keeps a covered bounded subscription open", async () const remote = wireOf(client).consume(Path.from("test")); const bounded = (end: bigint) => remote.track("video").subscribe({ - delay: { max: Milli(60_000) }, + delay: { max: Duration.millis(60_000) }, order: "ascending", ranges: [{ start: { absolute: 1n }, end: { absolute: end } }], }); @@ -686,7 +678,7 @@ test.each([Lite.ALPN_05, Lite.ALPN_06, Lite.ALPN_07_WIP])( const remote = wireOf(client).consume(Path.from("test")); const track = remote.track("video").subscribe().ordered(); expect(await track.readString()).toBe("hello"); - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); // One request, wanted from its subscription on and never let go in between. if (!producer) throw new Error("the track was never answered"); const served = producer; @@ -695,7 +687,7 @@ test.each([Lite.ALPN_05, Lite.ALPN_06, Lite.ALPN_07_WIP])( expect(edges.at(-1)).toBe(true); track.close(); - await withTimeout(unwanted(served.demand()), Nano.fromMilli(Milli(1000)), "demand outlived the reader"); + await withTimeout(unwanted(served.demand()), Duration.millis(1000), "demand outlived the reader"); expect(edges.at(-1)).toBe(false); expect(edges.filter((edge) => edge)).toEqual([true]); @@ -758,7 +750,7 @@ test("integration: lite draft-06 announce lifecycle", async () => { async function announcedUntil(announced: Announce.Routes, until: string) { const seen: string[] = []; while (!seen.includes(until)) { - const entry = await withTimeout(announced.next(), Nano.fromMilli(Milli(1000)), `waiting for ${until}`); + const entry = await withTimeout(announced.next(), Duration.millis(1000), `waiting for ${until}`); if (!entry) throw new Error("announcements ended"); seen.push(entry.prefix); } @@ -918,7 +910,7 @@ test("integration: subscribing to an unserved broadcast is refused as NotFound", broadcast.close(); const track = remote.track("video").subscribe(); - const err = await withTimeout(Promise.resolve(track.closed), Nano.fromMilli(Milli(1000)), "track never closed"); + const err = await withTimeout(Promise.resolve(track.closed), Duration.millis(1000), "track never closed"); expect(err).toBeInstanceOf(StreamError); expect((err as StreamError).code).toBe(StreamCode.NotFound); @@ -946,7 +938,7 @@ test("integration: a peer is served the cheaper route it was offered, not the lo const track = remote.track("video").subscribe(); const { value: request } = await withTimeout( dynamic.requested().next(), - Nano.fromMilli(Milli(1000)), + Duration.millis(1000), "the cheaper route was never asked", ); expect(request?.path).toBe(path); @@ -1190,23 +1182,23 @@ test("integration: lite draft-07 track info follows a republished broadcast", as const path = Path.from("test"); const first = publish(origin, path); - first.createTrack("video", { priority: 1, timescale: Timescale.MILLI, maxAge: Milli(1000) }); + first.createTrack("video", { priority: 1, timescale: Timescale.MILLI, maxAge: Duration.millis(1000) }); const remote = wireOf(client).consume(path); const before = await remote.track("video").info(); expect(before.priority).toBe(1); expect(before.timescale).toBe(Timescale.MILLI); - expect(before.maxAge).toBe(Milli(1000)); + expect(before.maxAge).toEqual(Duration.millis(1000)); // Replace the broadcast on the same path with one whose track declares different // immutable properties. const second = publish(origin, path); - second.createTrack("video", { priority: 7, timescale: Timescale.MICRO, maxAge: Milli(5000) }); + second.createTrack("video", { priority: 7, timescale: Timescale.MICRO, maxAge: Duration.millis(5000) }); const after = await remote.track("video").info(); expect(after.priority).toBe(7); expect(after.timescale).toBe(Timescale.MICRO); - expect(after.maxAge).toBe(Milli(5000)); + expect(after.maxAge).toEqual(Duration.millis(5000)); first.close(); second.close(); @@ -1233,9 +1225,9 @@ test.each([Lite.ALPN_03, Lite.ALPN_05, Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])( const tracks = { omitted: broadcast.createTrack("omitted", { timescale: Timescale.MILLI }), unlimited: broadcast.createTrack("unlimited", { timescale: Timescale.MILLI, maxAge: null }), - explicit: broadcast.createTrack("explicit", { timescale: Timescale.MILLI, maxAge: Milli(5000) }), + explicit: broadcast.createTrack("explicit", { timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }), }; - expect((await tracks.omitted.info()).maxAge).toBe(Milli.zero); + expect((await tracks.omitted.info()).maxAge).toEqual(Duration.ZERO); expect((await tracks.unlimited.info()).maxAge).toBeUndefined(); const remote = wireOf(client).consume(path); @@ -1243,15 +1235,15 @@ test.each([Lite.ALPN_03, Lite.ALPN_05, Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])( // moq-transport answers info through a subscription, so hold one open. const sub = remote.track(name).subscribe(); try { - return await withTimeout(sub.info(), Nano.fromMilli(Milli(5_000)), `${name} info`); + return await withTimeout(sub.info(), Duration.millis(5_000), `${name} info`); } finally { sub.close(); } }; const carried = alpn !== Lite.ALPN_03; - expect((await info("omitted")).maxAge).toBe(carried ? Milli.zero : undefined); + expect((await info("omitted")).maxAge).toEqual(carried ? Duration.ZERO : undefined); expect((await info("unlimited")).maxAge).toBeUndefined(); - expect((await info("explicit")).maxAge).toBe(carried ? Milli(5000) : undefined); + expect((await info("explicit")).maxAge).toEqual(carried ? Duration.millis(5000) : undefined); broadcast.close(); remote.close(); @@ -1645,7 +1637,7 @@ test("integration: lite fetch re-armed by a late reader keeps every frame", asyn group.writeFrame(textFrame("more")); const more = f2.readString(); - expect(`${delay}: ${await settlesWithin(more, clock, Milli(500))}`).toBe(`${delay}: true`); + expect(`${delay}: ${await settlesWithin(more, clock, Duration.millis(500))}`).toBe(`${delay}: true`); expect(await more).toBe("more"); f2.close(); @@ -1744,7 +1736,7 @@ test("integration: a follower waits for a late publisher", async () => { // Nobody publishes this path yet. A blind consume would be reset (see the // "subscribe to non-existent broadcast" test); the handle just stays offline. const watched = clientOrigin.follow(Path.from("late")); - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); expect(watched.active.peek()).toBeUndefined(); // The publisher arrives afterwards. @@ -1903,13 +1895,13 @@ async function runRepublishCycle(protocol: string) { // A dead consumer left in place would still satisfy `!== undefined`, so wait for the swap. const active = await withTimeout( waitFor(watched.active, (b) => b !== undefined && b !== previous), - Nano.fromMilli(Milli(1000)), + Duration.millis(1000), `generation ${generation} never came online`, ); if (!active) throw new Error("expected an active broadcast"); const frame = withTimeout( active.track("audio").subscribe().ordered().readString(), - Nano.fromMilli(Milli(1000)), + Duration.millis(1000), `generation ${generation} never served a frame`, ); expect(await frame).toBe(payload); @@ -1921,7 +1913,7 @@ async function runRepublishCycle(protocol: string) { await serving; await withTimeout( waitFor(watched.active, (b) => b === undefined), - Nano.fromMilli(Milli(1000)), + Duration.millis(1000), `generation ${generation} never ended`, ); expect(watched.closed.peek()).toBeUndefined(); @@ -2057,9 +2049,9 @@ test("integration: ietf blind handle picks up a publisher that arrives late", as /** Poll until `pred` holds, so a regression fails the test instead of hanging it. */ // Yields rather than sleeps, so it also polls under a Manual clock, where only the suite timeout bounds it. async function until(pred: () => boolean): Promise { - const deadline = Instant.add(now(), Nano.fromMilli(Milli(1000))); + const deadline = now().add(Duration.millis(1000)); while (!pred()) { - if (now() > deadline) throw new Error("timed out waiting for condition"); + if (now().gt(deadline)) throw new Error("timed out waiting for condition"); await yieldNow(); } } @@ -2197,7 +2189,7 @@ test("origin: one origin on both directions consumes locally and never echoes", // The critical part: the client must NOT re-announce "from-server" back. If it did, the // server's forwarder would insert it as a remote entry in serverSees. Give the wire a // moment, then check the only remote entry the server has is the client's own broadcast. - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); expect(wireOf(serverReader).routes(Path.from("from-server"))).toBe(false); watchingShared.close(); @@ -2357,7 +2349,7 @@ for (const alpn of [Lite.ALPN_06, Lite.ALPN_07_WIP]) { // The listing leaves. Its announce request stays open for the request beneath it rather // than handing the route to a narrower one, so the instance never changes. listing.close(); - await clock.advance(Nano.fromMilli(Milli(2000))); + await clock.advance(Duration.millis(2000)); expect([started, ended]).toEqual([1, 0]); expect(request.closed.peek()).toBeUndefined(); expect(request.active.peek()).toBe(front); @@ -2367,7 +2359,7 @@ for (const alpn of [Lite.ALPN_06, Lite.ALPN_07_WIP]) { // Once the request goes too, the announce request lingers out. request.close(); - await clock.advance(Nano.fromMilli(Milli(2000))); + await clock.advance(Duration.millis(2000)); expect(ended).toBe(1); broadcast.close(); @@ -2461,7 +2453,7 @@ test("origin: a blind request ends with its session, and the next session answer enabled: true, url: reconnectUrl, websocket: { enabled: false }, - delay: { initial: Milli(10), multiplier: 1, max: Milli(10) }, + delay: { initial: Duration.millis(10), multiplier: 1, max: Duration.millis(10) }, consume: clientOrigin, share: false, }); @@ -2504,7 +2496,7 @@ test("origin: a reactive handle follows announcements across a republish", async const watch = clientOrigin.follow(Path.from("show")); // Nothing published yet: the handle waits instead of subscribing blind. - await clock.advance(Nano.fromMilli(Milli(5))); + await clock.advance(Duration.millis(5)); expect(watch.active.peek()).toBeUndefined(); // The publish resolves it through the wire. @@ -2563,7 +2555,7 @@ test("origin: overlapping sessions carrying one path fail over", async () => { // The newer session dies; the older one still carries the path and must keep serving. second.client.abort(); second.server.abort(); - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); const remote = await routed(reader, Path.from("redundant")); if (!remote) throw new Error("route black-holed despite a live session"); @@ -2830,7 +2822,7 @@ async function runSessionDeath( else pair.server.close({ closeCode: DEATH, reason: "killed" }); const groupEnd = Promise.resolve(group.closed); const closed = await clock.drive( - withTimeout(Promise.resolve(track.closed), Nano.fromMilli(Milli(2000)), "the track never ended"), + withTimeout(Promise.resolve(track.closed), Duration.millis(2000), "the track never ended"), ); broadcast.close(); @@ -2841,7 +2833,7 @@ async function runSessionDeath( origin.close(); return [ closed, - await clock.drive(withTimeout(groupEnd, Nano.fromMilli(Milli(2000)), "the group never ended")), + await clock.drive(withTimeout(groupEnd, Duration.millis(2000), "the group never ended")), hooks.subscriberEnd(track), ]; } @@ -2903,11 +2895,7 @@ test("integration: lite draft-05 ends a track with the publisher's reset", async const reset = StreamCode(70); for (const producer of served) producer.abort(new StreamError(reset)); - const closed = await withTimeout( - Promise.resolve(track.closed), - Nano.fromMilli(Milli(2000)), - "the track never ended", - ); + const closed = await withTimeout(Promise.resolve(track.closed), Duration.millis(2000), "the track never ended"); expect(closed).toBeInstanceOf(StreamError); expect((closed as StreamError).code).toBe(reset); diff --git a/js/net/src/internal.ts b/js/net/src/internal.ts index ae144d4f70f..63464a786e3 100644 --- a/js/net/src/internal.ts +++ b/js/net/src/internal.ts @@ -5,7 +5,7 @@ * * @module */ -import { type Instant, Milli } from "@moq/clock"; +import { Duration, type Instant } from "@moq/clock"; import type { Dispose, GetPromise, Getter } from "@moq/signals"; import type { Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts"; import type { Charge, Pool } from "./cache.ts"; @@ -36,21 +36,21 @@ import * as Varint from "./varint.ts"; import type { Resolved, Window } from "./window.ts"; import type { Advertised, Advertisements } from "./wire.ts"; -/** What a null {@link Delay.max} goes out as: the largest value every peer can read, as Rust sends for `None`. */ -export const NO_MAX_DELAY = Milli(Varint.MAX_U53); +/** What a null {@link Delay.max} goes out as, in milliseconds: the largest value every peer can read, as Rust sends for `None`. */ +export const NO_MAX_DELAY = Varint.MAX_U53; -/** A subscription's {@link Delay.max} as the wire carries it: null for no limit, omitted for zero. */ -export function maxDelayOf(subscription: Pick): Milli { +/** A subscription's {@link Delay.max} in milliseconds as the wire carries it: null for no limit, omitted for zero. */ +export function maxDelayOf(subscription: Pick): number { const max = subscription.delay?.max; if (max === null) return NO_MAX_DELAY; - return max ?? Milli.zero; + return max?.asMillis() ?? 0; } -/** A subscription's {@link Delay.min} as the wire carries it: undefined when not stated, omitted for zero. */ -export function minDelayOf(subscription: Pick): Milli | undefined { +/** A subscription's {@link Delay.min} in milliseconds as the wire carries it: undefined when not stated, omitted for zero. */ +export function minDelayOf(subscription: Pick): number | undefined { const min = subscription.delay?.min; if (min === null) return undefined; - return min ?? Milli.zero; + return min?.asMillis() ?? 0; } /** Normalize public group bounds into an inclusive start and exclusive end. */ @@ -373,7 +373,7 @@ export interface Land { /** Whether the feed was asked to start at `start`: otherwise only from its first arrival. */ floor: boolean; /** How long a gap a later arrival opened is waited for. */ - grace: Milli; + grace: Duration; /** When given, only a group it lacks counts. */ delivered?: Delivered; } @@ -621,7 +621,7 @@ export const hooks: { * How long a session's tail waits for a late group: the subscribers' max delay, bounded by * the track's max age; assigned by `track.ts`. */ - tailGrace: (producer: Producer) => Milli; + tailGrace: (producer: Producer) => Duration; /** Snapshot the latest group sequence for wire positioning; assigned by `track.ts`. */ latestSequence: (subscriber: Subscriber) => bigint | undefined; /** @@ -745,7 +745,7 @@ export const hooks: { /** Wake once a subscriber's group cursor may read differently, including when the track declares its end; assigned by `track.ts`. */ groupChanged: (subscriber: Subscriber, fn: () => void) => Dispose; /** Apply a FETCH reader budget without inheriting SUBSCRIBE's zero default. */ - fetchBudget: (subscriber: Subscriber, maxDelay: Milli | undefined) => void; + fetchBudget: (subscriber: Subscriber, maxDelay: Duration | undefined) => void; /** Whether a reader beyond one-shot fetches subscribes to this copy. */ subscribing: (producer: Producer) => Getter; /** The aggregate across every reader, one-shot fetches included: what the wire asks for. */ diff --git a/js/net/src/ledger.test.ts b/js/net/src/ledger.test.ts index fa14f9ffba0..b0639cd1aaf 100644 --- a/js/net/src/ledger.test.ts +++ b/js/net/src/ledger.test.ts @@ -1,8 +1,8 @@ import { expect, test } from "bun:test"; -import { Instant, Milli, Nano } from "@moq/clock"; +import { Duration, Instant } from "@moq/clock"; import { Ledger } from "./ledger.ts"; -const at = (ms: number) => Instant(Nano.fromMilli(Milli(ms))); +const at = (ms: number) => Instant.ZERO.add(Duration.millis(ms)); test("overlapping and adjacent ranges merge without changing surviving gap ages", () => { const ledger = new Ledger(); @@ -23,7 +23,7 @@ test("overlapping and adjacent ranges merge without changing surviving gap ages" expect(ledger.covers(18n, 18n)).toBe(true); expect(ledger.gaps(6n, 9n)).toEqual([]); expect(ledger.gaps(4n, 6n)).toEqual([{ start: 4n, end: 5n, since: at(10) }]); - ledger.expire(at(110), Milli(100)); + ledger.expire(at(110), Duration.millis(100)); expect(ledger.covers(3n, 16n)).toBe(true); expect(ledger.first()).toBe(3n); ledger.account(16n, 17n, at(110)); @@ -37,12 +37,12 @@ test("demand changes age order and restarts the entire intersecting gap", () => ledger.account(8n, 9n, at(25)); ledger.demand(2n, 3n, at(50)); ledger.account(2n, 3n, at(75)); - ledger.expire(at(125), Milli(100)); + ledger.expire(at(125), Duration.millis(100)); expect(ledger.gaps(0n, 9n)).toEqual([ { start: 1n, end: 2n, since: at(50) }, { start: 3n, end: 4n, since: at(50) }, ]); - ledger.expire(at(150), Milli(100)); + ledger.expire(at(150), Duration.millis(100)); expect(ledger.covers(0n, 9n)).toBe(true); expect(ledger.hasGaps()).toBe(false); }); @@ -52,12 +52,12 @@ test("a leading gap keeps its age until a lower arrival makes it foldable", () = ledger.account(10n, 11n, at(0)); ledger.account(15n, 16n, at(10)); ledger.demand(0n, 5n, at(100)); - ledger.expire(at(110), Milli(100)); + ledger.expire(at(110), Duration.millis(100)); expect(ledger.gaps(0n, 16n)).toEqual([{ start: 0n, end: 10n, since: at(100) }]); ledger.account(0n, 1n, at(150)); - ledger.expire(at(199), Milli(100)); + ledger.expire(at(199), Duration.millis(100)); expect(ledger.covers(0n, 16n)).toBe(false); - ledger.expire(at(200), Milli(100)); + ledger.expire(at(200), Duration.millis(100)); expect(ledger.covers(0n, 16n)).toBe(true); }); @@ -65,15 +65,15 @@ test("changing grace reuses ages without reopening folded gaps", () => { const ledger = new Ledger(); ledger.account(0n, 1n, at(0)); ledger.account(2n, 3n, at(0)); - ledger.expire(at(100), Milli(200)); + ledger.expire(at(100), Duration.millis(200)); expect(ledger.hasGaps()).toBe(true); - ledger.expire(at(100), Milli(50)); + ledger.expire(at(100), Duration.millis(50)); expect(ledger.hasGaps()).toBe(false); ledger.account(4n, 5n, at(100)); - ledger.expire(at(200), Milli(200)); + ledger.expire(at(200), Duration.millis(200)); expect(ledger.gaps(0n, 5n)).toEqual([{ start: 3n, end: 4n, since: at(100) }]); ledger.account(2n, 4n, at(200)); - ledger.expire(at(300), Milli(0)); + ledger.expire(at(300), Duration.millis(0)); expect(ledger.covers(0n, 5n)).toBe(true); }); @@ -81,7 +81,7 @@ test.each([0, 1, 4, 32, 128])("rolling expiration keeps only %i pending gaps", ( const ledger = new Ledger(); for (let arrival = 0; arrival < retained * 4 + 8; arrival++) { ledger.account(BigInt(arrival * 2), BigInt(arrival * 2 + 1), at(arrival)); - ledger.expire(at(arrival), Milli(retained)); + ledger.expire(at(arrival), Duration.millis(retained)); const folded = Math.max(0, arrival - retained) * 2 + 1; expect(ledger.covers(0n, BigInt(folded))).toBe(true); expect(ledger.gaps(0n, BigInt(arrival * 2 + 1)).length).toBe(Math.min(arrival, retained)); @@ -98,7 +98,7 @@ test("shuffled arrivals and bulk merges agree with the accounted sequence set", const end = start + (i < 512 ? 1 : 32); ledger.account(BigInt(start), BigInt(end), at(i)); for (let n = start; n < end; n++) sequences.add(n); - ledger.expire(at(i), Milli(2000)); + ledger.expire(at(i), Duration.millis(2000)); } const gaps = ledger.gaps(0n, 4128n); for (let i = 0; i < 4128; i++) { @@ -107,14 +107,14 @@ test("shuffled arrivals and bulk merges agree with the accounted sequence set", expect(gaps.some((gap) => gap.start <= sequence && sequence < gap.end)).toBe(!sequences.has(i)); } ledger.account(0n, 4128n, at(1024)); - ledger.expire(at(4000), Milli(2000)); + ledger.expire(at(4000), Duration.millis(2000)); expect(ledger.hasGaps()).toBe(false); expect(ledger.covers(0n, 4128n)).toBe(true); }); test("unaccount reopens a gap for a fresh grace", () => { const ledger = new Ledger(); - const grace = Milli(1000); + const grace = Duration.millis(1000); ledger.account(0n, 10n, at(0)); ledger.unaccount(3n, 5n, at(1000)); expect(ledger.covers(0n, 3n) && ledger.covers(5n, 10n)).toBe(true); @@ -128,7 +128,7 @@ test("unaccount reopens a gap for a fresh grace", () => { test("unaccount restarts the older gap it joins", () => { const ledger = new Ledger(); - const grace = Milli(1000); + const grace = Duration.millis(1000); ledger.account(0n, 2n, at(0)); ledger.account(4n, 6n, at(0)); ledger.unaccount(1n, 2n, at(900)); diff --git a/js/net/src/ledger.ts b/js/net/src/ledger.ts index 0044625ba3e..653eed17cfe 100644 --- a/js/net/src/ledger.ts +++ b/js/net/src/ledger.ts @@ -1,4 +1,4 @@ -import { Instant, Milli, Nano } from "@moq/clock"; +import { Duration, Instant } from "@moq/clock"; import * as btree from "sorted-btree"; import { max, min } from "./util/sequence.ts"; @@ -16,11 +16,11 @@ const compare = (a: bigint, b: bigint): number => (a < b ? -1 : a > b ? 1 : 0); * so a stream opened before the end can still be in flight after it. This bounds the wait on * IETF, and on moq-lite when the subscription has no max delay to bound it with. */ -export const GRACE = Milli(1000); +export const GRACE = Duration.millis(1000); /** The grace for a subscription with `delay.max`: how long it was willing to wait for a late group anyway, or {@link GRACE} without one. */ -export function grace(maxDelay: Milli): Milli { - return maxDelay > 0 ? maxDelay : GRACE; +export function grace(maxDelay: Duration): Duration { + return maxDelay.isZero() ? GRACE : maxDelay; } // A run of accounted sequences `[start, end)`, and when the gap below it opened, which is @@ -43,7 +43,7 @@ export class Ledger { #runs = new BTree(undefined, compare); // Demand can restart a gap below an older one. Index ages separately so expiring // one gap never scans all the younger ones. Both indexes own exactly the same runs. - #ages = new BTree(undefined, (a, b) => a.since - b.since || compare(a.start, b.start)); + #ages = new BTree(undefined, (a, b) => a.since.cmp(b.since) || compare(a.start, b.start)); #last?: Run; // Exclude the leading gap, which has no lower run to fold into. #next?: Run; @@ -93,9 +93,8 @@ export class Ledger { } /** Fold every gap at least `grace` old into the runs around it. */ - expire(at: Instant, grace: Milli): void { - const limit = Nano.fromMilli(grace); - while (this.#next && Instant.durationSince(at, this.#next.since) >= limit) { + expire(at: Instant, grace: Duration): void { + while (this.#next && at.since(this.#next.since).ge(grace)) { const run = this.#next; const below = this.#runs.nextLowerPair(run.start)?.[1]; if (!below) throw new Error("an expiring gap must have a lower run"); diff --git a/js/net/src/lite/compression.test.ts b/js/net/src/lite/compression.test.ts index d6d32fb03f8..7796672f536 100644 --- a/js/net/src/lite/compression.test.ts +++ b/js/net/src/lite/compression.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Manual, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { accept } from "../connection/accept.ts"; import { connect } from "../connection/connect.ts"; import { createMockTransportPair } from "../mock.ts"; @@ -43,7 +43,7 @@ for (const downstream of [ALPN_06, ALPN_07_WIP]) { if (!active) throw new Error("broadcast did not resolve"); const remote = active.track("data"); expect((await remote.info()).compress).toBe(downstream === ALPN_07_WIP); - const reader = remote.subscribe({ delay: { max: Milli(1000) } }); + const reader = remote.subscribe({ delay: { max: Duration.millis(1000) } }); const group = track.appendGroup(); const payloads = [new Uint8Array(4096).fill(7), new Uint8Array(), new Uint8Array(4096).fill(7)]; for (const payload of payloads) group.writeFrame({ payload }); @@ -72,7 +72,7 @@ for (const downstream of [ALPN_06, ALPN_07_WIP]) { } finally { for (const origin of [source, destination]) origin.close(); for (const peer of peers) peer.abort(); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); installed.close(); } }); diff --git a/js/net/src/lite/connection.test.ts b/js/net/src/lite/connection.test.ts index 6a9b42928f3..07a69b345eb 100644 --- a/js/net/src/lite/connection.test.ts +++ b/js/net/src/lite/connection.test.ts @@ -1,5 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { Manual, Milli, Nano, yieldNow } from "@moq/clock"; +import { Duration, Manual, yieldNow } from "@moq/clock"; import Qmux from "@moq/qmux"; import { accept } from "../connection/accept.ts"; import { connect } from "../connection/connect.ts"; @@ -113,10 +113,10 @@ test("a lite GOAWAY keeps the session open, and a second one closes it", async ( await sendGoaway(pair.server, ""); const drain = await connection.draining; expect(drain.uri).toBe(""); - expect(await settlesWithin(connection.closed, clock, Milli(20))).toBe(false); + expect(await settlesWithin(connection.closed, clock, Duration.millis(20))).toBe(false); await sendGoaway(pair.server, "https://other.example/"); - expect(await settlesWithin(connection.closed, clock, Milli(50))).toBe(true); + expect(await settlesWithin(connection.closed, clock, Duration.millis(50))).toBe(true); } finally { connection.abort(); } @@ -323,7 +323,7 @@ function qmuxPair(): { client: WebTransport; server: WebTransport } { function mockDeadline() { const clock = new Manual(); return { - expire: () => clock.advance(Nano.fromMilli(Milli(1000))), + expire: () => clock.advance(Duration.millis(1000)), installed: clock.install(), }; } diff --git a/js/net/src/lite/connection.ts b/js/net/src/lite/connection.ts index 5ea2d4a8068..a020837171d 100644 --- a/js/net/src/lite/connection.ts +++ b/js/net/src/lite/connection.ts @@ -1,4 +1,4 @@ -import { Milli, Nano } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { Effect, type GetPromise, type Getter, Once, Signal } from "@moq/signals"; import * as announce from "../announced.ts"; import type * as Auth from "../auth.ts"; @@ -278,7 +278,7 @@ export class Connection implements Established { close(): Promise { this.#closing ??= withTimeout( this.#publisher.drain(), - Nano.fromMilli(Milli(1000)), + Duration.millis(1000), "session close timed out", ).finally(() => this.abort()); return this.#closing; diff --git a/js/net/src/lite/copy_fill.test.ts b/js/net/src/lite/copy_fill.test.ts index 6d1978d8c3c..d36665bfcb0 100644 --- a/js/net/src/lite/copy_fill.test.ts +++ b/js/net/src/lite/copy_fill.test.ts @@ -2,7 +2,7 @@ // lite subscriber's `FillServeRun` does: below where the copy's feed started, by the copy's start // rule, and inside the copy, once it evicted what it received. import { expect, test } from "bun:test"; -import { Elapsed, Manual, Milli, Nano, sleep, timeout } from "@moq/clock"; +import { Duration, Elapsed, Manual, sleep, timeout } from "@moq/clock"; import { DEFAULT_EXPIRY } from "../cache.ts"; import { accept as acceptSession, connect as connectSession } from "../connection/index.ts"; import type { Consumer as GroupConsumer } from "../group.ts"; @@ -92,7 +92,7 @@ async function take(reader: Subscriber, count: number): Promise { try { - (await clock.drive(timeout(Nano.fromMilli(Milli(200)), reader.recvGroup())))?.close(); + (await clock.drive(timeout(Duration.millis(200), reader.recvGroup())))?.close(); return false; } catch (err) { if (err instanceof Elapsed) return true; @@ -102,7 +102,7 @@ async function idle(clock: Manual, reader: Subscriber): Promise { // Groups 0 to 4, one per second: a group is as old as the start of the one after it, so a // reader with a half-second budget starts at group 3, on lite-06 and later. -const NARROW: Subscription = { delay: { max: Milli(500) } }; +const NARROW: Subscription = { delay: { max: Duration.millis(500) } }; const WIDE: Subscription = { delay: { max: null }, order: "ascending" }; function populate(track: Producer): void { @@ -204,7 +204,7 @@ test.each([Lite.ALPN_05, Lite.ALPN_06, Lite.ALPN_07_WIP])( // Both caches age out what nobody touched, a prune slice past the window; only the // live edge stays. - await clock.advance(Nano.fromMilli(Milli(DEFAULT_EXPIRY + 10_000))); + await clock.advance(DEFAULT_EXPIRY.add(Duration.millis(10_000))); write(peer.track.createGroup(4n), 4n, "live"); expect((await first.recvGroup())?.sequence).toBe(4n); const before = peer.fetches(); @@ -346,9 +346,9 @@ test("copy fill: a filled group nobody holds any more stops downloading", async expect((await live.nextGroup())?.sequence).toBe(2n); await clock.drive( timeout( - Nano.fromMilli(Milli(2000)), + Duration.millis(2000), (async () => { - while (hooks.holdsGroup(reader, 0n)) await sleep(Nano.fromMilli(Milli(10))); + while (hooks.holdsGroup(reader, 0n)) await sleep(Duration.millis(10)); })(), ), ); diff --git a/js/net/src/lite/fetch.test.ts b/js/net/src/lite/fetch.test.ts index 4859f9a9243..416cf656145 100644 --- a/js/net/src/lite/fetch.test.ts +++ b/js/net/src/lite/fetch.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Milli } from "@moq/clock"; + import * as Path from "../path.ts"; import { Reader, Writer } from "../stream.ts"; import { Fetch } from "./fetch.ts"; @@ -51,7 +51,7 @@ test("Fetch round-trips on draft-03/04/05", async () => { test("Fetch carries omitted and explicit maxDelay on draft-07", async () => { expect((await roundtrip(Version.DRAFT_07, sample())).maxDelay).toBeUndefined(); - for (const maxDelay of [Milli(0), Milli(250), Milli(Number.MAX_SAFE_INTEGER)]) { + for (const maxDelay of [0, 250, Number.MAX_SAFE_INTEGER]) { const got = await roundtrip( Version.DRAFT_07, new Fetch({ broadcast: Path.from("room/1"), track: "video", priority: 3, maxDelay, group: 42n }), @@ -66,7 +66,7 @@ test("Fetch carries omitted and explicit maxDelay on draft-07", async () => { broadcast: Path.from("room/1"), track: "video", priority: 3, - maxDelay: Milli(250), + maxDelay: 250, group: 42n, }), ), @@ -90,11 +90,10 @@ test("Fetch decodes the optional delay offset before converting to milliseconds" }), ); const decoded = Fetch.decode(new Reader(undefined, encoded, version), version); - if (delay === BigInt(Number.MAX_SAFE_INTEGER)) - expect((await decoded).maxDelay).toBe(Milli(Number.MAX_SAFE_INTEGER)); + if (delay === BigInt(Number.MAX_SAFE_INTEGER)) expect((await decoded).maxDelay).toBe(Number.MAX_SAFE_INTEGER); else await expect(decoded).rejects.toThrow(RangeError); } const unsafe = sample(); - unsafe.maxDelay = Milli(Number.MAX_SAFE_INTEGER + 1); + unsafe.maxDelay = Number.MAX_SAFE_INTEGER + 1; await expect(encode(version, unsafe)).rejects.toThrow(RangeError); }); diff --git a/js/net/src/lite/fetch.ts b/js/net/src/lite/fetch.ts index 75e4741b887..078d4039ca0 100644 --- a/js/net/src/lite/fetch.ts +++ b/js/net/src/lite/fetch.ts @@ -1,4 +1,3 @@ -import type { Milli } from "@moq/clock"; import type * as Instance from "../instance.ts"; import * as Path from "../path.ts"; import type { Reader, Writer } from "../stream.ts"; @@ -24,8 +23,8 @@ export class Fetch { instance?: Instance.Valid; track: string; priority: number; - /** Reader freshness budget. Lite-07+ only; omission leaves the publisher's max age as the only bound. */ - maxDelay?: Milli; + /** Reader freshness budget in whole milliseconds. Lite-07+ only; omission leaves the publisher's max age as the only bound. */ + maxDelay?: number; group: bigint; /** Index of the first frame to return; 0 is the start of the group. Lite-06+. */ @@ -51,7 +50,7 @@ export class Fetch { instance?: Instance.Valid; track: string; priority: number; - maxDelay?: Milli; + maxDelay?: number; group: bigint; startFrame?: number; endFrame?: number; @@ -89,9 +88,7 @@ export class Fetch { const instance = await decodePin(r, version); const track = await r.string(); const priority = fromWire(await r.u8()); - const maxDelay = hasFetchMaxDelay(version) - ? ((await Duration.decodeOptional(r)) as Milli | undefined) - : undefined; + const maxDelay = hasFetchMaxDelay(version) ? await Duration.decodeOptional(r) : undefined; const group = await r.u62(); if (!hasFrameBounds(version)) { diff --git a/js/net/src/lite/publisher.test.ts b/js/net/src/lite/publisher.test.ts index 59ad1f9ac55..59d7ba09138 100644 --- a/js/net/src/lite/publisher.test.ts +++ b/js/net/src/lite/publisher.test.ts @@ -1,5 +1,5 @@ import { expect, mock, spyOn, test } from "bun:test"; -import { Manual, Milli, Nano, yieldNow } from "@moq/clock"; +import { Duration, Manual, yieldNow } from "@moq/clock"; import { Signal } from "@moq/signals"; import type { Grant } from "../auth.ts"; import { Producer as BroadcastProducer } from "../broadcast.ts"; @@ -39,7 +39,7 @@ function publish(origin: OriginProducer, path: Path.Valid) { } // Scheduling tests intentionally stall groups, so keep latency enforcement out of their scope. -const TEST_MAX_DELAY_MS = Milli(30_000); +const TEST_MAX_DELAY_MS = 30_000; function replaySubscribe(props: ConstructorParameters[0]) { return new Subscribe({ ...props, maxDelay: TEST_MAX_DELAY_MS }); @@ -130,7 +130,7 @@ test.each([ }, }), }); - const settle = () => clock.advance(Nano.zero); + const settle = () => clock.advance(Duration.ZERO); const running = publisher.runAnnounce(new AnnounceRequest(Path.empty()), stream); await settle(); const initial = written.length; @@ -168,7 +168,7 @@ test.each([Version.DRAFT_06, Version.DRAFT_07])( }, }), }); - const settle = () => clock.advance(Nano.zero); + const settle = () => clock.advance(Duration.ZERO); const running = publisher.runAnnounce(new AnnounceRequest(Path.empty()), stream); await settle(); const initial = written.length; @@ -232,7 +232,7 @@ async function subscribeEnd( // Let the publisher drain this group before the next, so arrival order is the // order given rather than whatever the cache hands over in one batch. A group that // arrives late opens no stream at all, so there is nothing firmer to wait on. - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); } if (error) track.finishAt({ group: BigInt(Math.max(-1, ...sequences) + 1), frame: 0 }, error); else track.finish(); @@ -412,7 +412,7 @@ test("lite draft-05: a subscribe update re-ranks a group already on the wire", a // The publisher re-ranks from that same signal, so let everything it queued run rather // than depend on the dispatch order between its subscriber and this one. - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(stream.sendOrder).toBe(sendOrder({ priority: 9 })); } finally { @@ -469,7 +469,7 @@ test("lite draft-05: a subscribe update during the stream open still ranks the g if ((await opened.read()).done) throw new Error("publisher never opened the group stream"); opened.releaseLock(); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(pair.server.sendStreams.uni[0]?.sendOrder).toBe(sendOrder({ priority: 9 })); } finally { @@ -525,7 +525,7 @@ test("lite draft-05: many concurrent groups share one subscription listener", as const expected = groups.map((group) => sendOrder({ priority: 9, position: count - 1 - Number(group.sequence) }), ); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(pair.server.sendStreams.uni.map((stream) => stream.sendOrder)).toEqual(expected); } finally { @@ -644,7 +644,7 @@ test("lite draft-06: an unchecked track's fetched frames carry their own timesta // How long a served-subscription test waits on its manual clock for the next group stream // before calling the publisher idle. -const IDLE_MS = Milli(500); +const IDLE_MS = Duration.millis(500); // One macrotask turn, which drains every microtask queued behind it. Signal notifications // are coalesced per microtask, so this is what lets a just-written group reach the serving @@ -702,7 +702,7 @@ async function servedSubscription( endGroup?: bigint; endFrame?: number; gated?: boolean; - maxAge?: Milli; + maxAge?: Duration; // Frame payloads written into every served group. Frame bounds need draft-06. frames?: string[]; version?: Version; @@ -897,7 +897,7 @@ test("lite-07 SUBSCRIBE_START names each resolved range start", async () => { const sub = await servedSubscription({ version, prefill: [0n, 1n, 2n, 3n, 4n], - maxAge: Milli(3_600_000), + maxAge: Duration.millis(3_600_000), ranges: [ { start: { relative: 1n } }, // Group 1 starts at 1 ms. @@ -924,7 +924,7 @@ test("lite-07 SUBSCRIBE_STARTED reports an added range's start, which later upda const sub = await servedSubscription({ version, prefill: [0n, 1n, 2n, 3n, 4n], - maxAge: Milli(3_600_000), + maxAge: Duration.millis(3_600_000), ranges: [{ start: { absolute: 0n }, end: { absolute: 1n } }], }); const next = async () => { @@ -965,7 +965,7 @@ test("lite-07 keeps where an added time start resolved", async () => { const sub = await servedSubscription({ version, prefill: [0n, 1n, 2n, 3n, 4n], - maxAge: Milli(3_600_000), + maxAge: Duration.millis(3_600_000), ranges: [{ start: { absolute: 0n }, end: { absolute: 1n } }], }); const next = async () => { @@ -1006,7 +1006,7 @@ test("lite-07 keeps an added time start that resolved to group 0", async () => { const sub = await servedSubscription({ version, prefill: [0n], - maxAge: Milli(3_600_000), + maxAge: Duration.millis(3_600_000), ranges: [{ start: { absolute: 0n }, end: { absolute: 1n } }], }); const next = async () => { @@ -1059,7 +1059,7 @@ test("lite-07 answers a bounded window that resolves empty and FINs in reply", a const sub = await servedSubscription({ version, prefill: [0n, 1n, 2n, 3n, 4n, 5n], - maxAge: Milli(3_600_000), + maxAge: Duration.millis(3_600_000), ranges: [{ start: { relative: 0n }, end: { absolute: 3n } }], }); try { @@ -1353,9 +1353,13 @@ test("lite draft-06: a reported cut stays dropped when re-created", async () => test("lite draft-06: a group stream that never completes is reset once the group goes stale", async () => { const clock = new Manual(); const installed = clock.install(); - const budget = Milli(1_000); + const budget = 1_000; // The track's max age caps the subscription's budget. - const sub = await servedSubscription({ version: Version.DRAFT_06, startGroup: 0n, maxAge: budget }); + const sub = await servedSubscription({ + version: Version.DRAFT_06, + startGroup: 0n, + maxAge: Duration.millis(budget), + }); try { sub.serve(0n); expect(await sub.servedSequence()).toBe(0n); @@ -1368,14 +1372,14 @@ test("lite draft-06: a group stream that never completes is reset once the group sub.serve(1n); expect(await sub.servedHeader()).toBe(1n); await flush(); - await clock.advance(Nano.fromMilli(Milli(budget * 10))); + await clock.advance(Duration.millis(budget * 10)); expect(reason).toBeUndefined(); sub.serve(2n); expect(await sub.servedSequence()).toBe(2n); - await clock.advance(Nano.fromMilli(Milli(budget - 1))); + await clock.advance(Duration.millis(budget - 1)); expect(reason).toBeUndefined(); - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); await reset; expect(toStreamCode(fromTransport(reason))).toBe(StreamCode.Old); const resp = await decodeSubscribeResponse(sub.client.reader, Version.DRAFT_06); @@ -1394,8 +1398,12 @@ test("lite draft-06: a group stream that never completes is reset once the group test("lite draft-07: an update drops an expired stream again while it is still stale", async () => { const clock = new Manual(); const installed = clock.install(); - const budget = Milli(1_000); - const sub = await servedSubscription({ version: Version.DRAFT_07, startGroup: 0n, maxAge: budget }); + const budget = 1_000; + const sub = await servedSubscription({ + version: Version.DRAFT_07, + startGroup: 0n, + maxAge: Duration.millis(budget), + }); try { sub.serve(0n); expect(await sub.servedSequence()).toBe(0n); @@ -1405,10 +1413,10 @@ test("lite draft-07: an update drops an expired stream again while it is still s sub.serve(1n); expect(await sub.servedHeader()).toBe(1n); await flush(); - await clock.advance(Nano.fromMilli(Milli(budget * 10))); + await clock.advance(Duration.millis(budget * 10)); sub.serve(2n); expect(await sub.servedSequence()).toBe(2n); - await clock.advance(Nano.fromMilli(budget)); + await clock.advance(Duration.millis(budget)); expect(toStreamCode(fromTransport(await reset))).toBe(StreamCode.Old); const first = await decodeSubscribeResponse(sub.client.reader, Version.DRAFT_07); if (!("drop" in first)) throw new Error("expected SUBSCRIBE_DROP"); @@ -1481,8 +1489,12 @@ test("lite draft-07: a group served over a stale drop retires it", async () => { test("lite draft-07: a final drop replaces an expired stream", async () => { const clock = new Manual(); const installed = clock.install(); - const budget = Milli(1_000); - const sub = await servedSubscription({ version: Version.DRAFT_07, startGroup: 0n, maxAge: budget }); + const budget = 1_000; + const sub = await servedSubscription({ + version: Version.DRAFT_07, + startGroup: 0n, + maxAge: Duration.millis(budget), + }); try { sub.serve(0n); expect(await sub.servedSequence()).toBe(0n); @@ -1492,10 +1504,10 @@ test("lite draft-07: a final drop replaces an expired stream", async () => { sub.serve(1n); expect(await sub.servedHeader()).toBe(1n); await flush(); - await clock.advance(Nano.fromMilli(Milli(budget * 10))); + await clock.advance(Duration.millis(budget * 10)); sub.serve(2n); expect(await sub.servedSequence()).toBe(2n); - await clock.advance(Nano.fromMilli(budget)); + await clock.advance(Duration.millis(budget)); expect(toStreamCode(fromTransport(await reset))).toBe(StreamCode.Old); const first = await decodeSubscribeResponse(sub.client.reader, Version.DRAFT_07); if (!("drop" in first)) throw new Error("expected SUBSCRIBE_DROP"); @@ -1530,8 +1542,8 @@ test("lite draft-07: a re-offer dropped again before it opens stays stale at the // before the test writes update 3. const poll = spyOn(Budget.prototype, "poll").mockReturnValue(undefined); // Well inside the cache window, so the expired group is still cached to re-offer. - const budget = Milli(1_000); - const update = (update: bigint, maxDelay: Milli) => + const budget = 1_000; + const update = (update: bigint, maxDelay: number) => new SubscribeUpdate({ priority: 1, startGroup: 0n, @@ -1552,10 +1564,10 @@ test("lite draft-07: a re-offer dropped again before it opens stays stale at the sub.serve(1n); expect(await sub.servedHeader()).toBe(1n); await flush(); - await clock.advance(Nano.fromMilli(Milli(budget * 10))); + await clock.advance(Duration.millis(budget * 10)); sub.serve(2n); expect(await sub.servedSequence()).toBe(2n); - await clock.advance(Nano.fromMilli(budget)); + await clock.advance(Duration.millis(budget)); expect(toStreamCode(fromTransport(await reset))).toBe(StreamCode.Old); const first = await decodeSubscribeResponse(sub.client.reader, Version.DRAFT_07); if (!("drop" in first)) throw new Error("expected SUBSCRIBE_DROP"); @@ -1563,7 +1575,7 @@ test("lite draft-07: a re-offer dropped again before it opens stays stale at the // Update 2 widens the budget, so group 1 is re-offered. Update 3 restores it within the // task the publisher yields after an update, before that re-offer opens. - await update(2n, Milli(budget * 100)); + await update(2n, budget * 100); await flush(); await update(3n, budget); await flush(); @@ -1769,7 +1781,7 @@ for (const skipped of ["failed", "stale"] as const) { const sub = await servedSubscription({ version: Version.DRAFT_06, startGroup: 5n, - maxAge: skipped === "stale" ? Milli(0) : undefined, + maxAge: skipped === "stale" ? Duration.millis(0) : undefined, }); try { hooks.receiveTrack(sub.track); @@ -2184,7 +2196,7 @@ test("lite draft-06: scheduling updates apply while SUBSCRIBE_START is blocked", expect(sub.track.subscription.peek()).toEqual({ priority: 9, // Lite-06 cannot state a minimum. - delay: { min: null, max: TEST_MAX_DELAY_MS }, + delay: { min: null, max: Duration.millis(TEST_MAX_DELAY_MS) }, order: "descending", ranges: [{ end: { absolute: 6n } }], }); @@ -2370,7 +2382,7 @@ test("lite draft-06: an errored end is not declared early", async () => { const start = await decodeSubscribeResponse(client.reader, Version.DRAFT_06); expect("start" in start).toBe(true); const pending = decodeSubscribeResponse(client.reader, Version.DRAFT_06); - expect(await settlesWithin(pending, clock, Milli(20))).toBe(false); + expect(await settlesWithin(pending, clock, Duration.millis(20))).toBe(false); const second = track.createGroup(1n); second.writeFrame(textFrame("hello")); @@ -2648,7 +2660,7 @@ async function serve( // Let the publisher drain each group before the next, so the streams arrive in // the order written rather than whatever the cache hands over in one batch. - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); } track.finish(); track.close(); @@ -2661,7 +2673,7 @@ async function serve( // window. Cancel rather than release below: releasing with a read still pending // would throw. const read = reader.read(); - if (!(await settlesWithin(read, clock, Milli(50)))) break; + if (!(await settlesWithin(read, clock, Duration.millis(50)))) break; const next = await read; if (next.done) break; @@ -2934,7 +2946,7 @@ test("lite draft-05: a group waiting for a stream slot is dropped when the subsc // The slot is kept for the next open, never used to send the dropped group. freeSlot(); - expect(await settlesWithin(outcome, clock, Milli(20))).toBe(false); + expect(await settlesWithin(outcome, clock, Duration.millis(20))).toBe(false); close(); }); @@ -2958,7 +2970,7 @@ test("lite draft-05: a group waiting for a stream slot survives the track finish // The FIN holds until the queued group is on the wire. const fin = client.reader.closed.then(() => "fin" as const); - expect(await settlesWithin(fin, clock, Milli(20))).toBe(false); + expect(await settlesWithin(fin, clock, Duration.millis(20))).toBe(false); freeSlot(); expect(await outcome).toBe("sent"); @@ -3000,11 +3012,11 @@ test("runProbe rounds a fractional smoothedRtt instead of killing the stream", a test("a version without the latency field serves a non-dropping budget", async () => { for (const version of [Version.DRAFT_01, Version.DRAFT_02]) { - const sub = await servedSubscription({ version, maxAge: Milli(Number.MAX_SAFE_INTEGER) }); + const sub = await servedSubscription({ version, maxAge: Duration.millis(Number.MAX_SAFE_INTEGER) }); try { // These drafts decode the absent field as zero. The publisher must not turn // that into a live-edge request the peer never made. - expect(sub.track.subscription.peek()?.delay?.max).toBe(Milli(Number.MAX_SAFE_INTEGER)); + expect(sub.track.subscription.peek()?.delay?.max).toEqual(Duration.millis(Number.MAX_SAFE_INTEGER)); } finally { await sub.close(); } @@ -3173,7 +3185,7 @@ test("lite draft-06: announces wait for the setup grant", async () => { }, }), }); - const settle = () => clock.advance(Nano.zero); + const settle = () => clock.advance(Duration.ZERO); const running = publisher.runAnnounce(new AnnounceRequest(Path.empty()), stream); await settle(); expect(written.length).toBe(0); @@ -3217,7 +3229,7 @@ test("lite draft-06: closing while announces wait for the setup grant does not h }), }); const running = publisher.runAnnounce(new AnnounceRequest(Path.empty()), stream); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); // Without any time passing. expect(await settlesWithin(publisher.drain(), clock)).toBe(true); @@ -3440,7 +3452,7 @@ test("lite draft-07: a fetch whose budget gives up partway resets as too old", a broadcast: Path.from("live"), track: "video", priority: 0, - maxDelay: Milli(500), + maxDelay: 500, group: 0n, }); const serving = publisher.runFetch(msg, server); @@ -3555,11 +3567,11 @@ for (const version of [Version.DRAFT_03, Version.DRAFT_04, Version.DRAFT_05, Ver const serving = publisher.runProbe(server); try { await new ProbeMessage({ bitrate: 4_000_000, rtt: 20 }).encode(client.writer, version); - await clock.advance(Nano.fromMilli(Milli(100))); + await clock.advance(Duration.millis(100)); expect((await ProbeMessage.decode(client.reader, version)).bitrate).toBe(1_000_000); expect(reset).not.toHaveBeenCalled(); client.writer.close(); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(close).toHaveBeenCalled(); } finally { client.close(); @@ -3592,10 +3604,10 @@ for (const version of [Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07]) { server, ); try { - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); // The complete zero-length update cannot hold its required fields. await client.writer.write(new Uint8Array([0])); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(close.mock.calls.some(([info]) => info?.closeCode === SessionCode.ProtocolViolation)).toBe(true); } finally { client.close(); diff --git a/js/net/src/lite/publisher.ts b/js/net/src/lite/publisher.ts index e76ae79f119..dfff42e5b42 100644 --- a/js/net/src/lite/publisher.ts +++ b/js/net/src/lite/publisher.ts @@ -1,4 +1,4 @@ -import { Instant, Milli, Nano, now, sleep, yieldNow } from "@moq/clock"; +import { Duration, Instant, now, sleep, yieldNow } from "@moq/clock"; import { type Dispose, type Getter, Once, race, Signal } from "@moq/signals"; import type { Grant } from "../auth.ts"; import { Gate } from "../auth_gate.ts"; @@ -162,7 +162,7 @@ function trackInfoMessage(info: track.Info, version: Version): TrackInfoMessage refresh: info.refresh, // Publisher Max Age: the publisher's staleness bound, advertised so relays re-serve // with the same bound. - maxAge: info.maxAge, + maxAge: info.maxAge?.asMillis(), // `#serveGroup` emits each frame converted to it. timescale: info.timescale ?? undefined, // An older peer is served the frames inflated. @@ -480,8 +480,8 @@ function waitForControl(controls: SubscriptionControls): Promise { * a legacy subscriber never declined, so fall back to the publisher's max age alone * and leave enforcement to the receiver, as the IETF path does for the same reason. */ -function servingMaxDelay(version: Version, requested: number): Milli | null { - return carriesMaxDelay(version) ? Milli(requested) : null; +function servingMaxDelay(version: Version, requested: number): Duration | null { + return carriesMaxDelay(version) ? Duration.millis(requested) : null; } /** Whether this version's SUBSCRIBE carries Subscriber Max Age at all. */ @@ -990,7 +990,7 @@ export class Publisher { order: msg.order, delay: { max: servingMaxDelay(this.version, msg.maxDelay), - min: msg.minDelay === undefined ? null : Milli(msg.minDelay), + min: msg.minDelay === undefined ? null : Duration.millis(msg.minDelay), }, ranges, }); @@ -1154,7 +1154,7 @@ export class Publisher { order: update.order, delay: { max: servingMaxDelay(this.version, update.maxDelay), - min: update.minDelay === undefined ? null : Milli(update.minDelay), + min: update.minDelay === undefined ? null : Duration.millis(update.minDelay), }, ranges: requestedRanges(update, info.timescale ?? undefined), }); @@ -1282,7 +1282,7 @@ export class Publisher { // FETCH's slot until the requester leaves. group = await front.track(msg.track).fetchGroup(msg.group, { priority: msg.priority, - maxDelay: msg.maxDelay, + maxDelay: msg.maxDelay === undefined ? undefined : Duration.millis(msg.maxDelay), signal: left.signal, }); serving(group); @@ -2531,7 +2531,7 @@ export class Publisher { try { for (;;) { const timer = new AbortController(); - const timeout = sleep(Nano.fromMilli(Milli(PROBE_INTERVAL)), { signal: timer.signal }).then( + const timeout = sleep(Duration.millis(PROBE_INTERVAL), { signal: timer.signal }).then( () => "timeout" as const, () => "timeout" as const, ); @@ -2571,7 +2571,7 @@ export class Publisher { if (lastSent === undefined || lastSentTime === undefined) { shouldSend = true; } else { - const elapsed = Nano.toMilli(Instant.durationSince(now(), lastSentTime)); + const elapsed = now().since(lastSentTime).asMillis(); // The bitrate threshold decays to zero as the last report ages: a // stale estimate is worth refreshing for a smaller move. const t = Math.max(PROBE_INTERVAL, Math.min(PROBE_MAX_AGE, elapsed)); diff --git a/js/net/src/lite/refresh.test.ts b/js/net/src/lite/refresh.test.ts index 15378a82123..74997d325e6 100644 --- a/js/net/src/lite/refresh.test.ts +++ b/js/net/src/lite/refresh.test.ts @@ -1,5 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { Manual, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { accept } from "../connection/accept.ts"; import { connect } from "../connection/connect.ts"; import { createMockTransportPair } from "../mock.ts"; @@ -53,13 +53,13 @@ test.each([ALPN_06, ALPN_07_WIP])("refresh joins reach a browser publisher on %s expect((await received.readFrame())?.payload.length).toBe(3); expect((await received.readFrame())?.payload.length).toBe(3); const joins = [remote.subscribe()]; - await clock.advance(Nano(0)); + await clock.advance(Duration.nanos(0)); expect(producer.demand().wanted.peek()).toBe(0n); updates.length = 0; group.writeFrame({ payload: new Uint8Array(1) }); expect((await received.readFrame())?.payload.length).toBe(1); for (let i = 0; i < 8; i++) joins.push(remote.subscribe()); - await clock.advance(Nano(0)); + await clock.advance(Duration.nanos(0)); if (alpn === ALPN_07_WIP) { while (producer.demand().wanted.peek() !== 1n) await producer.demand().wanted.changed(); } @@ -68,7 +68,7 @@ test.each([ALPN_06, ALPN_07_WIP])("refresh joins reach a browser publisher on %s expect(updates).toEqual(alpn === ALPN_07_WIP ? [1n] : []); // A parameter change restates the wanted group rather than clearing it. joins.push(remote.subscribe({ priority: 9 })); - await clock.advance(Nano(0)); + await clock.advance(Duration.nanos(0)); expect(updates).toEqual(alpn === ALPN_07_WIP ? [1n, 1n] : []); for (const join of joins) join.close(); received.close(); @@ -78,7 +78,7 @@ test.each([ALPN_06, ALPN_07_WIP])("refresh joins reach a browser publisher on %s spy.mockRestore(); for (const origin of [b, source]) origin.close(); for (const peer of peers) peer.abort(); - await clock.advance(Nano(0)); + await clock.advance(Duration.nanos(0)); installed.close(); } }); diff --git a/js/net/src/lite/subscriber.test.ts b/js/net/src/lite/subscriber.test.ts index 1ba82234abc..a938276babb 100644 --- a/js/net/src/lite/subscriber.test.ts +++ b/js/net/src/lite/subscriber.test.ts @@ -1,5 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { Elapsed, Manual, Milli, Nano, timeout, yieldNow } from "@moq/clock"; +import { Duration, Elapsed, Manual, timeout, yieldNow } from "@moq/clock"; import { type Getter, Signal } from "@moq/signals"; import type { Grant } from "../auth.ts"; import type { AuthSession } from "../auth_session.ts"; @@ -140,7 +140,7 @@ function announceHarness(version: Version, origin = 1n) { // than hang it out to the suite timeout. const abortReason = async () => { try { - return reason(error(await timeout(Nano.fromMilli(Milli(250)), aborted))); + return reason(error(await timeout(Duration.millis(250), aborted))); } catch (error) { if (error instanceof Elapsed) throw new Error("stream was never aborted"); throw error; @@ -150,7 +150,7 @@ function announceHarness(version: Version, origin = 1n) { // Rejects promptly if the session outlives the violation, rather than hanging the test. const sessionEnded = async () => { try { - return await timeout(Nano.fromMilli(Milli(250)), sessionClosed); + return await timeout(Duration.millis(250), sessionClosed); } catch (error) { if (error instanceof Elapsed) throw new Error("session was never closed"); throw error; @@ -595,10 +595,10 @@ test("an RTT retraction clears the reading on lite-04+", async () => { // Seeded rather than sent, because lite-03 has no way to put one on the wire. test("lite-03 keeps an existing RTT, since its PROBE cannot carry one", async () => { const got = await runProbeScript(Version.DRAFT_03, [new Probe({ bitrate: 2_000_000 })], { - rtt: Milli(40), + rtt: Duration.millis(40), }); expect(got.estimatedRecvRate).toBe(2_000_000); - expect(got.rtt).toBe(Milli(40)); + expect(got.rtt).toEqual(Duration.millis(40)); }); test("an announce skipped as a reflected loop still holds its path", async () => { @@ -1121,7 +1121,7 @@ test.each([ await opened(0); await streams[0].reading; - await clock.advance(Nano.fromMilli(Milli(3_600_000))); + await clock.advance(Duration.millis(3_600_000)); expect(track.closed.peek()).toBeUndefined(); track.close(); @@ -1161,7 +1161,7 @@ test("a lite subscribe waiting on a stream slot for the SUBSCRIBE outlasts the d await answerTrackInfo(streams[0]); await opened(1); - await clock.advance(Nano.fromMilli(Milli(3_600_000))); + await clock.advance(Duration.millis(3_600_000)); expect(track.closed.peek()).toBeUndefined(); streams[1].release(); @@ -1277,7 +1277,7 @@ test("a lite subscribe abandoned while its SUBSCRIBE write stalls closes its TRA await answerTrackInfo(streams[0]); await (await opened(1)).writing; - await clock.advance(Nano.fromMilli(Milli(3_600_000))); + await clock.advance(Duration.millis(3_600_000)); expect(track.closed.peek()).toBeUndefined(); track.close(); await streams[0].finished; @@ -1302,7 +1302,7 @@ test.each( const track = subscriber .consume(Path.from("room")) .track("video") - .subscribe({ priority: 3, delay: { max: Milli(10_000) } }); + .subscribe({ priority: 3, delay: { max: Duration.millis(10_000) } }); try { await opened(0); await streams[0].reading; @@ -1325,7 +1325,7 @@ test.each( await track.info(); await request.reading; // An explicit change orders after any update caused by TRACK_INFO, even if its encoding yields. - track.update({ priority: 4, delay: { max: Milli(10_000) } }); + track.update({ priority: 4, delay: { max: Duration.millis(10_000) } }); const update = await SubscribeUpdate.decode(subscribe, version); expect([update.priority, update.maxDelay]).toEqual([4, 10_000]); track.close(); @@ -2482,7 +2482,7 @@ test.each([Version.DRAFT_05, Version.DRAFT_06])("version %p passes received time const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); const broadcast = subscriber.consume(Path.from("room")); // Old enough to keep every group, however far behind the newest start. - const track = broadcast.track("video").subscribe({ delay: { max: Milli(60_000) } }); + const track = broadcast.track("video").subscribe({ delay: { max: Duration.millis(60_000) } }); try { await opened(0); await answerTrackInfo(streams[0], version, 1000); @@ -2518,7 +2518,7 @@ test("a lite-07 rewind is refused", async () => { const { quic, streams, opened } = fakeSession(); const subscriber = new Subscriber(quic, version, HopSchema.parse(1n)); const broadcast = subscriber.consume(Path.from("room")); - const track = broadcast.track("video").subscribe({ delay: { max: Milli(60_000) } }); + const track = broadcast.track("video").subscribe({ delay: { max: Duration.millis(60_000) } }); try { await opened(0); await answerTrackInfo(streams[0], version, 1000); @@ -2632,7 +2632,7 @@ test("a group wins over its stale drop on lite-07", async () => { return runResponses(stream, captured); }); const broadcast = subscriber.consume(Path.from("room")); - const track = broadcast.track("video").subscribe({ delay: { max: Milli(500) } }); + const track = broadcast.track("video").subscribe({ delay: { max: Duration.millis(500) } }); try { await opened(0); await answerTrackInfo(streams[0], version); @@ -2674,7 +2674,7 @@ test("a group wins over its stale drop on lite-07", async () => { await send(old(4n)); if (!entry) throw new Error("no subscription"); - track.update({ priority: 1, delay: { max: Milli(500) } }); + track.update({ priority: 1, delay: { max: Duration.millis(500) } }); await drainReactions(); // Every group that arrived stays accounted for; the one that never arrived is owed again. expect(entry.tail.covers(1n, 4n)).toBe(true); @@ -2718,7 +2718,7 @@ test("a finished group wins over a late stale drop once evicted on lite-07", asy return runResponses(stream, captured); }); const broadcast = subscriber.consume(Path.from("room")); - const track = broadcast.track("video").subscribe({ delay: { max: Milli(500) } }); + const track = broadcast.track("video").subscribe({ delay: { max: Duration.millis(500) } }); try { await opened(0); await answerTrackInfo(streams[0], version); @@ -2744,10 +2744,10 @@ test("a finished group wins over a late stale drop once evicted on lite-07", asy new Reader(new ReadableStream({ start: (controller) => controller.close() }), undefined, version), ); // Everything below the live edge ages out of the cache. - const evict = () => clock.advance(Nano.fromMilli(Milli(2 * DEFAULT_EXPIRY))); + const evict = () => clock.advance(DEFAULT_EXPIRY.mul(2)); let priority = 0; const update = async () => { - track.update({ priority: ++priority, delay: { max: Milli(500) } }); + track.update({ priority: ++priority, delay: { max: Duration.millis(500) } }); await drainReactions(); }; @@ -2794,7 +2794,7 @@ test("a skip or final drop replaces an earlier stale one on lite-07", async () = return runResponses(stream, captured); }); const broadcast = subscriber.consume(Path.from("room")); - const track = broadcast.track("video").subscribe({ delay: { max: Milli(500) } }); + const track = broadcast.track("video").subscribe({ delay: { max: Duration.millis(500) } }); try { await opened(0); await answerTrackInfo(streams[0], version); @@ -2824,7 +2824,7 @@ test("a skip or final drop replaces an earlier stale one on lite-07", async () = await drainReactions(); if (!entry) throw new Error("no subscription"); - track.update({ priority: 1, delay: { max: Milli(500) } }); + track.update({ priority: 1, delay: { max: Duration.millis(500) } }); await drainReactions(); expect(entry.tail.covers(1n, 3n)).toBe(true); expect(entry.tail.covers(4n, 5n)).toBe(true); @@ -2857,7 +2857,7 @@ test("a skip replaces a final drop but not a cached group on lite-07", async () }); const warn = spyOn(console, "warn").mockImplementation(() => {}); const broadcast = subscriber.consume(Path.from("room")); - const track = broadcast.track("video").subscribe({ delay: { max: Milli(500) } }); + const track = broadcast.track("video").subscribe({ delay: { max: Duration.millis(500) } }); try { await opened(0); await answerTrackInfo(streams[0], version); @@ -2938,7 +2938,7 @@ test.each( streams[0].inbound.close(); await drainReactions(); - await clock.advance(Nano.fromMilli(GRACE)); + await clock.advance(GRACE); expect(await track.finished()).toEqual({ group: 0n, frame: 0 }); expect(await track.closed).toBeNull(); expect(closes).toEqual([]); @@ -3272,14 +3272,14 @@ test.each(["answer", "credit"] as const)("FETCH waiting for %s ends with its cal await answerTrackInfo(streams[0], Version.DRAFT_07); await opened(1); if (stage === "answer") await streams[1].reading; - await clock.advance(Nano.fromMilli(Milli(3_600_000))); + await clock.advance(Duration.millis(3_600_000)); expect(failure).toBeUndefined(); const reason = new Error("left"); cancel.abort(reason); await fetch; expect(failure).toBe(reason); // Credit granted once the caller has left can't send the FETCH. - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); if (stage === "credit") streams[1].release(); if (stage === "credit") { await drainReactions(); @@ -3382,7 +3382,7 @@ test("the PROBE stream sends the viewers' target to an Increase peer", async () // Reading the target back only proves its bytes were written: the writer may still be // yielding its write budget, and a FIN then would reset the stream instead of closing it. - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); finish(); await running; expect(await sent.done()).toBe(true); @@ -3448,7 +3448,7 @@ test("a stalled PROBE writer sends only the latest target once it drains", async expect((await Probe.decode(sent, version)).bitrate).toBe(4_000_000); // Let the last write finish yielding before the FIN, as in the test above. - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); finish(); await running; expect(await sent.done()).toBe(true); diff --git a/js/net/src/lite/subscriber.ts b/js/net/src/lite/subscriber.ts index e9cadb87e98..1a05d3d7079 100644 --- a/js/net/src/lite/subscriber.ts +++ b/js/net/src/lite/subscriber.ts @@ -1,4 +1,4 @@ -import { Milli, yieldNow } from "@moq/clock"; +import { Duration, yieldNow } from "@moq/clock"; import { type Dispose, Effect, type GetPromise, type Getter, race, Signal } from "@moq/signals"; import * as announce from "../announced.ts"; import type { Grant } from "../auth.ts"; @@ -1698,7 +1698,7 @@ export class Subscriber { timescale: info.timescale, // Publisher Max Age rides on the wire, so the local media-time budget // matches what the upstream advertises (relays re-serve with the same bound). - maxAge: info.maxAge === undefined ? undefined : Milli(info.maxAge), + maxAge: info.maxAge === undefined ? undefined : Duration.millis(info.maxAge), priority: info.priority, refresh: info.refresh, compress: info.compress, @@ -1750,7 +1750,14 @@ export class Subscriber { // Different freshness budgets use independent streams: once a FETCH is on the // wire its limit cannot be widened for a later, more tolerant caller. Equal // budgets still coalesce and each caller keeps an independent mirror. - const key = JSON.stringify([consumed.id, broadcast, instance, track, String(sequence), options.maxDelay]); + const key = JSON.stringify([ + consumed.id, + broadcast, + instance, + track, + String(sequence), + options.maxDelay?.asNanos(), + ]); let entry = this.#fetches.get(key); let consumer: netGroup.Consumer; if (entry && !entry.group.isClosed) { @@ -1795,7 +1802,7 @@ export class Subscriber { sequence: bigint, priority: number, group: netGroup.Producer, - maxDelay?: Milli, + maxDelay?: Duration, ): Promise { const refused = unauthorized(broadcast); try { @@ -1856,7 +1863,7 @@ export class Subscriber { priority: number, group: netGroup.Producer, deadline: Deadline, - maxDelay?: Milli, + maxDelay?: Duration, ): Promise<{ stream: Stream; info: TrackInfo }> { const { instance, valid } = consumed; const cancel = new AbortController(); @@ -1879,7 +1886,8 @@ export class Subscriber { instance, track, priority, - maxDelay: hasFetchMaxDelay(this.version) ? maxDelay : undefined, + maxDelay: + hasFetchMaxDelay(this.version) && maxDelay !== undefined ? Math.ceil(maxDelay.asMillis()) : undefined, group: sequence, }).encode(stream.writer, this.version); // A byte or an empty-group FIN accepts the fetch; a reset rejects it. @@ -2030,7 +2038,9 @@ export class Subscriber { for (;;) { const priority = fill.priority; // Lite-07 FETCH carries the budget; older ones leave it to the publisher's max age. - const maxDelay = hasFetchMaxDelay(this.version) ? (fill.maxDelay ?? undefined) : undefined; + const budget = fill.maxDelay; + // Rounded up, since a budget shortened by rounding skips a group a reader still wants. + const maxDelay = hasFetchMaxDelay(this.version) && budget !== null ? Math.ceil(budget.asMillis()) : undefined; try { // Wait for the grant as a subscribe or fetch does; nobody waiting ends the wait. while ( @@ -2066,7 +2076,8 @@ export class Subscriber { ); } catch (err) { if (cancel.aborted || !fill.isWanted(sequence)) return undefined; - if (maxDelay !== undefined && (fill.maxDelay ?? Number.POSITIVE_INFINITY) > maxDelay) continue; + if (maxDelay !== undefined && (fill.maxDelay?.asMillis() ?? Number.POSITIVE_INFINITY) > maxDelay) + continue; fill.refuseGroups(sequence, sequence + 1n, error(err)); return undefined; } @@ -2301,7 +2312,10 @@ export class Subscriber { let lastSent: track.Subscription = { priority: msg.priority, order: msg.order, - delay: { max: Milli(msg.maxDelay), min: msg.minDelay === undefined ? null : Milli(msg.minDelay) }, + delay: { + max: Duration.millis(msg.maxDelay), + min: msg.minDelay === undefined ? null : Duration.millis(msg.minDelay), + }, ranges: entry.asked, }; @@ -2721,7 +2735,7 @@ export class Subscriber { if (!probe) break; // Lite-03 carries no RTT; newer drafts retract it with a zero. const prev = this.#probe.peek(); - const rtt = probe.rtt !== undefined ? Milli(probe.rtt) : undefined; + const rtt = probe.rtt !== undefined ? Duration.millis(probe.rtt) : undefined; this.#probe.set({ // `undefined` is the peer reporting "unknown"; a 0 would become a real ABR target. estimatedRecvRate: probe.bitrate, diff --git a/js/net/src/lite/tail.test.ts b/js/net/src/lite/tail.test.ts index b092bcc583d..4b3f6b81059 100644 --- a/js/net/src/lite/tail.test.ts +++ b/js/net/src/lite/tail.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { Manual, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { ProtocolViolation, StreamCode, StreamError } from "../error.ts"; import type { Consumer as GroupConsumer } from "../group.ts"; import { randomHop } from "../hop.ts"; @@ -26,7 +26,7 @@ import { TrackInfo, Track as TrackMessage } from "./track.ts"; import { ALPN_05, hasRanges, resolvesStart, Version } from "./version.ts"; // The subscription's max delay, which is also how long it waits for a group that never arrives. -const GRACE = Milli(100); +const GRACE = Duration.millis(100); /** One lite-05+ frame: a zero timestamp delta, then the length-prefixed payload. */ function frame(payload: string): Uint8Array { @@ -225,7 +225,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver // QUIC does not order streams, so a lower group's stream can land after a higher one and // after SUBSCRIBE_FINISH. The reader receives it before its end, which then comes at once. test("a lower group that lands after SUBSCRIBE_FINISH reaches the reader", async () => { - const { subscriber, reader, respond, fin } = await subscribed(version, Milli(60_000)); + const { subscriber, reader, respond, fin } = await subscribed(version, Duration.millis(60_000)); await respond({ start: new SubscribeStart([0n]) }); const high = groupStream(subscriber, 1n); high.finish(); @@ -254,7 +254,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver test("a subscription ends without waiting once every group is accounted for", async () => { using clock = manual(); // A max delay far past the test's patience: only the accounting may end it. - const { subscriber, reader, respond, fin } = await subscribed(version, Milli(60_000)); + const { subscriber, reader, respond, fin } = await subscribed(version, Duration.millis(60_000)); await respond({ start: new SubscribeStart([0n]) }); await respond({ drop: new SubscribeDrop({ start: 0n, end: 0n, error: 0 }) }); const group = groupStream(subscriber, 1n); @@ -264,14 +264,14 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver await fin(); expect((await reader.recvGroup())?.sequence).toBe(1n); - expect(await settlesWithin(reader.recvGroup(), clock, Milli(1000))).toBe(true); + expect(await settlesWithin(reader.recvGroup(), clock, Duration.millis(1000))).toBe(true); expect(await reader.closed).toBeNull(); }); // Lite-07 carries a stream error code; earlier versions an application one, so the same // bytes read as OLD there. test("a SUBSCRIBE_DROP ends a group still arriving, before the FIN", async () => { - const { subscriber, reader, respond } = await subscribed(version, Milli(60_000)); + const { subscriber, reader, respond } = await subscribed(version, Duration.millis(60_000)); await respond({ start: new SubscribeStart([0n]) }); const arriving = groupStream(subscriber, 0n); arriving.write("0.0"); @@ -298,11 +298,11 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver test("a subscription that served nothing ends at SUBSCRIBE_FINISH", async () => { using clock = manual(); - const { reader, respond, fin } = await subscribed(version, Milli(60_000)); + const { reader, respond, fin } = await subscribed(version, Duration.millis(60_000)); await respond({ finish: new SubscribeFinish(0n) }); await fin(); - expect(await settlesWithin(reader.recvGroup(), clock, Milli(1000))).toBe(true); + expect(await settlesWithin(reader.recvGroup(), clock, Duration.millis(1000))).toBe(true); expect(await reader.closed).toBeNull(); expect(hooks.subscriberEnd(reader)).toEqual({ group: 0n, frame: 0 }); }); @@ -318,7 +318,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver const handled = groupStream(subscriber, 2n).handled; if (version === Version.DRAFT_05) { await handled; - expect(await settlesWithin(Promise.resolve(reader.closed), clock, Milli(50))).toBe(false); + expect(await settlesWithin(Promise.resolve(reader.closed), clock, Duration.millis(50))).toBe(false); } else { // The violation escapes to the connection, which closes the session on it. expect( @@ -333,7 +333,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver test("a floor below SUBSCRIBE_START owes nothing below it", async () => { using clock = manual(); - const { subscriber, reader, respond, fin } = await subscribed(version, Milli(60_000), { + const { subscriber, reader, respond, fin } = await subscribed(version, Duration.millis(60_000), { start: { absolute: 1n }, }); await respond({ start: new SubscribeStart([3n]) }); @@ -344,13 +344,13 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver await fin(); expect((await reader.recvGroup())?.sequence).toBe(3n); - expect(await settlesWithin(reader.recvGroup(), clock, Milli(1000))).toBe(true); + expect(await settlesWithin(reader.recvGroup(), clock, Duration.millis(1000))).toBe(true); expect(await reader.closed).toBeNull(); }); test("a lowered floor owes the groups it newly asked for", async () => { using clock = manual(); - const maxDelay = Milli(60_000); + const maxDelay = Duration.millis(60_000); const { subscriber, respond, update, fin } = await subscribed(version, maxDelay, { start: { absolute: 3n }, }); @@ -374,7 +374,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver await respond({ finish: new SubscribeFinish(4n) }); await fin(); // Long enough for a subscription that owed nothing more to have ended. - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); // QUIC does not order streams, so the lowered groups land after the FIN. for (const sequence of [1n, 2n]) { @@ -418,7 +418,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver test("lite-07 settles a skipped group with SUBSCRIBE_DROP", async () => { using clock = manual(); - const { subscriber, reader, respond, fin } = await subscribed(Version.DRAFT_07, Milli(60_000)); + const { subscriber, reader, respond, fin } = await subscribed(Version.DRAFT_07, Duration.millis(60_000)); await respond({ start: new SubscribeStart([0n]) }); for (const sequence of [0n, 2n]) { const group = groupStream(subscriber, sequence); @@ -432,19 +432,19 @@ test("lite-07 settles a skipped group with SUBSCRIBE_DROP", async () => { expect((await reader.recvGroup())?.sequence).toBe(0n); expect((await reader.recvGroup())?.sequence).toBe(2n); - expect(await settlesWithin(reader.recvGroup(), clock, Milli(1000))).toBe(true); + expect(await settlesWithin(reader.recvGroup(), clock, Duration.millis(1000))).toBe(true); expect(await reader.closed).toBeNull(); }); test("lite-07 settles a dropped range without grace", async () => { using clock = manual(); - const { reader, respond, fin } = await subscribed(Version.DRAFT_07, Milli(60_000)); + const { reader, respond, fin } = await subscribed(Version.DRAFT_07, Duration.millis(60_000)); await respond({ start: new SubscribeStart([0n]) }); await respond({ finish: new SubscribeFinish(3n) }); await respond({ drop: new SubscribeDrop({ start: 0n, end: 2n, error: 0 }) }); await fin(); - expect(await settlesWithin(reader.recvGroup(), clock, Milli(1000))).toBe(true); + expect(await settlesWithin(reader.recvGroup(), clock, Duration.millis(1000))).toBe(true); expect(await reader.closed).toBeNull(); expect(hooks.subscriberEnd(reader)).toEqual({ group: 3n, frame: 0 }); }); @@ -469,7 +469,10 @@ test("a subscribe stream reset preserves the publisher's failure", async () => { }); test("lite-07 FIN waits for the skipped and reset final range to settle", async () => { - const { subscriber, reader, respond, fin, subscriberFin } = await subscribed(Version.DRAFT_07, Milli(60_000)); + const { subscriber, reader, respond, fin, subscriberFin } = await subscribed( + Version.DRAFT_07, + Duration.millis(60_000), + ); await respond({ start: new SubscribeStart([0n]) }); const first = groupStream(subscriber, 0n); first.finish(); diff --git a/js/net/src/lite/track.test.ts b/js/net/src/lite/track.test.ts index c35c728589f..ee897891404 100644 --- a/js/net/src/lite/track.test.ts +++ b/js/net/src/lite/track.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { ProtocolViolation } from "../error.ts"; import * as Path from "../path.ts"; import { Reader, Writer } from "../stream.ts"; @@ -52,7 +52,7 @@ test("TrackInfo for Rust's default Info matches cross-language wire bytes", asyn // The default authored track is untimed, which lite-05 declares as milliseconds, and // advertises the default zero max age. const model = authoredInfo(); - const info = new TrackInfo({ ...model, timescale: model.timescale ?? undefined }); + const info = new TrackInfo({ ...model, maxAge: model.maxAge?.asMillis(), timescale: model.timescale ?? undefined }); expect(await bytes((w) => info.encode(w, Version.DRAFT_05), Version.DRAFT_05)).toEqual( new Uint8Array([0x05, 0x80, 0x00, 0x00, 0x43, 0xe8]), ); @@ -197,9 +197,9 @@ for (const version of [Version.DRAFT_05, Version.DRAFT_06]) { await old.u53(); // message length await old.u8(); // priority if (version === Version.DRAFT_05) await old.bool(); - const maxAge = Milli(await old.u53()); - expect(maxAge).toBe(Milli(Number.MAX_SAFE_INTEGER)); - expect(infoDefaults({ maxAge }).maxAge).toBe(maxAge); + const maxAge = Duration.millis(await old.u53()); + expect(maxAge).toEqual(Duration.millis(Number.MAX_SAFE_INTEGER)); + expect(infoDefaults({ maxAge }).maxAge).toEqual(maxAge); expect(await old.u53()).toBe(1000); }); test(`legacy unlimited range decodes without unsafe numeric conversion on ${version}`, async () => { diff --git a/js/net/src/lite/track_stream.test.ts b/js/net/src/lite/track_stream.test.ts index d29ae60ef5f..f4061b59684 100644 --- a/js/net/src/lite/track_stream.test.ts +++ b/js/net/src/lite/track_stream.test.ts @@ -2,7 +2,7 @@ // SUBSCRIBE is answered, and the publisher keeps the track wanted until the subscriber closes it. import { describe, expect, spyOn, test } from "bun:test"; -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { SessionCode } from "../error.ts"; import { randomHop } from "../hop.ts"; import { createMockTransportPair, manual, settlesWithin } from "../mock.ts"; @@ -28,7 +28,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver const reader = subscriber .consume(Path.from("room")) .track("video") - .subscribe({ delay: { max: Milli(100) } }); + .subscribe({ delay: { max: Duration.millis(100) } }); const track = await Stream.accept(pair.server, version); if (!track) throw new Error("the subscriber never asked for TRACK_INFO"); @@ -48,7 +48,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver using clock = manual(); const { subscriber, reader, track, sub } = await subscribing(); const fin = track.reader.done(); - expect(await settlesWithin(fin, clock, Milli(50))).toBe(false); + expect(await settlesWithin(fin, clock, Duration.millis(50))).toBe(false); await encodeSubscribeResponse(sub.writer, { start: new SubscribeStart([0n]) }, version); expect(await fin).toBe(true); @@ -61,7 +61,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver using clock = manual(); const { subscriber, reader, track } = await subscribing(); const fin = track.reader.done(); - expect(await settlesWithin(fin, clock, Milli(50))).toBe(false); + expect(await settlesWithin(fin, clock, Duration.millis(50))).toBe(false); reader.close(); expect(await fin).toBe(true); @@ -128,11 +128,11 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver await TrackInfo.decode(client.reader, version); expect(await client.reader.done()).toBe(true); if (!producer) throw new Error("the track was never answered"); - expect(await settlesWithin(Promise.resolve(producer.closed), clock, Milli(50))).toBe(false); + expect(await settlesWithin(Promise.resolve(producer.closed), clock, Duration.millis(50))).toBe(false); if (close === "FIN") client.writer.close(); else client.writer.reset(new Error("gone")); - expect(await settlesWithin(Promise.resolve(producer.closed), clock, Milli(1000))).toBe(true); + expect(await settlesWithin(Promise.resolve(producer.closed), clock, Duration.millis(1000))).toBe(true); publisher.close(); broadcast.close(); @@ -204,7 +204,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver if (close === "FIN") client.writer.close(); else client.writer.reset(new Error("gone")); - expect(await settlesWithin(Promise.resolve(producer.closed), clock, Milli(1000))).toBe(true); + expect(await settlesWithin(Promise.resolve(producer.closed), clock, Duration.millis(1000))).toBe(true); publisher.close(); broadcast.close(); @@ -244,10 +244,10 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver expect(producers.length).toBe(1); first.writer.close(); - expect(await settlesWithin(released(0), clock, Milli(50))).toBe(false); + expect(await settlesWithin(released(0), clock, Duration.millis(50))).toBe(false); second.writer.close(); - expect(await settlesWithin(released(0), clock, Milli(1000))).toBe(true); + expect(await settlesWithin(released(0), clock, Duration.millis(1000))).toBe(true); publisher.close(); broadcast.close(); @@ -282,15 +282,15 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver const first = await open(); await TrackInfo.decode(first.reader, version); first.writer.close(); - expect(await settlesWithin(released(0), clock, Milli(1000))).toBe(true); + expect(await settlesWithin(released(0), clock, Duration.millis(1000))).toBe(true); const second = await open(); await TrackInfo.decode(second.reader, version); expect(producers.length).toBe(2); - expect(await settlesWithin(released(1), clock, Milli(50))).toBe(false); + expect(await settlesWithin(released(1), clock, Duration.millis(50))).toBe(false); second.writer.close(); - expect(await settlesWithin(released(1), clock, Milli(1000))).toBe(true); + expect(await settlesWithin(released(1), clock, Duration.millis(1000))).toBe(true); publisher.close(); broadcast.close(); @@ -334,7 +334,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver // The handler still gets an open track, and the answer lets it go. const producer = request.accept({ timescale: Timescale.MILLI }); - expect(await settlesWithin(Promise.resolve(producer.closed), clock, Milli(1000))).toBe(true); + expect(await settlesWithin(Promise.resolve(producer.closed), clock, Duration.millis(1000))).toBe(true); publisher.close(); broadcast.close(); @@ -358,7 +358,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver pair.server.close(); // The handler still gets an open track, and the answer lets it go. const producer = request.accept({ timescale: Timescale.MILLI }); - expect(await settlesWithin(Promise.resolve(producer.closed), clock, Milli(1000))).toBe(true); + expect(await settlesWithin(Promise.resolve(producer.closed), clock, Duration.millis(1000))).toBe(true); publisher.close(); broadcast.close(); @@ -382,13 +382,13 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver // The next TRACK stream joins the request still waiting on the application. const second = await requester(pair, publisher, "TRACK"); - expect(await settlesWithin(wireOf(broadcast).requested(), clock, Milli(50))).toBe(false); + expect(await settlesWithin(wireOf(broadcast).requested(), clock, Duration.millis(50))).toBe(false); const producer = request.accept({ timescale: Timescale.MILLI }); await TrackInfo.decode(second.reader, version); - expect(await settlesWithin(Promise.resolve(producer.closed), clock, Milli(50))).toBe(false); + expect(await settlesWithin(Promise.resolve(producer.closed), clock, Duration.millis(50))).toBe(false); second.writer.close(); - expect(await settlesWithin(Promise.resolve(producer.closed), clock, Milli(1000))).toBe(true); + expect(await settlesWithin(Promise.resolve(producer.closed), clock, Duration.millis(1000))).toBe(true); publisher.close(); broadcast.close(); diff --git a/js/net/src/lite/tracks.test.ts b/js/net/src/lite/tracks.test.ts index cd3beebc5ab..ca8ea435d42 100644 --- a/js/net/src/lite/tracks.test.ts +++ b/js/net/src/lite/tracks.test.ts @@ -1,5 +1,5 @@ import { afterEach, expect, mock, spyOn, test } from "bun:test"; -import { Milli, yieldNow } from "@moq/clock"; +import { Duration, yieldNow } from "@moq/clock"; import { type Getter, Signal } from "@moq/signals"; import type { Grant } from "../auth.ts"; import { Producer as BroadcastProducer, type Tracks } from "../broadcast.ts"; @@ -462,7 +462,7 @@ test("a listing over a session carries each track's info, end to end", async () const broadcast = broadcastRoute.broadcast; broadcast.createTrack("a", { timescale: Timescale.MILLI, - maxAge: Milli(3000), + maxAge: Duration.millis(3000), priority: 9, refresh: 4, compress: true, @@ -473,7 +473,7 @@ test("a listing over a session carries each track's info, end to end", async () expect(await tracks.next()).toEqual({ kind: "added", name: "a", - info: { timescale: Timescale.MILLI, maxAge: Milli(3000), priority: 9, refresh: 4, compress: true }, + info: { timescale: Timescale.MILLI, maxAge: Duration.millis(3000), priority: 9, refresh: 4, compress: true }, }); broadcast.createTrack("b"); expect(await next(tracks)).toBe("+b"); diff --git a/js/net/src/lite/widened_max_age.test.ts b/js/net/src/lite/widened_max_age.test.ts index 8b6f87d2c1a..e4c7a74c005 100644 --- a/js/net/src/lite/widened_max_age.test.ts +++ b/js/net/src/lite/widened_max_age.test.ts @@ -2,7 +2,7 @@ // as stale, including those below where SUBSCRIBE_START resolved, and never one twice. import { expect, test } from "bun:test"; -import { Milli, now } from "@moq/clock"; +import { Duration, now } from "@moq/clock"; import { accept, connect } from "../connection/index.ts"; import { createMockTransportPair } from "../mock.ts"; import { Producer as OriginProducer } from "../origin.ts"; @@ -44,10 +44,10 @@ test("a widened maxDelay re-offers what the publisher skipped below the start", ]); const remote = wireOf(client).consume(Path.from("room")); // Group 5 ends at 6s, a full 3s behind the 9s edge. - const reader = remote.track("video").subscribe({ delay: { max: Milli(2500) } }); + const reader = remote.track("video").subscribe({ delay: { max: Duration.millis(2500) } }); expect(await received(reader, 4)).toEqual([6n, 7n, 8n, 9n]); - reader.update({ delay: { max: Milli(6500) } }); + reader.update({ delay: { max: Duration.millis(6500) } }); expect(await received(reader, 4)).toEqual([2n, 3n, 4n, 5n]); // Ending the track flushes anything else the publisher would send: nothing, not even a repeat. producer.finish(); @@ -85,7 +85,7 @@ for (const [version, alpn] of [ accept({ transport: pair.server, url, version, publish: origin.consume() }), ]); const remote = wireOf(client).consume(Path.from("room")); - const reader = remote.track("video").subscribe({ delay: { max: Milli(1500) } }); + const reader = remote.track("video").subscribe({ delay: { max: Duration.millis(1500) } }); expect(await received(reader, 1)).toEqual([0n]); // Groups 1 and 2 reach 2s and 3s, at least 1.5s behind the 6s edge, so they are reported // stale after SUBSCRIBE_START. @@ -100,7 +100,7 @@ for (const [version, alpn] of [ expect(await received(reader, 2)).toEqual([3n, 4n]); // Lite-07 re-offers only the groups reported stale; earlier subscribers settled them for good. - reader.update({ delay: { max: Milli(10_000) } }); + reader.update({ delay: { max: Duration.millis(10_000) } }); if (reoffers) expect(await received(reader, 2)).toEqual([1n, 2n]); producer.finish(); producer.close(); @@ -134,7 +134,7 @@ test("a widening keeps a bounded lite-07 subscription open for the stale groups ]); const remote = wireOf(client).consume(Path.from("room")); const ranges = [{ start: { absolute: 0n }, end: { absolute: 5n } }]; - const reader = remote.track("video").subscribe({ delay: { max: Milli(1500) }, ranges }); + const reader = remote.track("video").subscribe({ delay: { max: Duration.millis(1500) }, ranges }); expect(await received(reader, 1)).toEqual([0n]); // Groups 1 and 2 are reported stale after SUBSCRIBE_START. for (const [sequence, millis] of [ @@ -148,7 +148,7 @@ test("a widening keeps a bounded lite-07 subscription open for the stale groups expect(await received(reader, 2)).toEqual([3n, 4n]); // The widening re-offers them, and the track's end does not settle the tail before they arrive. - reader.update({ delay: { max: Milli(10_000) }, ranges }); + reader.update({ delay: { max: Duration.millis(10_000) }, ranges }); producer.finish(); expect(await received(reader, 2)).toEqual([1n, 2n]); @@ -181,7 +181,7 @@ test("an update keeping the budget drops the stale groups again on lite-07", asy accept({ transport: pair.server, url, version: Version.DRAFT_07, publish: origin.consume() }), ]); const remote = wireOf(client).consume(Path.from("room")); - const reader = remote.track("video").subscribe({ delay: { max: Milli(1500) } }); + const reader = remote.track("video").subscribe({ delay: { max: Duration.millis(1500) } }); expect(await received(reader, 1)).toEqual([0n]); for (const [sequence, millis] of [ [1, 1000], @@ -200,7 +200,7 @@ test("an update keeping the budget drops the stale groups again on lite-07", asy producer.close(); expect(await reader.recvGroup()).toBeUndefined(); // Well inside the 1.5s grace a missing re-drop would wait out, in nanoseconds. - expect(now() - before).toBeLessThan(500_000_000); + expect(now().since(before).lt(Duration.millis(500))).toBe(true); reader.close(); remote.close(); diff --git a/js/net/src/mock.test.ts b/js/net/src/mock.test.ts index e3a661ce49e..f414355d09b 100644 --- a/js/net/src/mock.test.ts +++ b/js/net/src/mock.test.ts @@ -1,9 +1,9 @@ import { expect, test } from "bun:test"; -import { Elapsed, Instant, Milli, Nano, now, sleep, timeout } from "@moq/clock"; +import { Duration, Elapsed, Instant, now, sleep, timeout } from "@moq/clock"; import { StreamCode, toTransport } from "./error.ts"; import { createMockTransportPair, manual } from "./mock.ts"; -const ms = (n: number) => Nano.fromMilli(Milli(n)); +const ms = (n: number) => Duration.millis(n); async function pair() { const { client, server } = createMockTransportPair(); @@ -75,7 +75,7 @@ test("drive delivers a queued round trip before its deadline and stops at the de await sleep(ms(10)); return { value, at: now() }; })(); - expect(await clock.drive(work)).toEqual({ value: Uint8Array.of(7), at: Instant(ms(10)) }); + expect(await clock.drive(work)).toEqual({ value: Uint8Array.of(7), at: Instant.ZERO.add(ms(10)) }); expect(late).toBe(false); }); @@ -84,7 +84,7 @@ test("drive times out a read with nothing in flight at its deadline", async () = const { local } = await pair(); const read = timeout(ms(1000), local.readable.getReader().read()); expect(await clock.drive(read.catch((e: unknown) => e))).toBeInstanceOf(Elapsed); - expect(clock.now()).toBe(Instant(ms(1000))); + expect(clock.now()).toEqual(Instant.ZERO.add(ms(1000))); }); test("drive reaches a deadline while deliveries keep arriving", async () => { @@ -106,7 +106,7 @@ test("drive reaches a deadline while deliveries keep arriving", async () => { send(); try { await clock.drive(sleep(ms(1000))); - expect(clock.now()).toBe(Instant(ms(1000))); + expect(clock.now()).toEqual(Instant.ZERO.add(ms(1000))); expect(delivered).toBeGreaterThan(0); } finally { sending = false; diff --git a/js/net/src/mock.ts b/js/net/src/mock.ts index a505fbb13b9..c9bd5936cb7 100644 --- a/js/net/src/mock.ts +++ b/js/net/src/mock.ts @@ -4,7 +4,7 @@ * Creates paired client/server transports connected by in-memory streams. */ -import { Manual, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import type { Getter } from "@moq/signals"; import { Consumer as BroadcastConsumer } from "./broadcast.ts"; import type { TransportStats } from "./connection/stats.ts"; @@ -28,14 +28,14 @@ export function manual(): Manual & Disposable { export async function settlesWithin( work: PromiseLike, clock: Manual, - duration = Milli.zero, + duration = Duration.ZERO, ): Promise { let settled = false; const done = () => { settled = true; }; Promise.resolve(work).then(done, done); - await clock.advance(Nano.fromMilli(duration)); + await clock.advance(duration); return settled; } diff --git a/js/net/src/net-cleanups.test.ts b/js/net/src/net-cleanups.test.ts index af11677ba1b..76f9d8cfb08 100644 --- a/js/net/src/net-cleanups.test.ts +++ b/js/net/src/net-cleanups.test.ts @@ -1,5 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { Manual, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { accept } from "./connection/accept.ts"; import { connect } from "./connection/connect.ts"; import { ConnectTimeout } from "./error.ts"; @@ -85,9 +85,9 @@ for (const [version, alpn] of [ const dispose = client.probe.subscribe(() => {}); try { // The publisher samples on its 100ms PROBE cadence. - await clock.advance(Nano.fromMilli(Milli(100))); + await clock.advance(Duration.millis(100)); expect(client.probe.peek().estimatedRecvRate).toBe(8_000_000); - expect(client.probe.peek().rtt).toBe(version === Version.DRAFT_03 ? undefined : Milli(12)); + expect(client.probe.peek().rtt).toEqual(version === Version.DRAFT_03 ? undefined : Duration.millis(12)); } finally { dispose(); client.abort(); @@ -111,9 +111,9 @@ test("accept applies its default handshake deadline and releases a silent transp }, ); try { - await clock.advance(Nano.fromMilli(Milli(29_999))); + await clock.advance(Duration.millis(29_999)); expect(outcome).toBeUndefined(); - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); expect(outcome).toBeInstanceOf(ConnectTimeout); expect((await pair.client.closed).closeCode).toBe(0); } finally { @@ -170,7 +170,7 @@ test("zero accept timeout waits for caller cancellation and preserves its reason const pending = accept({ transport: pair.server, url: new URL("https://example.com"), - timeout: Milli(0), + timeout: Duration.millis(0), signal: controller.signal, }).then( (value) => { @@ -181,7 +181,7 @@ test("zero accept timeout waits for caller cancellation and preserves its reason }, ); try { - await clock.advance(Nano.fromMilli(Milli(60_000))); + await clock.advance(Duration.millis(60_000)); expect(outcome).toBeUndefined(); controller.abort(reason); await pending; @@ -195,15 +195,10 @@ test("zero accept timeout waits for caller cancellation and preserves its reason } }); -test("invalid or pre-aborted accept options never take ownership of the transport", async () => { +test("pre-aborted accept options never take ownership of the transport", async () => { const pair = createMockTransportPair("moqt-18"); const closing = spyOn(pair.server, "close"); try { - for (const timeout of [-1, Number.NaN, Number.POSITIVE_INFINITY]) { - await expect( - accept({ transport: pair.server, url: new URL("https://example.com"), timeout: timeout as Milli }), - ).rejects.toThrow("invalid time"); - } const reason = new Error("already cancelled"); await expect( accept({ transport: pair.server, url: new URL("https://example.com"), signal: AbortSignal.abort(reason) }), @@ -225,11 +220,11 @@ test.each([ALPN_04, "moqt-18"])("accepted %s sessions outlive their handshake ti const url = new URL("https://example.com"); const [client, server] = await Promise.all([ connect({ url, transport: pair.client }), - accept({ url, transport: pair.server, timeout: Milli(1_000), signal: controller.signal }), + accept({ url, transport: pair.server, timeout: Duration.millis(1_000), signal: controller.signal }), ]); try { controller.abort(); - await clock.advance(Nano.fromMilli(Milli(5_000))); + await clock.advance(Duration.millis(5_000)); expect(closing).not.toHaveBeenCalled(); expect(await server.stats()).toEqual({}); } finally { diff --git a/js/net/src/open.test.ts b/js/net/src/open.test.ts index b62789991be..f75bbd478dc 100644 --- a/js/net/src/open.test.ts +++ b/js/net/src/open.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Manual, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import Qmux from "@moq/qmux"; import { Version } from "./lite/version.ts"; import { createMockTransportPair } from "./mock.ts"; @@ -93,7 +93,7 @@ test("an open waiting a round trip resets the lowest stream below it, one per wa await low.write(new Uint8Array(16)); await mid.write(new Uint8Array(16)); // Before any RTT sample, an open waits 100 ms. - const wait = () => clock.advance(Nano.fromMilli(Milli(100))); + const wait = () => clock.advance(Duration.millis(100)); const below = Promise.withResolvers(); const pending = Writer.tryOpen(client, { version, sendOrder: 0, cancel: below.promise, group: true }); @@ -135,7 +135,7 @@ test("an open makes room only once it has waited a round trip itself", async () try { const low = await openGroup(client, 1); await low.write(new Uint8Array(16)); - const wait = (ms: number) => clock.advance(Nano.fromMilli(Milli(ms))); + const wait = (ms: number) => clock.advance(Duration.millis(ms)); const below = Promise.withResolvers(); const pending = Writer.tryOpen(client, { version, sendOrder: 0, cancel: below.promise, group: true }); @@ -170,13 +170,13 @@ test("an open ranked above an impatient one makes room for it at once", async () await mid.write(new Uint8Array(16)); const waiting = openGroup(client, 5); - await clock.advance(Nano.fromMilli(Milli(100))); + await clock.advance(Duration.millis(100)); expect(orders(client)).toEqual([2]); // The reset's credit will reach this open instead, so the one still waiting is owed another. const higher = openGroup(client, 10); // Well short of its own round trip. - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); expect(orders(client)).toEqual([]); const incoming = server.incomingUnidirectionalStreams.getReader(); @@ -204,9 +204,9 @@ test("an RTT of 0 reads as no sample, so an open still waits 100 ms", async () = await low.write(new Uint8Array(16)); const high = openGroup(client, 5); - await clock.advance(Nano.fromMilli(Milli(99))); + await clock.advance(Duration.millis(99)); expect(orders(client)).toEqual([1]); - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); await expect(low.closed).rejects.toThrow("lagged"); const incoming = server.incomingUnidirectionalStreams.getReader(); diff --git a/js/net/src/open.ts b/js/net/src/open.ts index 032e01347b4..5a820ce3292 100644 --- a/js/net/src/open.ts +++ b/js/net/src/open.ts @@ -1,4 +1,4 @@ -import { Milli, Nano, sleep } from "@moq/clock"; +import { Duration, sleep } from "@moq/clock"; import { type Getter, race } from "@moq/signals"; import type { Probe } from "./connection/stats.ts"; import { transportStats } from "./connection/stats.ts"; @@ -46,7 +46,7 @@ interface Waiting { interface Room { streams: OpenStreams; /** About one round trip: how long an open waits for credit before making room. */ - patience: () => Promise; + patience: () => Promise; } /** An admitted stream, with the send order it was created at. */ @@ -162,7 +162,7 @@ class Line { try { const patience = await room.patience(); if (waiting.left.signal.aborted) return; - await sleep(Nano.fromMilli(patience), { signal: waiting.left.signal, ref: false }); + await sleep(patience, { signal: waiting.left.signal, ref: false }); } catch { // Left the line first. return; @@ -299,7 +299,10 @@ export function lines(quic: WebTransport): Lines { sendOrder === 0 ? { waitUntilAvailable: true } : { sendOrder, waitUntilAvailable: true }; const streams = new OpenStreams(transportOf(quic) === "websocket"); // Before any RTT sample, wait 100 ms. A transport may report 0 until its first sample. - const patience = async () => (await transportStats(quic)).rtt || session.probe?.peek().rtt || Milli(100); + // A zero RTT is a transport that has not sampled yet. + const sampled = (rtt?: Duration) => (rtt?.isZero() ? undefined : rtt); + const patience = async () => + sampled((await transportStats(quic)).rtt) ?? sampled(session.probe?.peek().rtt) ?? Duration.millis(100); const session: Lines = { uni: new Line( (sendOrder) => quic.createUnidirectionalStream(options(sendOrder)) as Promise, diff --git a/js/net/src/order.test.ts b/js/net/src/order.test.ts index 4ddba1863dc..1359541f337 100644 --- a/js/net/src/order.test.ts +++ b/js/net/src/order.test.ts @@ -6,7 +6,7 @@ // streams stay in flight and ranked against each other. import { expect, test } from "bun:test"; -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { accept, connect, type Established } from "./connection/index.ts"; import type { Producer as GroupProducer } from "./group.ts"; import { FetchHeader } from "./ietf/fetch.ts"; @@ -24,7 +24,7 @@ import { wireOf } from "./wire.ts"; const url = new URL("https://localhost:4443/test"); // A budget covering every group these tests write, so expiry never decides what is sent. -const MAX_DELAY = Milli(30_000); +const MAX_DELAY = Duration.millis(30_000); // The send orders a subscription at priority 0 gives its streams, in the order they opened, // when stream `i` carries group `i` of `count` all still in flight. diff --git a/js/net/src/parked-expiry.test.ts b/js/net/src/parked-expiry.test.ts index 62b7b6547dd..ca6c393ef20 100644 --- a/js/net/src/parked-expiry.test.ts +++ b/js/net/src/parked-expiry.test.ts @@ -1,5 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { Manual, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { StreamCode } from "./error.ts"; import { randomHop } from "./hop.ts"; import { Publisher as IetfPublisher } from "./ietf/publisher.ts"; @@ -110,10 +110,10 @@ for (const protocol of protocols) { expect(ended).toBe(false); write(1n); if (mode === "expires") { - await clock.advance(Nano.fromMilli(Milli(budget - 1))); + await clock.advance(Duration.millis(budget - 1)); expect(ended).toBe(false); - await clock.advance(Nano.fromMilli(Milli(1))); - } else await clock.advance(Nano.fromMilli(Milli(45_000))); + await clock.advance(Duration.millis(1)); + } else await clock.advance(Duration.millis(45_000)); expect(ended).toBe(true); if (protocol.kind === "lite") { for (;;) { @@ -127,7 +127,7 @@ for (const protocol of protocols) { // The transport cannot cancel createUnidirectionalStream. A late slot is kept for // the next open, never used to transmit the obsolete group's header or frames. slot.resolve(); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(writes).toBe(0); expect(resets).toBe(0); } finally { @@ -221,10 +221,10 @@ for (const protocol of protocols) { try { await blocked.promise; write(1n, 1); - await clock.advance(Nano.fromMilli(Milli(45_000))); + await clock.advance(Duration.millis(45_000)); // The write already handed to the stream finishes, and the stream is reset after it. credit.resolve(); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(writes).toBe(1); expect(resets).toBe(1); } finally { diff --git a/js/net/src/request-deadline.test.ts b/js/net/src/request-deadline.test.ts index a377e4d3948..46e8e3b9e98 100644 --- a/js/net/src/request-deadline.test.ts +++ b/js/net/src/request-deadline.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Manual, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { SessionCode, SessionError } from "./error.ts"; import { HopSchema } from "./hop.ts"; import { NativeSession } from "./ietf/session.ts"; @@ -46,7 +46,7 @@ function limited(mode: "queue" | "open") { }; } -const HOUR = Nano.fromMilli(Milli(3_600_000)); +const HOUR = Duration.millis(3_600_000); // A publisher may hold its answer, so a request waits until its caller leaves, as in Rust. // Cancellation resets opened streams and gives up queued opens without spending their credit. @@ -64,13 +64,13 @@ for (const protocol of ["lite", "ietf"] as const) { const track = broadcast.track("video").subscribe(); try { await transport.created; - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); await clock.advance(HOUR); expect(track.closed.peek()).toBeUndefined(); track.close(); if (mode === "queue") { transport.release(); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(transport.written).toEqual([]); } else { await transport.aborted; @@ -141,7 +141,7 @@ for (const operation of ["info", "fetch"] as const) { }); try { await transport.created; - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); await clock.advance(HOUR); expect(failure).toBeUndefined(); const left = new Error("left"); @@ -149,10 +149,10 @@ for (const operation of ["info", "fetch"] as const) { await request; expect(failure).toBe(left); // Credit granted once the caller has left can't send the request. - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); if (mode === "queue") { transport.release(); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(transport.written).toEqual([]); } else { await transport.aborted; @@ -182,13 +182,13 @@ for (const protocol of ["lite", "ietf"] as const) { const announced = subscriber.routes(); try { await transport.created; - await clock.advance(Nano.zero); - await clock.advance(Nano.fromMilli(Milli(30_000))); + await clock.advance(Duration.ZERO); + await clock.advance(Duration.millis(30_000)); expect(announced.closed.peek()).toBeUndefined(); if (mode === "queue") { expect(transport.written).toEqual([]); transport.release(); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(transport.written).not.toEqual([]); } expect(transport.options).toEqual([{ waitUntilAvailable: true }]); @@ -216,7 +216,7 @@ for (const protocol of ["lite", "ietf"] as const) { await transport.created; track.close(); transport.release(); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(transport.written).toEqual([]); const next = broadcast.track("next").subscribe(); await transport.writing; diff --git a/js/net/src/resume.model.test.ts b/js/net/src/resume.model.test.ts index 39a0dd25174..66c9d824afb 100644 --- a/js/net/src/resume.model.test.ts +++ b/js/net/src/resume.model.test.ts @@ -12,7 +12,7 @@ */ import { expect, test } from "bun:test"; -import { Manual, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import fc from "fast-check"; import { Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts"; import { NotFound, StreamCode, StreamError, TooFarBehind } from "./error.ts"; @@ -36,9 +36,9 @@ const INSTANCES = [Instance.parse("first"), Instance.parse("second")]; const READERS = 4; const PATH = Path.from("room/alice"); /** A budget nothing in a case outlives. */ -const HOUR = Milli(3_600_000); +const HOUR = Duration.millis(3_600_000); /** A budget spanning about three groups. */ -const SHORT = Milli(30); +const SHORT = Duration.millis(30); const enc = new TextEncoder(); const dec = new TextDecoder(); @@ -400,10 +400,10 @@ class Model { this.end(op.instance, op.slot); break; case "advance": - await this.clock.advance(Nano.fromMilli(Milli(op.ms))); + await this.clock.advance(Duration.millis(op.ms)); break; case "expire": - await this.clock.advance(Nano.fromMilli(Milli(60_000))); + await this.clock.advance(Duration.millis(60_000)); for (const instance of this.instances) instance.expired = instance.newest(); for (const reader of this.readers) { if (reader) reader.floor = this.instances[reader.instance].newest(); @@ -553,7 +553,7 @@ class Model { request.close(); throw fail(index, `request failed: ${closed ?? "never resolved"}`); } - await this.clock.advance(Nano.zero); + await this.clock.advance(Duration.ZERO); } const broadcast = request.active.peek(); const instance = broadcast?.instance === undefined ? -1 : INSTANCES.indexOf(broadcast.instance); @@ -725,7 +725,7 @@ class Model { let quiet = 0; for (let round = 0; round < 10_000; round++) { const progress = this.progress; - await this.clock.advance(Nano.zero); + await this.clock.advance(Duration.ZERO); if (this.failure) throw this.failure; let woken = this.progress !== progress; for (let index = 0; index < READERS; index++) { @@ -842,7 +842,7 @@ class Model { } } this.origin.close(); - await this.clock.advance(Nano.zero); + await this.clock.advance(Duration.ZERO); } } diff --git a/js/net/src/resume.test.ts b/js/net/src/resume.test.ts index 8948611f37b..20e61f3d5ea 100644 --- a/js/net/src/resume.test.ts +++ b/js/net/src/resume.test.ts @@ -1,5 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { Manual, Milli, Nano, yieldNow } from "@moq/clock"; +import { Duration, Manual, yieldNow } from "@moq/clock"; import { Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts"; import { NotFound, SessionCode, SessionError, StreamCode, StreamError } from "./error.ts"; import { type Consumer as GroupConsumer, Producer as GroupProducer } from "./group.ts"; @@ -117,22 +117,22 @@ test("returning to a route reuses its subscription and held group", async () => const open = tracks[0].write(0n, 1, false); const mirrored = spyOn(open, "mirror"); front.serve(handles[0]); - const sub = front.consumer.track("seq").subscribe({ delay: { max: Milli(3_600_000) } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(3_600_000) } }); try { - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); const held = sub.tryRecvGroup(); if (!held) throw new Error("expected the held group"); expect(dec.decode((await held.readFrame())?.payload)).toBe("0.0"); for (let round = 0; round < 32; round++) { front.serve(handles[round % 2]); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(sub.tryRecvGroup()).toBeUndefined(); expect(mirrored.mock.calls.length).toBe(1); } tracks[1].write(1n); expect(drain(sub)).toEqual([1n]); front.serve(handles[0]); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); open.writeFrame({ payload: enc.encode("0.1") }); expect(dec.decode((await held.readFrame())?.payload)).toBe("0.1"); tracks[0].write(2n); @@ -163,19 +163,19 @@ test("a returning route backfills below the reader's newest", async () => { const open = ta.write(0n, 1, false); const mirrored = spyOn(open, "mirror"); front.serve(handles[0]); - const sub = front.consumer.track("seq").subscribe({ delay: { max: Milli(3_600_000) } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(3_600_000) } }); try { - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); const held = sub.tryRecvGroup(); if (!held) throw new Error("expected the held group"); front.serve(handles[1]); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); tb.write(10n); tb.write(20n); expect(drain(sub)).toEqual([10n, 20n]); ta.write(15n); front.serve(handles[0]); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(mirrored.mock.calls.length).toBe(1); expect(drain(sub)).toEqual([15n]); ta.write(26n); @@ -208,22 +208,22 @@ test("route flaps keep one backfill per distinct route", async () => { const handles = sources.map((source) => source.consume()); const tracks = sources.map(copy); front.serve(handles[0]); - const sub = front.consumer.track("seq").subscribe({ delay: { max: Milli(3_600_000) } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(3_600_000) } }); const subscribed = tracks.map((track) => spyOn(track.producer, "subscribe")); try { - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); for (let round = 1; round < 24; round++) { front.serve(handles[round % 2]); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); // Every odd group never lands, so every resume point leaves a gap. tracks[round % 2].write(BigInt(round * 2)); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(drain(sub)).toEqual([BigInt(round * 2)]); } // Each route's own copy, returned to on every flap, and its one backfill. for (const spy of subscribed) expect(spy.mock.calls.length).toBe(2); tracks[1].write(1n); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(drain(sub)).toEqual([1n]); } finally { for (const spy of subscribed) spy.mockRestore(); @@ -243,20 +243,20 @@ test("a group below the replacement's resume point is backfilled", async () => { const handles = sources.map((source) => source.consume()); const [ta, tb] = sources.map(copy); front.serve(handles[0]); - const sub = front.consumer.track("seq").subscribe({ delay: { max: Milli(3_600_000) } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(3_600_000) } }); try { - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); ta.write(5n); expect(drain(sub)).toEqual([5n]); front.serve(handles[1]); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(drain(sub)).toEqual([]); tb.write(2n); tb.write(6n); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(drain(sub)).toEqual([2n, 6n]); tb.write(4n); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(drain(sub)).toEqual([4n]); } finally { sub.close(); @@ -284,15 +284,15 @@ test("a backfill waits on a fill the finished route still owes", async () => { tb.write(6n); tb.producer.finish(); front.serve(handles[0]); - const sub = front.consumer.track("seq").subscribe({ delay: { max: Milli(3_600_000) } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(3_600_000) } }); try { - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); ta.write(5n); expect(drain(sub)).toEqual([5n]); front.serve(handles[1]); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(drain(sub)).toEqual([6n]); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(fills.length).toBeGreaterThan(0); expect(drain(sub)).toEqual([]); expect(sub.closed.peek()).toBeUndefined(); @@ -309,7 +309,7 @@ test("a backfill waits on a fill the finished route still owes", async () => { } fill.close(); } - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(drain(sub)).toEqual([2n]); } finally { requests.close(); @@ -461,7 +461,7 @@ test.each(["conclude", "park"] as const)("a fork made after the front's %s repla ta.write(1n); expect(drain(parent)).toEqual([1n]); front[end](); - const fork = parent.fork({ delay: { max: Milli(10_000) } }); + const fork = parent.fork({ delay: { max: Duration.millis(10_000) } }); try { expect(drain(fork)).toEqual([0n, 1n]); } finally { @@ -486,7 +486,7 @@ test("a resumed fork has its own preferences and replay cursor", async () => { ta.write(0n); ta.write(1n); expect(drain(parent)).toEqual([1n]); - const fork = parent.fork({ priority: 7, delay: { max: Milli(10_000) } }); + const fork = parent.fork({ priority: 7, delay: { max: Duration.millis(10_000) } }); try { expect(drain(fork)).toEqual([0n, 1n]); fork.update({ priority: 9 }); @@ -550,7 +550,7 @@ test("a lagging same-instance replica resumes from one publisher's bytes exactly function replica(lagging: boolean) { const broadcast = new BroadcastProducer(); const output = broadcast.createTrack("seq", { maxAge: null }); - const input = source.subscribe({ delay: { max: Milli(60_000) } }); + const input = source.subscribe({ delay: { max: Duration.millis(60_000) } }); const release = Promise.withResolvers(); let stopped = false; const done = (async () => { @@ -600,14 +600,14 @@ test("a lagging same-instance replica resumes from one publisher's bytes exactly const disposeA = serve(origin, a.broadcast, 5n); const request = origin.request(path); const standby = b.broadcast.consume(); - const warm = standby.track("seq").subscribe({ delay: { max: Milli(60_000) } }); + const warm = standby.track("seq").subscribe({ delay: { max: Duration.millis(60_000) } }); let sub: track.Subscriber | undefined; let disposeB: (() => void) | undefined; try { - await clock.advance(Nano(0)); + await clock.advance(Duration.nanos(0)); const active = request.active.peek(); if (!active) throw new Error("expected the incumbent route"); - sub = active.track("seq").subscribe({ delay: { max: Milli(60_000) } }); + sub = active.track("seq").subscribe({ delay: { max: Duration.millis(60_000) } }); const first = source.appendGroup(); for (let frame = 0; frame < 4; frame++) first.writeFrame({ payload: enc.encode(`0.${frame}`) }); first.finish(); @@ -643,11 +643,11 @@ test("a lagging same-instance replica resumes from one publisher's bytes exactly group.close(); } disposeB = serve(origin, b.broadcast, 9n); - await clock.advance(Nano(0)); + await clock.advance(Duration.nanos(0)); expect(request.active.peek()).toBe(active); disposeA(); a.stop(new StreamError(StreamCode.SessionClosed)); - await clock.advance(Nano(0)); + await clock.advance(Duration.nanos(0)); for (let frame = 2; frame < 4; frame++) seen.push(dec.decode((await interrupted.readFrame())?.payload)); expect(await interrupted.readFrame()).toBeUndefined(); interrupted.close(); @@ -658,7 +658,7 @@ test("a lagging same-instance replica resumes from one publisher's bytes exactly expect(await successor.readFrame()).toBeUndefined(); successor.close(); expect(seen).toEqual(Array.from({ length: 12 }, (_, index) => `${Math.floor(index / 4)}.${index % 4}`)); - await clock.advance(Nano(0)); + await clock.advance(Duration.nanos(0)); expect(sub.tryRecvGroup()).toBeUndefined(); // The source is still open, so the resumed subscription must stay live. expect(sub.closed.peek()).toBeUndefined(); @@ -684,7 +684,7 @@ test("a subscription reads on across a same-instance route swap, each group once const { a, b, active, request, swap, close } = await setup(); const ta = copy(a); const tb = copy(b); - const sub = active.track("seq").subscribe({ delay: { max: 10_000 as track.Delay["max"] } }); + const sub = active.track("seq").subscribe({ delay: { max: Duration.millis(10_000) } }); ta.write(0n); expect(drain(sub)).toEqual([0n]); @@ -1356,7 +1356,7 @@ test("an ordered reader takes a replaced copy's buffered group before the new co front.serve(a.consume()); const ordered = front.consumer .track("seq") - .subscribe({ delay: { max: 10_000 as track.Delay["max"] } }) + .subscribe({ delay: { max: Duration.millis(10_000) } }) .ordered(); ta.write(0n); expect((await ordered.nextGroup())?.sequence).toBe(0n); @@ -1389,7 +1389,7 @@ test("a routed read right after an update picks its group under the new preferen ta.write(1n); await settle(); // The copy learns of the update a microtask later; the read must not pick under its old budget. - ordered.update({ delay: { max: Milli.zero } }); + ordered.update({ delay: { max: Duration.ZERO } }); expect(ordered.tryNextGroup()?.sequence).toBe(1n); } finally { ordered.close(); @@ -1412,7 +1412,7 @@ for (const resolution of ["arrival", "drop", "other copy", "budget"] as const) { front.serve(a.consume()); const ordered = front.consumer .track("seq") - .subscribe({ delay: { max: Milli(1000) } }) + .subscribe({ delay: { max: Duration.millis(1000) } }) .ordered(); try { ta.write(4n); @@ -1431,7 +1431,7 @@ for (const resolution of ["arrival", "drop", "other copy", "budget"] as const) { } if (resolution === "drop") hooks.dropTrackGroups(ta.producer, 5n, 6n, { error: new StreamError(StreamCode.Old) }); - if (resolution === "budget") await clock.advance(Nano.fromMilli(Milli(1000))); + if (resolution === "budget") await clock.advance(Duration.millis(1000)); const expected = resolution === "arrival" || resolution === "other copy" ? [5n, 6n, 7n] : [6n, 7n]; expect((await held)?.sequence).toBe(expected[0]); for (const sequence of expected.slice(1)) expect((await ordered.nextGroup())?.sequence).toBe(sequence); @@ -1520,7 +1520,7 @@ for (const fails of [true, false]) { const pending = [ta.producer.requests(), tb.producer.requests()]; const stalled = ta.write(0n, 1, false); front.serve(a.consume()); - const sub = front.consumer.track("seq").subscribe({ delay: { max: Milli(60_000) } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(60_000) } }); const group = sub.tryRecvGroup(); if (!group) throw new Error("expected group 0"); expect(dec.decode((await group.readFrame())?.payload)).toBe("0.0"); @@ -1563,7 +1563,7 @@ test("a resumed reader reports a drop once and still serves a late group", async const a = new BroadcastProducer(); const ta = copy(a); front.serve(a.consume()); - const sub = front.consumer.track("seq").subscribe({ delay: { max: Milli(60_000) } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(60_000) } }); ta.write(0n); expect(recvDisposition(sub)).toBe(0n); // A route failing is no verdict: another route may still deliver the group. @@ -1591,7 +1591,7 @@ test("a resumed reader reports a skip over a reported drop", () => { const a = new BroadcastProducer(); const ta = copy(a); front.serve(a.consume()); - const sub = front.consumer.track("seq").subscribe({ delay: { max: Milli(60_000) } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(60_000) } }); const recv = () => { const next = hooks.tryRecvGroup(sub, true); if (next.kind === "group") { @@ -1646,11 +1646,11 @@ test("a resumed reader reports a group its serving copy skipped past the budget" const a = new BroadcastProducer(); const ta = copy(a); front.serve(a.consume()); - const sub = front.consumer.track("seq").subscribe({ delay: { max: Milli(1_000) } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(1_000) } }); expect(recvDisposition(sub)).toBe("idle"); ta.write(0n); ta.write(1n); - await clock.advance(Nano(2_000_000_000)); + await clock.advance(Duration.nanos(2_000_000_000)); expect(recvDisposition(sub)).toBe(1n); expect(recvDisposition(sub)).toEqual([0n, 1n, StreamCode.Old]); expect(recvDisposition(sub)).toBe("idle"); @@ -1673,7 +1673,7 @@ test("a drop waits while a copy the serving one replaced may still deliver it", const ta = copy(a); const tb = copy(b); front.serve(a.consume()); - const sub = front.consumer.track("seq").subscribe({ delay: { max: Milli(1_000) } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(1_000) } }); ta.write(0n); expect(recvDisposition(sub)).toBe(0n); front.serve(b.consume()); @@ -1688,7 +1688,7 @@ test("a drop waits while a copy the serving one replaced may still deliver it", expect(recvDisposition(sub)).toBe(3n); expect(recvDisposition(sub)).toBe("idle"); // Once the old copy is past the reader's budget, nothing delivers 2. - await clock.advance(Nano(1_000_000_000)); + await clock.advance(Duration.nanos(1_000_000_000)); expect(recvDisposition(sub)).toEqual([2n, 3n, 70]); ta.write(2n); expect(recvDisposition(sub)).toBe("idle"); @@ -1714,7 +1714,7 @@ test("a held-back stale run new terms supersede is not reported", async () => { const ta = copy(a); const tb = copy(b); front.serve(a.consume()); - const sub = front.consumer.track("seq").subscribe({ delay: { max: Milli(1_000) } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(1_000) } }); ta.write(0n); expect(recvDisposition(sub)).toBe(0n); front.serve(b.consume()); @@ -1726,7 +1726,7 @@ test("a held-back stale run new terms supersede is not reported", async () => { expect(recvDisposition(sub)).toBe(3n); // The route's subscription updates before the old copy is past the budget. hooks.supersedeStale(tb.producer, undefined); - await clock.advance(Nano(1_000_000_000)); + await clock.advance(Duration.nanos(1_000_000_000)); expect(recvDisposition(sub)).toBe("idle"); sub.close(); @@ -1748,7 +1748,7 @@ test("a resumed reader retires a stale report its group or final drop replaces", const ta = copy(a); const tb = copy(b); front.serve(a.consume()); - const sub = front.consumer.track("seq").subscribe({ delay: { max: Milli(60_000) } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(60_000) } }); ta.write(0n); expect(drain(sub)).toEqual([0n]); hooks.dropTrackGroups(ta.producer, 1n, 4n, staleHole(60_000)); @@ -1812,7 +1812,7 @@ test("a front serving another front reports the inner serving route's drop", asy const ta = copy(a); inner.serve(a.consume()); outer.serve(inner.consumer); - const sub = outer.consumer.track("seq").subscribe({ delay: { max: Milli(60_000) } }); + const sub = outer.consumer.track("seq").subscribe({ delay: { max: Duration.millis(60_000) } }); ta.write(0n); expect(recvDisposition(sub)).toBe(0n); hooks.dropTrackGroups(ta.producer, 1n, 3n, { error: new StreamError(StreamCode(70), { message: "cut" }) }); @@ -1903,7 +1903,7 @@ test("a failed group whose replacement cannot fetch ends with the failure, or co const tb = copy(b); front.serve(a.consume()); // A budget wide enough that the newer group never gives group 0 up first. - const sub = front.consumer.track("seq").subscribe({ delay: { max: Milli(3_600_000) } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(3_600_000) } }); const stalled = ta.write(0n, 1, false); const group = sub.tryRecvGroup(); if (!group) throw new Error("expected group 0"); @@ -2452,7 +2452,7 @@ test("an arrival read takes a replaced copy's buffered group before the new copy const ta = copy(a); const tb = copy(b); front.serve(a.consume()); - const sub = front.consumer.track("seq").subscribe({ delay: { max: 10_000 as track.Delay["max"] } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(10_000) } }); ta.write(0n); expect(drain(sub)).toEqual([0n]); // Both buffered when the read starts: the lower one comes first. @@ -2569,7 +2569,7 @@ function manual() { return { clock, installed: clock.install() }; } -const SECOND = Milli(1000); +const SECOND = Duration.millis(1000); test.each(["lands", "dropped", "expired"])( "an arrival reader gets a group still in flight on the replaced route (%s)", @@ -2593,7 +2593,7 @@ test.each(["lands", "dropped", "expired"])( expect(ta.producer.demand().wanted.peek()).toBeDefined(); if (outcome === "dropped") hooks.dropTrackGroups(ta.producer, 1n, 2n, { error: new NotFound("group") }); - if (outcome === "expired") await clock.advance(Nano.fromMilli(SECOND)); + if (outcome === "expired") await clock.advance(SECOND); if (outcome !== "lands") { // The groups drained above are released once their close settles. await settle(); @@ -2636,7 +2636,7 @@ test("a group read whole still expires once the reader lets go of its copy", asy tb.write(2n); expect(drain(sub)).toEqual([2n]); // Its successor lands on the replaced copy, starting the budget there. - const half = Nano.fromMilli(Milli(SECOND / 2)); + const half = SECOND.div(2); await clock.advance(half); ta.write(1n); drain(sub); @@ -2706,7 +2706,7 @@ test.each([true, false])( const ta = copy(a); const tb = copy(b); front.serve(a.consume()); - const sub = front.consumer.track("seq").subscribe({ delay: { max: Milli(3_600_000) } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(3_600_000) } }); const view = ordered ? sub.ordered() : undefined; const next = () => (view ? view.nextGroup() : sub.recvGroup()); ta.write(0n); @@ -2748,7 +2748,7 @@ test.each([true, false])("a replaced copy backs a group before its first arrival const tb = copy(b); const tc = copy(c); front.serve(a.consume()); - const sub = front.consumer.track("seq").subscribe({ delay: { max: Milli(3_600_000) } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(3_600_000) } }); const view = ordered ? sub.ordered() : undefined; const next = () => (view ? view.nextGroup() : sub.recvGroup()); ta.write(0n); @@ -3031,7 +3031,7 @@ test.each(["lands", "expired"])( expect(sub.closed.peek()).toBeUndefined(); if (outcome === "lands") ta.write(1n); - else await clock.advance(Nano.fromMilli(SECOND)); + else await clock.advance(SECOND); await settle(); // Settled like a direct reader's, with the group that landed still readable. expect(sub.closed.peek()).toBeNull(); @@ -3067,7 +3067,7 @@ test.each([ const ta = copy(a); const tb = copy(b); front.serve(a.consume()); - const sub = front.consumer.track("seq").subscribe({ delay: { max: Milli(3_600_000) } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(3_600_000) } }); const inOrder = ordered ? sub.ordered() : undefined; const read = () => { const sequences: bigint[] = []; @@ -3081,21 +3081,21 @@ test.each([ const asked = () => tb.producer.subscription.peek()?.ranges?.[0]?.start?.absolute; try { sub.withRange({ start: { included: 4n } }); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); for (let sequence = 0n; sequence < 6n; sequence++) ta.write(sequence); expect(read()).toEqual([4n, 5n]); if (cached) for (let sequence = 0n; sequence < 6n; sequence++) tb.write(sequence); front.serve(b.consume()); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); tb.write(6n); expect(read()).toEqual([6n]); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(ta.producer.demand().wanted.peek()).toBeUndefined(); expect(asked()).toBe(5n); sub.withRange({ start: { included: 1n } }); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(asked()).toBe(ordered ? 5n : 1n); if (!cached) { expect(read()).toEqual([]); @@ -3121,7 +3121,7 @@ test("a clean end keeps the serving copy while a group read from a replaced one const ta = copy(a); const tb = copy(b); front.serve(a.consume()); - const sub = front.consumer.track("seq").subscribe({ delay: { max: Milli(3_600_000) } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(3_600_000) } }); try { ta.write(0n); expect(drain(sub)).toEqual([0n]); @@ -3203,7 +3203,7 @@ test("a clean end keeps the serving copy while a group handed out before the swa const ta = copy(a); const tb = copy(b); front.serve(a.consume()); - const sub = front.consumer.track("seq").subscribe({ delay: { max: Milli(3_600_000) } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(3_600_000) } }); try { // Group 0 is handed out while the old route is the only one. const stalled = ta.write(0n, 1, false); @@ -3560,7 +3560,7 @@ test("a resumed reader re-offers a group its serving copy still caches", () => { const a = new BroadcastProducer(); const ta = copy(a); front.serve(a.consume()); - const sub = front.consumer.track("seq").subscribe({ delay: { max: Milli(60_000) } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(60_000) } }); ta.write(0n); expect(drain(sub)).toEqual([0n]); const { groups, givenUp } = hooks.reofferGroups(sub, 0n, 3n); @@ -3579,7 +3579,7 @@ test("a resumed reader takes back its stale reports", () => { const a = new BroadcastProducer(); const ta = copy(a); front.serve(a.consume()); - const sub = front.consumer.track("seq").subscribe({ delay: { max: Milli(60_000) } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(60_000) } }); ta.write(0n); expect(drain(sub)).toEqual([0n]); hooks.dropTrackGroups(ta.producer, 1n, 3n, staleHole(60_000)); @@ -3601,7 +3601,7 @@ test("a resumed reader takes back a replaced route's stale reports", async () => const ta = copy(a); const tb = copy(b); front.serve(a.consume()); - const sub = front.consumer.track("seq").subscribe({ delay: { max: Milli(60_000) } }); + const sub = front.consumer.track("seq").subscribe({ delay: { max: Duration.millis(60_000) } }); ta.write(0n); expect(drain(sub)).toEqual([0n]); hooks.dropTrackGroups(ta.producer, 1n, 3n, staleHole(60_000)); @@ -3641,7 +3641,7 @@ test("routed metadata receives a refusal without polling a group cursor", async outcome = error; }, ); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(outcome).toBeInstanceOf(NotFound); subscriber.close(); request.close(); diff --git a/js/net/src/resume.ts b/js/net/src/resume.ts index a93a52a81b5..0faf9c8c677 100644 --- a/js/net/src/resume.ts +++ b/js/net/src/resume.ts @@ -45,7 +45,7 @@ * * @module */ -import { Instant, Milli, now, sleepUntil } from "@moq/clock"; +import { Duration, Instant, now, sleepUntil } from "@moq/clock"; import { type Dispose, type Getter, race, Signal } from "@moq/signals"; import * as broadcast from "./broadcast.ts"; import { Delivered } from "./delivered.ts"; @@ -141,7 +141,10 @@ const INFO_FIELDS = Object.keys({ /** Two copies claiming the same content must agree on all of it, like Rust's `Info` equality. */ function compatible(a: track.Info, b: track.Info): boolean { const [x, y] = [track.infoDefaults(a), track.infoDefaults(b)]; - return INFO_FIELDS.every((field) => x[field] === y[field]); + return INFO_FIELDS.every((field) => { + const [l, r] = [x[field], y[field]]; + return l instanceof Duration && r instanceof Duration ? l.eq(r) : l === r; + }); } /** @@ -1106,7 +1109,7 @@ class Reader implements ResumeSource { const start = max(cursor.start, copy.floor ?? 0n); if (!hooks.spent(copy.sub, start, undefined, delivered)) return true; // A group read from a copy it replaced may still continue from it. - if (this.#backs(copy, true, grace(this.#budget()))) return true; + if (this.#backs(copy, true, grace(Duration.millis(this.#budget())))) return true; } else { const retains = this.#retains(copy, delivered, edge); if (retains === "wait") waits = true; @@ -1132,7 +1135,7 @@ class Reader implements ResumeSource { // Superseded once the serving copy has a group past the bound. if (copy.since === undefined && end !== undefined && edge !== undefined && edge >= end) copy.since = now(); const budget = this.#budget(); - const wait = grace(budget); + const wait = grace(Duration.millis(budget)); // What is under the bound is past the reader's budget a full budget after a newer group // superseded it, landed or not. if (copy.done === undefined && end !== undefined && !this.#expired(copy, budget)) { @@ -1146,7 +1149,7 @@ class Reader implements ResumeSource { if (hooks.hasUnreadGroup(copy.sub, cursor.start, end, delivered)) return "keep"; } if (copy.lease > 0) return "keep"; - const lands = copy.since !== undefined && !this.#expired(copy, wait); + const lands = copy.since !== undefined && !this.#expired(copy, wait.asMillis()); return this.#backs(copy, lands, wait) ? "keep" : undefined; } @@ -1154,7 +1157,7 @@ class Reader implements ResumeSource { * Whether `copy` holds a group still read, or may yet get it within `wait` when it `lands`: a * failure of the copy that group is read from continues here. */ - #backs(copy: Copy, lands: boolean, wait: Milli): boolean { + #backs(copy: Copy, lands: boolean, wait: Duration): boolean { for (const recover of this.out) { const sequence = recover.sequence; if (hooks.holdsGroup(copy.sub, sequence)) return true; @@ -1186,10 +1189,10 @@ class Reader implements ResumeSource { } } - /** The reader's budget: how far behind a group may fall before it is skipped. */ - #budget(): Milli { + /** The reader's budget in milliseconds: how far behind a group may fall before it is skipped. */ + #budget(): number { const subscription = this.#shell.subscription.peek(); - return subscription ? maxDelayOf(subscription) : Milli.zero; + return subscription ? maxDelayOf(subscription) : 0; } /** @@ -1198,9 +1201,9 @@ class Reader implements ResumeSource { */ #expired(copy: Copy, within: number): boolean { if (copy.since === undefined) return false; - // Plain arithmetic: an unenforced budget is infinite, which no duration brand holds. - const at = copy.since + within * 1_000_000; - if (now() >= at) return true; + // Plain nanoseconds: an unenforced budget is infinite, which no Duration holds. + const at = copy.since.since(Instant.ZERO).asNanos() + within * 1_000_000; + if (now().since(Instant.ZERO).asNanos() >= at) return true; this.#wakeAt(at); return false; } @@ -1212,7 +1215,7 @@ class Reader implements ResumeSource { const timer = new AbortController(); this.#wall = { at, timer }; // A wakeup is never a reason to hold a Node/Bun process open. - void sleepUntil(Instant(at), { signal: timer.signal, ref: false }).then( + void sleepUntil(Instant.ZERO.add(Duration.nanos(at)), { signal: timer.signal, ref: false }).then( () => { if (timer.signal.aborted) return; this.#wall = undefined; @@ -1739,7 +1742,7 @@ class Recover implements GroupRecover { // a copy that failed, once the serving subscription will not deliver the group either. if (outcome && failed && !routeFailed(outcome.error) && !copyFailed(serving)) { const subscription = serving.sub.subscription.peek(); - const maxDelay = subscription ? maxDelayOf(subscription) : Milli.zero; + const maxDelay = Duration.millis(subscription ? maxDelayOf(subscription) : 0); const land = { start: this.sequence, end: this.sequence + 1n, floor: true, grace: grace(maxDelay) }; if (generation === current.generation || !hooks.mayLand(serving.sub, land)) throw outcome.error; landing = new Promise((resolve) => { diff --git a/js/net/src/socket.test.ts b/js/net/src/socket.test.ts index 12c4cc4c421..df430f4821f 100644 --- a/js/net/src/socket.test.ts +++ b/js/net/src/socket.test.ts @@ -1,5 +1,5 @@ import { afterEach, expect, test } from "bun:test"; -import { Manual, Milli, Nano, Second } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { type Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts"; import { accept as acceptConnection } from "./connection/accept.ts"; import { connect } from "./connection/connect.ts"; @@ -136,7 +136,7 @@ test("a peer route replaced between metadata and opening cannot inherit a socket // Both route changes happen before the info promise's continuation opens the session. first.close(); advertise(replacementKeep); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(outcome).toBeInstanceOf(Error); } finally { a.close(); @@ -155,7 +155,7 @@ test("track halves start reliable and ascending, preserve old messages and accep const { local, remote } = await track(); expect((await local.producer.info()).maxAge).toBeUndefined(); expect(remote.consumer.subscription.peek()?.order).toBe("ascending"); - expect(remote.consumer.subscription.peek()?.delay?.max).toBe(Milli(Number.MAX_SAFE_INTEGER)); + expect(remote.consumer.subscription.peek()?.delay?.max).toEqual(Duration.millis(Number.MAX_SAFE_INTEGER)); for (let i = 0; i < 3; i++) local.producer.writeFrame(bytes(i)); local.producer.finish(); const reader = remote.consumer.ordered(); @@ -180,7 +180,7 @@ test("a track session skips dropped groups and keeps the next message", async () group.writeFrame(bytes(7)); group.finish(); local.producer.finish(); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); const frame = await reading; expect(frame?.group).toBe(1n); expect(frame?.payload).toEqual(bytes(7).payload); @@ -220,7 +220,7 @@ test("finished track sessions release their unlisted producers after both halves expect((await remoteReader.readFrame())?.payload).toEqual(bytes(1).payload); expect(await localReader.readFrame()).toBeUndefined(); expect(await remoteReader.readFrame()).toBeUndefined(); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(hooks.trackReleased(local.producer).peek()).toBeNull(); expect(hooks.trackReleased(remote.producer).peek()).toBeNull(); }); @@ -249,7 +249,7 @@ for (const protocol of ["tcp", "track"] as const) { }, ); try { - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); const unverified = await next; expect(unverified.session).toBe(local.session); // A late query has the old name, but the original dial no longer answers. @@ -293,7 +293,7 @@ test("an endpoint announces only the roles it takes, and its client answers only // Bob has not accepted yet, so the dial waits for him to serve. const clock = time(); - await clock.advance(Nano.fromSecond(Second(3600))); + await clock.advance(Duration.secs(3600)); expect(announced(origin, ".server", "bob")).toBeUndefined(); const incoming = b.acceptTcp(); expect(announced(origin, ".server", "bob")).toBeDefined(); @@ -348,7 +348,7 @@ test("cancelled dials leave queues and cannot be accepted later", async () => { const pending = new AbortController(); const dropped = a.dialTcp("bob", { signal: pending.signal }); const observed = dropped.catch((error: unknown) => error); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); pending.abort(); expect(await observed).toBeInstanceOf(Error); const newIncoming = b.acceptTcp(); @@ -364,14 +364,14 @@ test("dial and accept cancellation before announcement release their routing hol const cancel = new AbortController(); const dialing = a.dialTcp("later", { signal: cancel.signal }); const failure = dialing.catch((error: unknown) => error); - await clock.advance(Nano.fromSecond(Second(3600))); + await clock.advance(Duration.secs(3600)); cancel.abort(); expect(await failure).toBeInstanceOf(Error); const next = b.acceptTcp(); const subscriber = await raw(origin, ".server", "bob", "tcp/absent/bob/never-announced"); const accepted = (await next).accept(); const acceptanceFailure = accepted.catch((error: unknown) => error); - await clock.advance(Nano.fromSecond(Second(3600))); + await clock.advance(Duration.secs(3600)); subscriber.close(); expect(await acceptanceFailure).toBeInstanceOf(Error); }); @@ -380,7 +380,7 @@ test("a dial waits for the peer to announce, without an arbitrary timeout", asyn const clock = time(); const { origin, a } = setup(); const dialing = a.dialTcp("later"); - await clock.advance(Nano.fromSecond(Second(3600))); + await clock.advance(Duration.secs(3600)); const later = new Socket.Endpoint(origin, Path.from("room"), "later"); const incoming = await later.acceptTcp(); const remote = await incoming.accept(); @@ -396,11 +396,11 @@ test("accept waits for a delayed dialer announcement only while its original dia const subscriber = await raw(origin, ".server", "bob", "track/late/bob/delayed-announcement"); const incoming = await next; const acceptance = incoming.accept(); - await clock.advance(Nano.fromSecond(Second(3600))); + await clock.advance(Duration.secs(3600)); const route = origin.route(Path.from("room/.client/late"), { hidden: true }); const answer = hooks.reserveUnlistedTrack(route.broadcast, "track/late/bob/delayed-announcement"); route.announce(); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(answer.demand().wanted.peek()).toBeDefined(); const producer = answer.accept({ maxAge: null }); const remote = await acceptance; @@ -486,7 +486,7 @@ test("a second TCP group resets the session even after the first FIN", async () const acceptance = (await next).accept(); // Drive the accept's return subscription before publishing the first half. const clock = time(); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); const producer = answer.accept(); const stream = await acceptance; const group = producer.createGroup(initial); @@ -512,7 +512,7 @@ for (const dropped of [false, true]) { const subscriber = await raw(origin, ".server", "bob", name); const acceptance = (await next).accept(); const clock = time(); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); const producer = answer.accept(); const stream = await acceptance; const reading = stream.consumer.readFrame(); @@ -539,7 +539,7 @@ test("unpaced TCP eviction is an error, never a skipped frame or clean FIN", asy const payload = new Uint8Array(1024 * 1024); for (let i = 0; i < 32; i++) { local.producer.writeFrame({ payload }); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); } local.producer.finish(); await expect(remote.consumer.readFrame()).rejects.toMatchObject({ code: StreamCode.Evicted }); @@ -607,7 +607,7 @@ for (const protocol of ["tcp", "track"] as const) { } staged.producer.finish(); staged.commit(); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); const local = await dialing; const reader = local instanceof Socket.TcpStream ? local.consumer : local.consumer.ordered(); const received: number[] = []; @@ -624,7 +624,7 @@ for (const protocol of ["tcp", "track"] as const) { failure = error; }, ); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(failure).toBeUndefined(); expect(received).toEqual([1, 2, 3]); expect(completed).toBe(true); @@ -670,7 +670,7 @@ for (const alpn of [Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_18, Ietf.ALPN.DRAFT_20, Ie ); try { (await next).reject(); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(outcome).toBeInstanceOf(Error); } finally { a.close(); @@ -712,7 +712,7 @@ for (const alpn of [Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_18, Ietf.ALPN.DRAFT_20, Ie ); try { const incoming = await next; - await clock.advance(Nano.fromSecond(Second(3600))); + await clock.advance(Duration.secs(3600)); expect(outcome).toBeUndefined(); const remote = await incoming.accept(); const local = await dialing; @@ -769,7 +769,7 @@ test("a socket endpoint behind a lite-06 client fails its dials and accepts, not await expect(a.acceptTcp()).rejects.toThrow(unsupported); await expect(a.acceptTrack()).rejects.toThrow(unsupported); // The server's endpoint keeps accepting, and never heard a dial it can't answer. - await clock.advance(Nano.fromSecond(Second(3600))); + await clock.advance(Duration.secs(3600)); expect(heard).toBe(false); // The session's end releases the endpoint: an accept waits again. @@ -784,7 +784,7 @@ test("a socket endpoint behind a lite-06 client fails its dials and accepts, not accepted = error; }, ); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); expect(accepted).toBeUndefined(); a.close(); await accepting; diff --git a/js/net/src/tail.test.ts b/js/net/src/tail.test.ts index 76396bf244e..c730c3a011c 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 { type Installed, Instant, Manual, Milli, Nano } from "@moq/clock"; +import { Duration, type Installed, Instant, Manual } from "@moq/clock"; import { Once } from "@moq/signals"; import { accept, connect } from "./connection/index.ts"; import * as Ietf from "./ietf/index.ts"; @@ -17,7 +17,7 @@ const url = new URL("https://localhost:4443/test"); // Long enough that no group is skipped as stale, and the moq-lite grace for the one group the // IETF case never produces. -const MAX_DELAY = Milli(100); +const MAX_DELAY = Duration.millis(100); async function session(protocol: string) { const pair = createMockTransportPair(protocol); @@ -103,7 +103,7 @@ test.each([Ietf.ALPN.DRAFT_22])("%s: END_OF_TRACK carries the declared end", asy const read = readAll(reader); await clock.drive(reader.closed); // Every counted stream arrived, so nothing waited out the grace. - expect(Nano.toMilli(Instant.durationSince(clock.now(), ended))).toBeLessThan(TAIL_GRACE_MS); + expect(clock.now().since(ended).lt(TAIL_GRACE_MS)).toBe(true); expect(await read).toEqual(["1", "2"]); expect(await reader.closed).toBeNull(); expect(await reader.finished()).toEqual({ group: 4n, frame: 0 }); @@ -113,7 +113,7 @@ test.each([Ietf.ALPN.DRAFT_22])("%s: END_OF_TRACK carries the declared end", asy }); describe("Tail", () => { - const GRACE = Milli(1000); + const GRACE = Duration.millis(1000); let installed: Installed | undefined; afterEach(() => installed?.close()); @@ -122,7 +122,7 @@ describe("Tail", () => { function tail(grace = GRACE) { const clock = new Manual(); installed = clock.install(); - const at = (ms: number) => clock.jump(Nano(Nano.fromMilli(Milli(ms)) - clock.now())); + const at = (to: Duration) => clock.jump(Instant.ZERO.add(to).since(clock.now())); return { at, clock, tail: new Tail({ grace: () => grace }) }; } @@ -130,7 +130,7 @@ describe("Tail", () => { const { at, tail: t } = tail(); t.account(0n, 1n); t.account(2n, 3n); - at(GRACE / 2); + at(GRACE.div(2)); t.account(4n, 5n); expect(t.covers(0n, 3n)).toBe(false); @@ -146,7 +146,7 @@ describe("Tail", () => { const { at, tail: t } = tail(); t.account(0n, 1n); t.account(9n, 10n); - at(GRACE / 2); + at(GRACE.div(2)); t.account(5n, 6n); expect(t.covers(0n, 10n)).toBe(false); @@ -160,20 +160,20 @@ describe("Tail", () => { t.account(3n, 4n); t.account(9n, 10n); - at(GRACE * 2); + at(GRACE.mul(2)); t.demand(1n, 3n); t.account(1n, 2n); expect(t.covers(1n, 4n)).toBe(false); // Only the gap the floor reached restarts. expect(t.covers(3n, 10n)).toBe(true); - at(GRACE * 3); + at(GRACE.mul(3)); t.account(9n, 10n); expect(t.covers(1n, 10n)).toBe(true); }); test("the grace waits for a stream being read", async () => { - const { clock, tail: t } = tail(Milli(10)); + const { clock, tail: t } = tail(Duration.millis(10)); const read = t.open(0n); let settled = false; const settling = t @@ -182,7 +182,7 @@ describe("Tail", () => { settled = true; }); - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); expect(settled).toBe(false); read(); await settling; diff --git a/js/net/src/tail.ts b/js/net/src/tail.ts index 1b87fb6e44d..1235fd55d05 100644 --- a/js/net/src/tail.ts +++ b/js/net/src/tail.ts @@ -1,4 +1,4 @@ -import { type Milli, Nano, now, sleep } from "@moq/clock"; +import { Duration, now, sleep } from "@moq/clock"; import { type GetPromise, Signal } from "@moq/signals"; import { insertRun, type Run, runGaps } from "./internal.ts"; import { GRACE, Ledger } from "./ledger.ts"; @@ -6,7 +6,7 @@ import { GRACE, Ledger } from "./ledger.ts"; /** How a {@link Tail} measures its grace. */ export interface TailOptions { /** How long to wait for a group that cannot be accounted for. Read each time it is needed. */ - grace?: () => Milli; + grace?: () => Duration; } /** @@ -29,7 +29,7 @@ export class Tail { #streams = 0; #active = 0; #changed = new Signal(0); - #grace: () => Milli; + #grace: () => Duration; // Groups whose stream finished since the last update was sent. A lite-07 stale drop under that // update names one only if it was sent before the publisher served the group, so the group won // over it, even once the cache evicted it. @@ -151,7 +151,7 @@ export class Tail { let expired = false; const timer = new AbortController(); - void sleep(Nano.fromMilli(this.#grace()), { signal: timer.signal }).then( + void sleep(this.#grace(), { signal: timer.signal }).then( () => { expired = true; this.#bump(); diff --git a/js/net/src/time.ts b/js/net/src/time.ts index fffb5226661..57a73aa3edb 100644 --- a/js/net/src/time.ts +++ b/js/net/src/time.ts @@ -1,11 +1,11 @@ /** * {@link Timescale} and {@link Timestamp} for presentation timing. * - * Duration units (`Nano`, `Micro`, `Milli`, `Second`) live in `@moq/clock`. + * Durations and instants live in `@moq/clock`. * * @module */ -import { now } from "@moq/clock"; +import { Instant, now } from "@moq/clock"; import { toNumber } from "./util/bigint.ts"; /** Units per second for a {@link Timestamp}'s value, e.g. `1000` for milliseconds. */ @@ -46,7 +46,7 @@ function assertTimestampValue(value: number): void { /** * A presentation timestamp: a raw value in a given {@link Timescale}. * - * Mirrors the Rust `Timestamp`. Unlike `@moq/clock`'s bare duration units it carries its + * Mirrors the Rust `Timestamp`. Unlike a `@moq/clock` `Duration` it carries its * own scale, so a track can pick its units and conversions can't silently mix them up. * * The value must be finite and in `[0, Number.MAX_SAFE_INTEGER]`. Fractions are allowed @@ -71,7 +71,7 @@ export class Timestamp { /** The installed clock's monotonic instant in milliseconds, not wall-clock time. */ static now(): Timestamp { - return new Timestamp(now() / 1_000_000, Timescale.MILLI); + return new Timestamp(now().since(Instant.ZERO).asMillis(), Timescale.MILLI); } /** A timestamp of `ms` milliseconds. */ diff --git a/js/net/src/track.test.ts b/js/net/src/track.test.ts index 42db09bf3ad..3890cfef851 100644 --- a/js/net/src/track.test.ts +++ b/js/net/src/track.test.ts @@ -1,5 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { Manual, Milli, Nano, Wall, yieldNow } from "@moq/clock"; +import { Duration, Instant, Manual, Wall, yieldNow } from "@moq/clock"; import { race } from "@moq/signals"; import { DEFAULT_EXPIRY } from "./cache.ts"; import { ProtocolViolation, Skipped, StreamCode, StreamError, TimestampMismatch, TooFarBehind } from "./error.ts"; @@ -14,7 +14,7 @@ import { unwanted } from "./util/demand.ts"; const enc = new TextEncoder(); const dec = new TextDecoder(); -const CACHE_WINDOW_MS = DEFAULT_EXPIRY; +const CACHE_WINDOW_MS = DEFAULT_EXPIRY.asMillis(); // How late the pool's sweep may reclaim a group nothing writes to: it runs every half window. const SWEEP_LAG_MS = CACHE_WINDOW_MS / 2; @@ -49,12 +49,12 @@ function settle(): Promise { function manualTime(initial: number) { const clock = new Manual(); const installed = clock.install(); - const to = (ms: number) => Nano(Nano.fromMilli(Milli(ms)) - clock.now()); + const to = (ms: number) => Instant.ZERO.add(Duration.millis(ms)).since(clock.now()); clock.jump(to(initial)); return { set: (ms: number) => clock.jump(to(ms)), advance: (ms: number) => clock.advance(to(ms)), - stepWall: (ms: number) => clock.stepWall(Wall(ms)), + stepWall: (ms: number) => clock.stepWall(Wall.UNIX_EPOCH.add(Duration.millis(ms))), installed, }; } @@ -87,7 +87,7 @@ test("ordered reads wait only for subscription-owed groups", () => { try { for (const received of [false, true]) { const producer = received ? receivedTrack() : new TrackProducer("test"); - const reader = producer.subscribe({ delay: { max: Milli(1000) } }).ordered(); + const reader = producer.subscribe({ delay: { max: Duration.millis(1000) } }).ordered(); putGroup(producer, 0n); putGroup(producer, 2n); expect(drainOrdered(reader)).toEqual(received ? [0n] : [0n, 2n]); @@ -105,7 +105,7 @@ test("ordered reads wait only for subscription-owed groups", () => { test("an ordered owed hole wakes exactly at its wall budget", async () => { const clock = manualTime(0); const producer = receivedTrack(); - const reader = producer.subscribe({ delay: { max: Milli(50) } }).ordered(); + const reader = producer.subscribe({ delay: { max: Duration.millis(50) } }).ordered(); try { putGroup(producer, 0n); expect(drainOrdered(reader)).toEqual([0n]); @@ -135,9 +135,9 @@ test("an ordered owed hole wakes exactly at its wall budget", async () => { test("an ordered read skipping a stale group stops waiting on holes below it", () => { const clock = manualTime(0); const producer = receivedTrack(); - const reader = producer.subscribe({ delay: { max: Milli(50) } }).ordered(); + const reader = producer.subscribe({ delay: { max: Duration.millis(50) } }).ordered(); // A wider subscriber keeps the ledger's gaps open past this reader's budget. - const wide = producer.subscribe({ delay: { max: Milli(1000) } }); + const wide = producer.subscribe({ delay: { max: Duration.millis(1000) } }); try { putGroup(producer, 0n); expect(drainOrdered(reader)).toEqual([0n]); @@ -162,7 +162,7 @@ test("an ordered read skipping a stale group stops waiting on holes below it", ( test("an ordered owed hole follows media time and a lower successor", async () => { const clock = manualTime(0); const producer = receivedTrack({ timescale: Timescale.MILLI }); - const reader = producer.subscribe({ delay: { max: Milli(1000) } }).ordered(); + const reader = producer.subscribe({ delay: { max: Duration.millis(1000) } }).ordered(); try { putGroup(producer, 0n, 0); expect(drainOrdered(reader)).toEqual([0n]); @@ -198,7 +198,7 @@ test("an ordered owed hole follows media time and a lower successor", async () = test("an ordered owed hole wakes when its ledger gap folds", async () => { const clock = manualTime(0); const producer = receivedTrack(); - const reader = producer.subscribe({ delay: { max: Milli(50) } }).ordered(); + const reader = producer.subscribe({ delay: { max: Duration.millis(50) } }).ordered(); try { putGroup(producer, 0n); expect(drainOrdered(reader)).toEqual([0n]); @@ -228,28 +228,28 @@ test("an ordered owed hole wakes when its ledger gap folds", async () => { test("ordered owed holes follow zero, narrowed, unlimited, and publisher budgets", async () => { const clock = manualTime(0); try { - for (const maxDelay of [Milli.zero, Milli(1000), null]) { + for (const maxDelay of [Duration.ZERO, Duration.millis(1000), null]) { const producer = receivedTrack(); const reader = producer.subscribe({ delay: { max: maxDelay } }).ordered(); putGroup(producer, 0n); expect(drainOrdered(reader)).toEqual([0n]); putGroup(producer, 2n); - expect(drainOrdered(reader)).toEqual(maxDelay === 0 ? [2n] : []); + expect(drainOrdered(reader)).toEqual(maxDelay?.isZero() ? [2n] : []); if (maxDelay === null) { await clock.advance(3_600_000); expect(drainOrdered(reader)).toEqual([]); putGroup(producer, 1n); expect(drainOrdered(reader)).toEqual([1n, 2n]); - } else if (maxDelay > 0) { + } else if (!maxDelay.isZero()) { const pending = reader.nextGroup(); - reader.update({ delay: { max: Milli.zero } }); + reader.update({ delay: { max: Duration.ZERO } }); expect((await pending)?.sequence).toBe(2n); } reader.close(); producer.finish(); producer.close(); } - const producer = receivedTrack({ maxAge: Milli(50) }); + const producer = receivedTrack({ maxAge: Duration.millis(50) }); const reader = producer.subscribe({ delay: { max: null } }).ordered(); putGroup(producer, 0n); putGroup(producer, 2n); @@ -436,12 +436,12 @@ test("rescale matches the track's timeline, rounded down as Rust's convert does" test("subscriber options and updates are forwarded to the producer's aggregate", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ delay: { max: Milli.zero }, ranges: [{ start: { absolute: 0n } }] }); + const track = producer.subscribe({ delay: { max: Duration.ZERO }, ranges: [{ start: { absolute: 0n } }] }); // The initial options are available before the request is accepted or put on the wire. expect(producer.subscription.peek()).toEqual({ priority: 0, - delay: { min: Milli(0), max: Milli(0) }, + delay: { min: Duration.millis(0), max: Duration.millis(0) }, order: "descending", ranges: [{ start: { absolute: 0n } }], }); @@ -450,13 +450,13 @@ test("subscriber options and updates are forwarded to the producer's aggregate", const next = producer.subscription.changed(); track.update({ priority: 7, - delay: { max: Milli(250) }, + delay: { max: Duration.millis(250) }, order: "ascending", ranges: [{ start: { absolute: 2n }, end: { absolute: 9n } }], }); expect(await next).toEqual({ priority: 7, - delay: { min: Milli(0), max: Milli(250) }, + delay: { min: Duration.millis(0), max: Duration.millis(250) }, order: "ascending", ranges: [{ start: { absolute: 2n }, end: { absolute: 9n } }], }); @@ -464,20 +464,20 @@ test("subscriber options and updates are forwarded to the producer's aggregate", test("subscriber maxAge and maxDelay are refused before defaults or updates take effect", () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ delay: { max: Milli(250) } }); + const track = producer.subscribe({ delay: { max: Duration.millis(250) } }); const original = producer.subscription.peek(); - for (const maxAge of [Milli(500), undefined]) { + for (const maxAge of [Duration.millis(500), undefined]) { expect(() => producer.subscribe({ maxAge } as Subscription)).toThrow("delay.max"); - const options = { maxDelay: Milli(100), maxAge } as Subscription; + const options = { maxDelay: Duration.millis(100), maxAge } as Subscription; expect(() => producer.subscribe(options)).toThrow(TypeError); expect(() => track.update(options)).toThrow("delay.max"); - expect(() => producer.subscribe({ maxDelay: Milli(100) } as Subscription)).toThrow("delay.max"); + expect(() => producer.subscribe({ maxDelay: Duration.millis(100) } as Subscription)).toThrow("delay.max"); expect(producer.subscription.peek()).toEqual(original); } // The publisher's own staleness bound keeps its distinct maxAge field. - producer.accept({ maxAge: Milli(500) }); + producer.accept({ maxAge: Duration.millis(500) }); track.close(); producer.finish(); producer.close(); @@ -498,34 +498,28 @@ test("a fractional delay is rounded up before the wire sees it", async () => { // Subscribers derive this from measurements (a jitter estimate scaled off RTT), so a // fractional millisecond is expected. The wire encodes it as a varint, which throws on a // non-integer, and rounding down would shorten a budget the subscriber asked for. - const track = producer.subscribe({ delay: { max: Milli(38.75) } }); - expect(producer.subscription.peek()?.delay?.max).toBe(Milli(39)); + const track = producer.subscribe({ delay: { max: Duration.millis(38.75) } }); + expect(producer.subscription.peek()?.delay?.max).toEqual(Duration.millis(39)); const next = producer.subscription.changed(); - track.update({ delay: { max: Milli(500.25) } }); - expect((await next)?.delay?.max).toBe(Milli(501)); + track.update({ delay: { max: Duration.millis(500.25) } }); + expect((await next)?.delay?.max).toEqual(Duration.millis(501)); const min = producer.subscription.changed(); - track.update({ delay: { min: Milli(99.5) } }); - expect((await min)?.delay?.min).toBe(Milli(100)); + track.update({ delay: { min: Duration.millis(99.5) } }); + expect((await min)?.delay?.min).toEqual(Duration.millis(100)); // The publisher half of the budget lands on the wire through TRACK_INFO, with the same hazard. - producer.accept({ maxAge: Milli(1000.5) }); - expect((await producer.info()).maxAge).toBe(Milli(1001)); + producer.accept({ maxAge: Duration.millis(1000.5) }); + expect((await producer.info()).maxAge).toEqual(Duration.millis(1001)); }); -test("a delay or maxAge that is not a duration is refused, not rounded into one", () => { +test("a delay or maxAge past the wire's millisecond range is refused", () => { const producer = new TrackProducer("test"); - // The wire carries an unsigned varint, so rounding these would encode a budget the - // caller never asked for: -0.5 would ceil to zero and silently take the live edge. - expect(() => producer.subscribe({ delay: { max: -0.5 as Milli } })).toThrow(RangeError); - expect(() => producer.subscribe({ delay: { max: -100 as Milli } })).toThrow(RangeError); - expect(() => producer.subscribe({ delay: { max: Number.NaN as Milli } })).toThrow(RangeError); - expect(() => producer.subscribe({ delay: { min: -1 as Milli } })).toThrow(RangeError); - expect(() => producer.subscribe({ delay: { max: Number.POSITIVE_INFINITY as Milli } })).toThrow(RangeError); - expect(() => producer.accept({ maxAge: -0.5 as Milli })).toThrow(RangeError); - expect(() => producer.accept({ maxAge: Milli(Number.MAX_SAFE_INTEGER + 1) })).toThrow(RangeError); - expect(() => producer.subscribe({ delay: { max: Milli(Number.MAX_SAFE_INTEGER + 1) } })).toThrow(RangeError); + expect(() => producer.accept({ maxAge: Duration.millis(Number.MAX_SAFE_INTEGER + 1) })).toThrow(RangeError); + expect(() => producer.subscribe({ delay: { max: Duration.millis(Number.MAX_SAFE_INTEGER + 1) } })).toThrow( + RangeError, + ); }); test("priority -128..=127 is accepted and anything outside is refused", () => { @@ -541,17 +535,21 @@ test("priority -128..=127 is accepted and anything outside is refused", () => { test("infoDefaults re-validates timescale and the safe maxAge bound", () => { expect(infoDefaults({ timescale: Timescale.MICRO }).timescale).toBe(Timescale.MICRO); - expect(infoDefaults({ maxAge: Milli(Number.MAX_SAFE_INTEGER) }).maxAge).toBe(Milli(Number.MAX_SAFE_INTEGER)); + expect(infoDefaults({ maxAge: Duration.millis(Number.MAX_SAFE_INTEGER) }).maxAge).toEqual( + Duration.millis(Number.MAX_SAFE_INTEGER), + ); expect(() => infoDefaults({ timescale: 0 as Timescale })).toThrow(RangeError); expect(() => infoDefaults({ timescale: (Number.MAX_SAFE_INTEGER + 1) as Timescale })).toThrow(RangeError); - expect(() => infoDefaults({ maxAge: Milli(Number.MAX_SAFE_INTEGER + 1) })).toThrow(RangeError); + expect(() => infoDefaults({ maxAge: Duration.millis(Number.MAX_SAFE_INTEGER + 1) })).toThrow(RangeError); }); test("an authored track defaults to a zero max age, null is unlimited, and decoded absence stays unlimited", async () => { - expect((await new TrackProducer("omitted").accept().info()).maxAge).toBe(Milli.zero); - expect((await new TrackProducer("undefined").accept({ maxAge: undefined }).info()).maxAge).toBe(Milli.zero); + expect((await new TrackProducer("omitted").accept().info()).maxAge).toEqual(Duration.ZERO); + expect((await new TrackProducer("undefined").accept({ maxAge: undefined }).info()).maxAge).toEqual(Duration.ZERO); expect((await new TrackProducer("unlimited").accept({ maxAge: null }).info()).maxAge).toBeUndefined(); - expect((await new TrackProducer("explicit").accept({ maxAge: Milli(5000) }).info()).maxAge).toBe(Milli(5000)); + expect((await new TrackProducer("explicit").accept({ maxAge: Duration.millis(5000) }).info()).maxAge).toEqual( + Duration.millis(5000), + ); expect(authoredInfo({ maxAge: null }).maxAge).toBeUndefined(); // Decoded metadata has no authored default: absence is no publisher limit. expect(infoDefaults({}).maxAge).toBeUndefined(); @@ -565,7 +563,7 @@ test("a sole snapshot stays readable to a late joiner at the zero default max ag const clock = manualTime(10_000); const producer = new TrackProducer("catalog").accept({ timescale: Timescale.MILLI, compress: true }); try { - expect((await producer.info()).maxAge).toBe(Milli.zero); + expect((await producer.info()).maxAge).toEqual(Duration.ZERO); const group = producer.appendGroup(); group.writeFrame(textFrame("snapshot", Timestamp.fromMillis(0))); group.finish(); @@ -599,23 +597,26 @@ test("multiple subscriber options aggregate like Rust", async () => { const producer = new TrackProducer("test"); const bounded = producer.subscribe({ priority: 2, - delay: { min: Milli(400), max: Milli(100) }, + delay: { min: Duration.millis(400), max: Duration.millis(100) }, order: "ascending", ranges: [{ start: { absolute: 10n }, end: { absolute: 20n } }], }); const live = producer.subscribe({ priority: 7, - delay: { min: Milli(50), max: Milli(250) }, + delay: { min: Duration.millis(50), max: Duration.millis(250) }, ranges: [{ start: { absolute: 5n } }], }); // A minimum that went unstated, as a legacy peer's does, never pulls the smallest to zero. - const legacy = producer.subscribe({ delay: { min: null, max: Milli(0) }, ranges: [{ start: { absolute: 5n } }] }); + const legacy = producer.subscribe({ + delay: { min: null, max: Duration.millis(0) }, + ranges: [{ start: { absolute: 5n } }], + }); // One descending subscriber makes the aggregate descending, so a live reader is never held // behind another's backlog. expect(producer.subscription.peek()).toEqual({ priority: 7, - delay: { min: Milli(50), max: Milli(250) }, + delay: { min: Duration.millis(50), max: Duration.millis(250) }, order: "descending", ranges: [{ start: { absolute: 5n } }], }); @@ -625,7 +626,7 @@ test("multiple subscriber options aggregate like Rust", async () => { live.close(); expect(await narrowed).toEqual({ priority: 2, - delay: { min: Milli(400), max: Milli(100) }, + delay: { min: Duration.millis(400), max: Duration.millis(100) }, order: "ascending", ranges: [{ start: { absolute: 10n }, end: { absolute: 20n } }], }); @@ -719,7 +720,10 @@ test("a bounded read on a subscribed copy ends once its feed stops owing a hole" const clock = manualTime(0); try { const producer = receivedTrack(); - const reader = producer.subscribe({ delay: { max: Milli(1000) }, ranges: [{ end: { absolute: 3n } }] }); + const reader = producer.subscribe({ + delay: { max: Duration.millis(1000) }, + ranges: [{ end: { absolute: 3n } }], + }); putGroup(producer, 0n); putGroup(producer, 2n); expect(reader.tryRecvGroup()?.sequence).toBe(0n); @@ -889,8 +893,8 @@ test("an untimed track or a moq-transport copy refuses a time anchor", () => { test("only unstated minimums aggregate to an unstated one", () => { const producer = new TrackProducer("test"); producer.subscribe({ delay: { min: null } }); - producer.subscribe({ delay: { min: null, max: Milli(250) } }); - expect(producer.subscription.peek()?.delay).toEqual({ min: null, max: Milli(250) }); + producer.subscribe({ delay: { min: null, max: Duration.millis(250) } }); + expect(producer.subscription.peek()?.delay).toEqual({ min: null, max: Duration.millis(250) }); }); // A resume floor above the live edge must not hide the latest group from a reader that @@ -906,24 +910,24 @@ test("the producer aggregate is not clamped to the track's maxAge", () => { // The publisher applies its own, so a subscriber asking upstream before the info lands // asks for the same demand after it. const producer = new TrackProducer("test"); - const track = producer.subscribe({ delay: { max: Milli(10_000) } }); + const track = producer.subscribe({ delay: { max: Duration.millis(10_000) } }); const before = producer.subscription.peek(); - producer.accept({ timescale: Timescale.MILLI, maxAge: Milli(2_000) }); + producer.accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(2_000) }); expect(producer.subscription.peek()).toEqual(before); - expect(producer.subscription.peek()?.delay?.max).toBe(Milli(10_000)); - expect(track.subscription.peek()?.delay?.max).toBe(Milli(10_000)); + expect(producer.subscription.peek()?.delay?.max).toEqual(Duration.millis(10_000)); + expect(track.subscription.peek()?.delay?.max).toEqual(Duration.millis(10_000)); // A late group is waited for no longer than the publisher keeps it fresh. - expect(hooks.tailGrace(producer)).toBe(Milli(2_000)); + expect(hooks.tailGrace(producer)).toEqual(Duration.millis(2_000)); }); test("a null delay.max dominates when subscriptions combine", () => { const producer = new TrackProducer("test"); producer.subscribe({ delay: { max: null } }); - producer.subscribe({ delay: { max: Milli(250) } }); + producer.subscribe({ delay: { max: Duration.millis(250) } }); // The most tolerant subscriber wins the aggregate, so no limit dominates. - expect(producer.subscription.peek()?.delay?.max).toBe(Milli(Number.MAX_SAFE_INTEGER)); + expect(producer.subscription.peek()?.delay?.max).toEqual(Duration.millis(Number.MAX_SAFE_INTEGER)); }); test("nextGroup skips late arrivals", async () => { @@ -946,7 +950,7 @@ test("nextGroup skips late arrivals", async () => { test("nextGroup returns buffered groups in sequence", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ delay: { max: Milli(5000) } }).ordered(); + const track = producer.subscribe({ delay: { max: Duration.millis(5000) } }).ordered(); producer.createGroup(3n); producer.createGroup(5n); @@ -959,7 +963,7 @@ test.each([false, true])("a reordered tail keeps the group PTS drift verdict (B- const clock = manualTime(0); try { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: null }); - const subscriber = producer.subscribe({ delay: { max: Milli(80) } }); + const subscriber = producer.subscribe({ delay: { max: Duration.millis(80) } }); for (const ms of [0, 100]) { const group = producer.appendGroup(); group.writeFrame({ payload: new Uint8Array(), timestamp: Timestamp.fromMillis(ms) }); @@ -984,8 +988,8 @@ test.each([false, true])("a reordered tail keeps the group PTS drift verdict (B- // is level with the live edge still owes the reader every frame in it, so judging it by // its first timestamp would discard exactly the group being filled. test("a long group is not stale while its tail reaches the edge", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(5000) }); - const sub = producer.subscribe({ delay: { max: Milli(500) } }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); + const sub = producer.subscribe({ delay: { max: Duration.millis(500) } }); // Group 0 spans 0..2000ms; group 1 starts at 2000ms, where group 0 ends. const long = producer.appendGroup(); @@ -1000,8 +1004,8 @@ test("a long group is not stale while its tail reaches the edge", async () => { }); test("a long group is stale once its successor falls behind", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(5000) }); - const sub = producer.subscribe({ delay: { max: Milli(500) } }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); + const sub = producer.subscribe({ delay: { max: Duration.millis(500) } }); const long = producer.appendGroup(); for (const ms of [0, 500, 1000]) { @@ -1023,7 +1027,7 @@ test("a long group is stale once its successor falls behind", async () => { // Both cursors write a backlog off: a buffered group is not free to deliver, since a // consumer reading one that is already too old plays it at 1x and never catches up. test("the latency budget skips a buffered timeline on either cursor", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(5000) }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); const arrival = producer.subscribe(); const ordered = producer.subscribe().ordered(); @@ -1035,7 +1039,7 @@ test("the latency budget skips a buffered timeline on either cursor", async () = expect((await ordered.nextGroup())?.sequence).toBe(2n); // The budget is the only gate: one that spans the backlog bursts it in order. - const replay = producer.subscribe({ delay: { max: Milli(30_000) } }).ordered(); + const replay = producer.subscribe({ delay: { max: Duration.millis(30_000) } }).ordered(); expect((await replay.nextGroup())?.sequence).toBe(0n); expect((await replay.nextGroup())?.sequence).toBe(1n); expect((await replay.nextGroup())?.sequence).toBe(2n); @@ -1045,9 +1049,9 @@ test("the latency budget skips a buffered timeline on either cursor", async () = // it. That bound is sound: the frameless group's first frame is checked to start at or below // the next group's, so the true reach can only be earlier. test("a frameless successor leaves the next started group as the bound", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(5000) }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); // Any budget, so only media time judges: the wall clock barely moves here. - const track = producer.subscribe({ delay: { max: Milli(500) } }); + const track = producer.subscribe({ delay: { max: Duration.millis(500) } }); producer.writeFrame({ payload: enc.encode("0"), timestamp: Timestamp.fromMillis(0) }); producer.appendGroup(); // seq 1 stalls before its first frame @@ -1061,8 +1065,8 @@ test("a frameless successor leaves the next started group as the bound", async ( // Groups can arrive out of sequence order; the immediate successor bounds reach even when it // arrived last. test("a late-arriving successor bounds a group's reach", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(5000) }); - const track = producer.subscribe({ delay: { max: Milli(500) } }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); + const track = producer.subscribe({ delay: { max: Duration.millis(500) } }); for (const [sequence, ms] of [ [0n, 0], @@ -1083,8 +1087,8 @@ test("a late-arriving successor bounds a group's reach", async () => { // The ordered frame helpers ride the same cursor, so they see the same budget: a // backlog inside it is drained in full, and what is past it is skipped. test("ordered frame reads follow the budget", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(5000) }); - const ordered = producer.subscribe({ delay: { max: Milli(5000) } }).ordered(); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); + const ordered = producer.subscribe({ delay: { max: Duration.millis(5000) } }).ordered(); const live = producer.subscribe().ordered(); for (const timestamp of [0, 1000, 2000]) { @@ -1104,7 +1108,7 @@ test("ordered frame reads follow the budget", async () => { for (const take of ["nextGroup", "tryNextGroup"] as const) { test(`${take} abandons the frame helpers' group when it passes it`, async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ delay: { max: Milli(5000) } }).ordered(); + const track = producer.subscribe({ delay: { max: Duration.millis(5000) } }).ordered(); const zero = producer.createGroup(0n); zero.writeFrame(textFrame("0.0")); @@ -1134,7 +1138,7 @@ for (const take of ["nextGroup", "tryNextGroup"] as const) { // after a higher one was read is skipped, never fed to the caller backwards. test("ordered frame reads skip a late lower-sequence group", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ delay: { max: Milli(5000) } }).ordered(); + const track = producer.subscribe({ delay: { max: Duration.millis(5000) } }).ordered(); const five = producer.createGroup(5n); five.writeFrame(textFrame("five", Timestamp.fromMillis(5))); @@ -1155,7 +1159,10 @@ test("ordered frame reads skip a late lower-sequence group", async () => { test("zero latency takes the latest group when ages are equal", async () => { const clock = manualTime(10_000); try { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(5000) }); + const producer = new TrackProducer("test").accept({ + timescale: Timescale.MILLI, + maxAge: Duration.millis(5000), + }); const track = producer.subscribe(); producer.writeFrame(textFrame("old")); producer.writeFrame(textFrame("new")); @@ -1169,11 +1176,11 @@ test("zero latency takes the latest group when ages are equal", async () => { test("an omitted delay is the default zero, and a null max sets no limit", async () => { expect(Subscription.default()).toEqual({ priority: 0, - delay: { min: Milli.zero, max: Milli.zero }, + delay: { min: Duration.ZERO, max: Duration.ZERO }, order: "descending", }); - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(5000) }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); const explicit = producer.subscribe(Subscription.default()); const implicit = producer.subscribe(); const bare = producer.subscribe({}); @@ -1185,20 +1192,20 @@ test("an omitted delay is the default zero, and a null max sets no limit", async expect((await explicit.recvGroup())?.sequence).toBe(2n); expect((await implicit.recvGroup())?.sequence).toBe(2n); expect((await bare.recvGroup())?.sequence).toBe(2n); - expect(producer.subscription.peek()?.delay?.max).toBe(Milli.zero); + expect(producer.subscription.peek()?.delay?.max).toEqual(Duration.ZERO); // An explicit null leaves the publisher's max age as the only bound. const unlimited = producer.subscribe({ delay: { max: null } }); for (const sequence of [0n, 1n, 2n]) expect((await unlimited.recvGroup())?.sequence).toBe(sequence); - expect(producer.subscription.peek()?.delay?.max).toBe(Milli(Number.MAX_SAFE_INTEGER)); - expect(hooks.tailGrace(producer)).toBe(Milli(5000)); + expect(producer.subscription.peek()?.delay?.max).toEqual(Duration.millis(Number.MAX_SAFE_INTEGER)); + expect(hooks.tailGrace(producer)).toEqual(Duration.millis(5000)); producer.finish(); producer.close(); }); test("latency budget admits groups within its presentation-time window", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(5000) }); - const track = producer.subscribe({ delay: { max: Milli(1500) } }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); + const track = producer.subscribe({ delay: { max: Duration.millis(1500) } }); for (const timestamp of [0, 1000, 2000]) { producer.writeFrame({ payload: enc.encode(`${timestamp}`), timestamp: Timestamp.fromMillis(timestamp) }); @@ -1211,7 +1218,7 @@ test("latency budget admits groups within its presentation-time window", async ( }); test("a late lower group within the budget is delivered", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(30_000) }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(30_000) }); for (const [sequence, timestamp] of [ [5n, 1000], [6n, 2000], @@ -1222,7 +1229,7 @@ test("a late lower group within the budget is delivered", async () => { group.finish(); } - const track = producer.subscribe({ delay: { max: Milli(5000) } }); + const track = producer.subscribe({ delay: { max: Duration.millis(5000) } }); expect((await track.recvGroup())?.sequence).toBe(5n); expect((await track.recvGroup())?.sequence).toBe(6n); expect((await track.recvGroup())?.sequence).toBe(7n); @@ -1241,25 +1248,28 @@ test("a late lower group within the budget is delivered", async () => { }); test("a named start is a floor, not a request", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(30_000) }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(30_000) }); for (const timestamp of [0, 1000, 2000, 3000, 4000]) { producer.writeFrame({ payload: enc.encode(`${timestamp}`), timestamp: Timestamp.fromMillis(timestamp) }); } // The budget is the only thing that asks for data; a named start only bounds how far // back it may reach. - const floored = producer.subscribe({ ranges: [{ start: { absolute: 3n } }], delay: { max: Milli(60_000) } }); + const floored = producer.subscribe({ + ranges: [{ start: { absolute: 3n } }], + delay: { max: Duration.millis(60_000) }, + }); expect((await floored.recvGroup())?.sequence).toBe(3n); expect((await floored.recvGroup())?.sequence).toBe(4n); // Naming group 1 at real time still delivers the live edge alone: the zero budget // calls everything older stale. - const named = producer.subscribe({ delay: { max: Milli.zero }, ranges: [{ start: { absolute: 1n } }] }); + const named = producer.subscribe({ delay: { max: Duration.ZERO }, ranges: [{ start: { absolute: 1n } }] }); expect((await named.recvGroup())?.sequence).toBe(4n); }); test("the ordered cursor sheds a stale backlog", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(30_000) }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(30_000) }); for (const timestamp of [0, 1000, 2000, 3000]) { producer.writeFrame({ payload: enc.encode(`${timestamp}`), timestamp: Timestamp.fromMillis(timestamp) }); } @@ -1271,21 +1281,21 @@ test("the ordered cursor sheds a stale backlog", async () => { // Only what is provably too old goes. Group 0 reaches 1s, a full 2s behind the 3s // edge; group 1 reaches 2s and could still present inside a 1.5s budget. - const bounded = producer.subscribe({ delay: { max: Milli(1500) } }).ordered(); + const bounded = producer.subscribe({ delay: { max: Duration.millis(1500) } }).ordered(); expect((await bounded.nextGroup())?.sequence).toBe(1n); expect((await bounded.nextGroup())?.sequence).toBe(2n); expect((await bounded.nextGroup())?.sequence).toBe(3n); // A budget spanning the history still bursts it in full, gap-free. - const replay = producer.subscribe({ delay: { max: Milli(30_000) } }).ordered(); + const replay = producer.subscribe({ delay: { max: Duration.millis(30_000) } }).ordered(); for (const sequence of [0n, 1n, 2n, 3n]) { expect((await replay.nextGroup())?.sequence).toBe(sequence); } }); test("the budget is clamped to the publisher's maxAge", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(1500) }); - const track = producer.subscribe({ delay: { max: Milli(60_000) } }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(1500) }); + const track = producer.subscribe({ delay: { max: Duration.millis(60_000) } }); // Spaced so group 0's reach (2s) sits 2s behind the edge (4s): outside the // publisher's 1.5s window, inside the subscriber's requested minute. @@ -1303,7 +1313,10 @@ test("the budget is clamped to the publisher's maxAge", async () => { test("a stamped successor expires a group stalled before its first frame", async () => { const clock = manualTime(10_000); try { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(5000) }); + const producer = new TrackProducer("test").accept({ + timescale: Timescale.MILLI, + maxAge: Duration.millis(5000), + }); const track = producer.subscribe(); producer.appendGroup(); // seq 0 has no timestamp @@ -1328,7 +1341,7 @@ test("real time reads a live stream without truncating it", async () => { // close and the next group's first frame are separate events. A zero budget gives up // there, and the group fails with Old since its producer never closed it, but only // after the reader took every frame. - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(60_000) }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(60_000) }); const track = producer.subscribe(); let open = producer.appendGroup(); @@ -1381,8 +1394,8 @@ test("a budget is measured from the reader's position", async () => { // for. A straggling frame of the old group must still reach it. Measuring from the // group's first frame instead makes the drift 2000ms, so a budget shorter than one // GOP would drop the tail of every GOP. - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(60_000) }); - const track = producer.subscribe({ delay: { max: Milli(1000) } }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(60_000) }); + const track = producer.subscribe({ delay: { max: Duration.millis(1000) } }); const open = producer.appendGroup(); open.writeFrame({ payload: enc.encode("key"), timestamp: Timestamp.fromMillis(0) }); @@ -1408,7 +1421,10 @@ test("a budget is measured from the reader's position", async () => { test("a handed-out group still expires while its first frame is stalled", async () => { const clock = manualTime(10_000); try { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(5000) }); + const producer = new TrackProducer("test").accept({ + timescale: Timescale.MILLI, + maxAge: Duration.millis(5000), + }); const track = producer.subscribe(); producer.appendGroup(); @@ -1431,7 +1447,7 @@ test("a handed-out group still expires while its first frame is stalled", async test("committing track info wakes a group newly past the publisher's maxAge", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ delay: { max: Milli(10_000) } }); + const track = producer.subscribe({ delay: { max: Duration.millis(10_000) } }); const source = producer.appendGroup(); source.writeFrame({ payload: enc.encode("old"), timestamp: Timestamp.fromMillis(0) }); @@ -1445,13 +1461,13 @@ test("committing track info wakes a group newly past the publisher's maxAge", as // bounded by where its successor begins, so the successor alone never convicts it. producer.writeFrame({ payload: enc.encode("later"), timestamp: Timestamp.fromMillis(2_000) }); await settle(); - producer.accept({ timescale: Timescale.MILLI, maxAge: Milli(100) }); + producer.accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(100) }); await expect(waiting).rejects.toMatchObject({ code: StreamCode.Old }); }); test("a handed-out group reports its expiry to a writer racing it", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(5000) }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); const track = producer.subscribe(); producer.writeFrame(textFrame("old")); @@ -1468,8 +1484,8 @@ test("a handed-out group reports its expiry to a writer racing it", async () => }); test("a frame still being written is judged against the budget", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(100) }); - const track = producer.subscribe({ delay: { max: Milli(100) } }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(100) }); + const track = producer.subscribe({ delay: { max: Duration.millis(100) } }); const source = producer.appendGroup(); source.writeFrame({ payload: enc.encode("old"), timestamp: Timestamp.fromMillis(0) }); source.writeFrame({ payload: enc.encode("future"), timestamp: Timestamp.fromMillis(10_000) }); @@ -1492,7 +1508,7 @@ test("a fully read group still reports its expiry", async () => { const clock = manualTime(10_000); const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: null }); try { - const track = producer.subscribe({ delay: { max: Milli(1000) } }); + const track = producer.subscribe({ delay: { max: Duration.millis(1000) } }); const source = producer.appendGroup(); source.writeFrame({ payload: enc.encode("a"), timestamp: Timestamp.fromMillis(0) }); source.finish(); @@ -1523,7 +1539,7 @@ test("a fully read group still reports its expiry", async () => { }); test("a drained group finishes cleanly after the live edge advances", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(5000) }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); const track = producer.subscribe(); producer.writeFrame(textFrame("old")); @@ -1543,16 +1559,16 @@ test("a drained group finishes cleanly after the live edge advances", async () = // holds them, since two seconds is well inside its idle window: this is staleness, not eviction. test("a stalled track serves only its newest group", () => { const clock = manualTime(10_000); - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(1000) }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(1000) }); try { for (const millis of [0, 10, 20]) { producer.writeFrame({ payload: enc.encode(`${millis}`), timestamp: Timestamp.fromMillis(millis) }); } - expect(drain(producer.subscribe({ delay: { max: Milli(1000) } }))).toEqual([0n, 1n, 2n]); + expect(drain(producer.subscribe({ delay: { max: Duration.millis(1000) } }))).toEqual([0n, 1n, 2n]); // Nothing is written again: media time stands still. clock.set(12_000); - expect(drain(producer.subscribe({ delay: { max: Milli(1000) } }))).toEqual([2n]); + expect(drain(producer.subscribe({ delay: { max: Duration.millis(1000) } }))).toEqual([2n]); } finally { producer.finish(); producer.close(); @@ -1574,11 +1590,11 @@ test("frozen timestamps still age out by wall clock", () => { frame(); // Group 0's successor arrived 800ms ago, group 1's just now. - expect(drain(producer.subscribe({ delay: { max: Milli(1000) } }))).toEqual([0n, 1n, 2n]); + expect(drain(producer.subscribe({ delay: { max: Duration.millis(1000) } }))).toEqual([0n, 1n, 2n]); clock.set(11_500); - expect(drain(producer.subscribe({ delay: { max: Milli(1000) } }))).toEqual([1n, 2n]); + expect(drain(producer.subscribe({ delay: { max: Duration.millis(1000) } }))).toEqual([1n, 2n]); clock.set(12_500); - expect(drain(producer.subscribe({ delay: { max: Milli(1000) } }))).toEqual([2n]); + expect(drain(producer.subscribe({ delay: { max: Duration.millis(1000) } }))).toEqual([2n]); } finally { producer.finish(); producer.close(); @@ -1597,7 +1613,7 @@ test("a startup burst ages out by media time", () => { } // Group N reaches N + 1 seconds against the 4s edge: groups 0 and 1 are 3s and 2s // behind, past 1.5s. Their successors arrived just now. - expect(drain(producer.subscribe({ delay: { max: Milli(1500) } }))).toEqual([2n, 3n, 4n]); + expect(drain(producer.subscribe({ delay: { max: Duration.millis(1500) } }))).toEqual([2n, 3n, 4n]); } finally { producer.finish(); producer.close(); @@ -1612,7 +1628,7 @@ test("a parked read wakes at its wall deadline", async () => { const clock = manualTime(10_000); const producer = new TrackProducer("test").accept({ timescale, maxAge: null }); try { - const track = producer.subscribe({ delay: { max: Milli(1000) } }); + const track = producer.subscribe({ delay: { max: Duration.millis(1000) } }); const held = producer.appendGroup(); held.writeFrame({ payload: enc.encode("x"), timestamp: timescale && Timestamp.fromMillis(0) }); const group = track.tryRecvGroup(); @@ -1650,7 +1666,7 @@ test("an evicted successor with unread frames still starts the wall clock", asyn const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: null }); try { const budget = 2 * CACHE_WINDOW_MS; - const track = producer.subscribe({ delay: { max: Milli(budget) } }); + const track = producer.subscribe({ delay: { max: Duration.millis(budget) } }); const write = () => { const group = producer.appendGroup(); group.writeFrame({ payload: enc.encode("x"), timestamp: Timestamp.fromMillis(0) }); @@ -1692,7 +1708,7 @@ test("a failed successor hands the wall clock on after the cache evicts it", asy const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: null }); try { const budget = 2 * CACHE_WINDOW_MS; - const track = producer.subscribe({ delay: { max: Milli(budget) } }); + const track = producer.subscribe({ delay: { max: Duration.millis(budget) } }); const held = producer.appendGroup(); held.writeFrame({ payload: enc.encode("x"), timestamp: Timestamp.fromMillis(0) }); held.finish(); @@ -1738,18 +1754,18 @@ test("a run of empty groups ages out by wall clock", () => { const clock = manualTime(10_000); const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: null }); try { - const track = producer.subscribe({ delay: { max: Milli(1000) } }); + const track = producer.subscribe({ delay: { max: Duration.millis(1000) } }); producer.writeFrame({ payload: enc.encode("x"), timestamp: Timestamp.fromMillis(0) }); for (let sequence = 1; sequence <= RUN; sequence++) { const group = producer.appendGroup(); if (sequence % 2 === 0) group.finish(); } producer.writeFrame({ payload: enc.encode("x"), timestamp: Timestamp.fromMillis(10) }); - expect(drain(producer.subscribe({ delay: { max: Milli(1000) } }))).toHaveLength(RUN + 2); + expect(drain(producer.subscribe({ delay: { max: Duration.millis(1000) } }))).toHaveLength(RUN + 2); clock.set(11_000); expect(drain(track)).toEqual([BigInt(RUN + 1)]); - expect(drain(producer.subscribe({ delay: { max: Milli(1000) } }))).toEqual([BigInt(RUN + 1)]); + expect(drain(producer.subscribe({ delay: { max: Duration.millis(1000) } }))).toEqual([BigInt(RUN + 1)]); } finally { producer.finish(); producer.close(); @@ -1759,7 +1775,7 @@ test("a run of empty groups ages out by wall clock", () => { test("a live track retains its newest closed group through idle expiry", async () => { const clock = manualTime(10_000); - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(100) }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(100) }); try { // A late older group must not replace the protected newest snapshot. for (const sequence of [2n, 1n]) { @@ -1768,7 +1784,7 @@ test("a live track retains its newest closed group through idle expiry", async ( group.finish(); } await clock.advance(10_000 + CACHE_WINDOW_MS + 200); - const replay = producer.subscribe({ delay: { max: Milli(100) } }); + const replay = producer.subscribe({ delay: { max: Duration.millis(100) } }); expect(replay.tryRecvGroup()?.sequence).toBe(2n); expect(replay.tryRecvGroup()).toBeUndefined(); replay.close(); @@ -1786,8 +1802,8 @@ test("a live track retains its newest closed group through idle expiry", async ( test("retention eviction surfaces as a gap for a handed-out group", async () => { const clock = manualTime(10_000); try { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(100) }); - const track = producer.subscribe({ delay: { max: Milli(100) } }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(100) }); + const track = producer.subscribe({ delay: { max: Duration.millis(100) } }); const source = producer.appendGroup(); source.writeFrame(textFrame("first")); source.writeFrame(textFrame("tail")); @@ -1809,8 +1825,8 @@ test("retention eviction surfaces as a gap for a handed-out group", async () => test("idle expiry reclaims an ended track's held mirror", async () => { const clock = manualTime(10_000); try { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(100) }); - const track = producer.subscribe({ delay: { max: Milli(100) } }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(100) }); + const track = producer.subscribe({ delay: { max: Duration.millis(100) } }); const source = producer.appendGroup(); source.writeFrame(textFrame("first")); source.writeFrame(textFrame("tail")); @@ -1823,7 +1839,7 @@ test("idle expiry reclaims an ended track's held mirror", async () => { producer.finish(); producer.close(); clock.set(10_000 + CACHE_WINDOW_MS + 200); - producer.subscribe({ delay: { max: Milli(100) } }); + producer.subscribe({ delay: { max: Duration.millis(100) } }); await expect(group.readFrame()).rejects.toBeInstanceOf(TooFarBehind); } finally { @@ -1834,8 +1850,8 @@ test("idle expiry reclaims an ended track's held mirror", async () => { test("retention reclaims a group the publisher abandoned open", async () => { const clock = manualTime(10_000); try { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(100) }); - const track = producer.subscribe({ delay: { max: Milli(100) } }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(100) }); + const track = producer.subscribe({ delay: { max: Duration.millis(100) } }); const stalled = producer.appendGroup(); stalled.writeFrame(textFrame("first")); // A successor, so the stalled group is not the live edge the publisher is @@ -1847,7 +1863,7 @@ test("retention reclaims a group the publisher abandoned open", async () => { expect(await group.readString()).toBe("first"); clock.set(10_000 + CACHE_WINDOW_MS + 200); - producer.subscribe({ delay: { max: Milli(100) } }); + producer.subscribe({ delay: { max: Duration.millis(100) } }); // A gap, not a clean finish: the publisher never ended this group. await expect(group.readFrame()).rejects.toBeInstanceOf(TooFarBehind); @@ -1859,8 +1875,8 @@ test("retention reclaims a group the publisher abandoned open", async () => { test("an idle live edge ages out once a newer group arrives", async () => { const clock = manualTime(10_000); try { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(100) }); - const track = producer.subscribe({ delay: { max: Milli(100) } }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(100) }); + const track = producer.subscribe({ delay: { max: Duration.millis(100) } }); const edge = producer.appendGroup(); edge.writeFrame(textFrame("first")); @@ -1870,7 +1886,7 @@ test("an idle live edge ages out once a newer group arrives", async () => { // A prune while it is still the live edge keeps it, and finds nothing else to age out. clock.set(10_000 + CACHE_WINDOW_MS + 200); - producer.subscribe({ delay: { max: Milli(100) } }); + producer.subscribe({ delay: { max: Duration.millis(100) } }); // A successor ends the exemption, and the group is long past the window, so the // write evicts it rather than a later wakeup. @@ -1891,7 +1907,7 @@ test("an abandoned open group ages out with no further write", async () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: null }); try { // A budget past the cache window, so the eviction rather than the budget ends it. - const track = producer.subscribe({ delay: { max: Milli(2 * CACHE_WINDOW_MS) } }); + const track = producer.subscribe({ delay: { max: Duration.millis(2 * CACHE_WINDOW_MS) } }); const stalled = producer.appendGroup(); stalled.writeFrame(textFrame("first")); producer.appendGroup(); @@ -1910,7 +1926,7 @@ test("an abandoned open group ages out with no further write", async () => { }); test("publisher maxAge does not change the idle cache deadline", async () => { - for (const maxAge of [Milli(30), Milli(2 ** 31 + 10_000)]) { + for (const maxAge of [Duration.millis(30), Duration.millis(2 ** 31 + 10_000)]) { const clock = manualTime(10_000); const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge }); try { @@ -1934,8 +1950,8 @@ test("publisher maxAge does not change the idle cache deadline", async () => { test("retention pruning preserves clean EOF for a drained mirror", async () => { const clock = manualTime(10_000); try { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(100) }); - const track = producer.subscribe({ delay: { max: Milli(100) } }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(100) }); + const track = producer.subscribe({ delay: { max: Duration.millis(100) } }); const source = producer.appendGroup(); source.writeFrame(textFrame("only")); source.finish(); @@ -1948,7 +1964,7 @@ test("retention pruning preserves clean EOF for a drained mirror", async () => { producer.finish(); producer.close(); clock.set(10_000 + CACHE_WINDOW_MS + 200); - producer.subscribe({ delay: { max: Milli(100) } }); + producer.subscribe({ delay: { max: Duration.millis(100) } }); expect(await group.readFrame()).toBeUndefined(); expect(await group.closed).toBeNull(); @@ -1961,8 +1977,8 @@ test("system clock changes do not affect the latency budget", async () => { const clock = manualTime(10_000); clock.stepWall(10_000); try { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(100) }); - const track = producer.subscribe({ delay: { max: Milli(100) } }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(100) }); + const track = producer.subscribe({ delay: { max: Duration.millis(100) } }); producer.writeFrame(textFrame("old")); clock.stepWall(20_000); @@ -1976,8 +1992,8 @@ test("system clock changes do not affect the latency budget", async () => { }); test("frame readiness cancels the losing latency waiter", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(5000) }); - const track = producer.subscribe({ delay: { max: Milli(5000) } }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); + const track = producer.subscribe({ delay: { max: Duration.millis(5000) } }); const source = producer.appendGroup(); const group = await track.recvGroup(); if (!group) throw new Error("missing group"); @@ -1990,7 +2006,7 @@ test("frame readiness cancels the losing latency waiter", async () => { }); test("latency budget retains a consumed live-edge anchor", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(5000) }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); const track = producer.subscribe(); const edge = producer.createGroup(2n); @@ -2008,7 +2024,7 @@ test("latency budget retains a consumed live-edge anchor", async () => { }); test("an aborted live-edge anchor does not make older content stale", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(5000) }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); const track = producer.subscribe(); const edge = producer.createGroup(2n); @@ -2025,9 +2041,9 @@ test("an aborted live-edge anchor does not make older content stale", async () = test.each(["arrival", "ordered"] as const)("subscription bounds stay reader-local for %s reads", async (order) => { const producer = new TrackProducer("test"); - const everything = producer.subscribe({ delay: { max: Milli(5000) } }); + const everything = producer.subscribe({ delay: { max: Duration.millis(5000) } }); const subscriber = producer.subscribe({ - delay: { max: Milli(5000) }, + delay: { max: Duration.millis(5000) }, ranges: [{ start: { absolute: 1n }, end: { absolute: 3n } }], }); const ordered = order === "ordered" ? subscriber.ordered() : undefined; @@ -2041,18 +2057,18 @@ test.each(["arrival", "ordered"] as const)("subscription bounds stay reader-loca expect(await read()).toBeUndefined(); // Replacing the ranges reads on from the same reader. subscriber.update({ - delay: { max: Milli(5000) }, + delay: { max: Duration.millis(5000) }, ranges: [{ start: { absolute: 3n }, end: { absolute: 4n } }], }); expect((await read())?.sequence).toBe(3n); expect(await read()).toBeUndefined(); - subscriber.update({ delay: { max: Milli(5000) }, ranges: [{ end: { absolute: 5n } }] }); + subscriber.update({ delay: { max: Duration.millis(5000) }, ranges: [{ end: { absolute: 5n } }] }); // Arrival readers can now offer the unread group below the old floor; ordered ones cannot rewind. if (!ordered) expect((await read())?.sequence).toBe(0n); expect((await read())?.sequence).toBe(4n); expect(await read()).toBeUndefined(); // An open range parks at the live edge instead. - subscriber.update({ delay: { max: Milli(5000) }, ranges: [{ start: { absolute: 5n } }] }); + subscriber.update({ delay: { max: Duration.millis(5000) }, ranges: [{ start: { absolute: 5n } }] }); const pending = read(); expect(await Promise.race([pending, Promise.resolve("pending")])).toBe("pending"); producer.finish(); @@ -2068,11 +2084,14 @@ test.each(["arrival", "ordered"] as const)("subscription bounds stay reader-loca test("subscription updates narrow the cursor before its first read", async () => { const producer = new TrackProducer("test"); - const everything = producer.subscribe({ delay: { max: Milli(5000) } }); - const track = producer.subscribe({ delay: { max: Milli(5000) } }); + const everything = producer.subscribe({ delay: { max: Duration.millis(5000) } }); + const track = producer.subscribe({ delay: { max: Duration.millis(5000) } }); try { for (let sequence = 0n; sequence < 5n; sequence++) producer.createGroup(sequence); - track.update({ delay: { max: Milli(5000) }, ranges: [{ start: { absolute: 3n }, end: { absolute: 4n } }] }); + track.update({ + delay: { max: Duration.millis(5000) }, + ranges: [{ start: { absolute: 3n }, end: { absolute: 4n } }], + }); expect((await track.recvGroup())?.sequence).toBe(3n); // Its window read, the bounded read ends. expect(await track.recvGroup()).toBeUndefined(); @@ -2085,9 +2104,9 @@ test("subscription updates narrow the cursor before its first read", async () => }); test("a subscription cap chooses its own live edge", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(5000) }); - const everything = producer.subscribe({ delay: { max: Milli(5000) } }); - const track = producer.subscribe({ delay: { max: Milli.zero }, ranges: [{ end: { absolute: 2n } }] }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); + const everything = producer.subscribe({ delay: { max: Duration.millis(5000) } }); + const track = producer.subscribe({ delay: { max: Duration.ZERO }, ranges: [{ end: { absolute: 2n } }] }); try { for (let sequence = 0; sequence < 5; sequence++) { producer.writeFrame({ @@ -2096,7 +2115,7 @@ test("a subscription cap chooses its own live edge", async () => { }); } expect((await track.recvGroup())?.sequence).toBe(1n); - track.update({ delay: { max: Milli.zero }, ranges: [{ start: { absolute: 3n }, end: { absolute: 4n } }] }); + track.update({ delay: { max: Duration.ZERO }, ranges: [{ start: { absolute: 3n }, end: { absolute: 4n } }] }); expect((await track.recvGroup())?.sequence).toBe(3n); } finally { track.close(); @@ -2108,8 +2127,8 @@ test("a subscription cap chooses its own live edge", async () => { test("withRange with an excluded end of 0 is the empty range and does not ride another subscriber's demand", async () => { const producer = new TrackProducer("test"); - const everything = producer.subscribe({ delay: { max: Milli(5000) } }); - const empty = producer.subscribe({ delay: { max: Milli(5000) } }).withRange({ end: { excluded: 0n } }); + const everything = producer.subscribe({ delay: { max: Duration.millis(5000) } }); + const empty = producer.subscribe({ delay: { max: Duration.millis(5000) } }).withRange({ end: { excluded: 0n } }); for (let sequence = 0n; sequence < 3n; sequence++) producer.createGroup(sequence); @@ -2154,7 +2173,7 @@ for (const ordered of [false, true]) { } test("withRange caps the live edge used by the latency budget", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(5000) }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); const track = producer.subscribe(); track.withRange({ end: { excluded: 2n } }); @@ -2170,8 +2189,8 @@ test("withRange caps the live edge used by the latency budget", async () => { // The frame helpers ride the group cursor, so its bounds apply to them too: a group // above the cap stays cached across a clean close until the cap admits it. test("withRange caps frame-level reads like the group cursor", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(5000) }); - const track = producer.subscribe({ delay: { max: Milli(5000) } }).ordered(); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); + const track = producer.subscribe({ delay: { max: Duration.millis(5000) } }).ordered(); track.withRange({ end: { excluded: 1n } }); producer.writeFrame({ payload: enc.encode("zero"), timestamp: Timestamp.fromMillis(0) }); @@ -2190,7 +2209,7 @@ test("withRange caps frame-level reads like the group cursor", async () => { test("local cursor bounds can skip, pause, and release buffered groups", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ delay: { max: Milli(5000) } }).ordered(); + const track = producer.subscribe({ delay: { max: Duration.millis(5000) } }).ordered(); for (let sequence = 0n; sequence < 5n; sequence++) producer.createGroup(sequence); @@ -2210,7 +2229,7 @@ test("local cursor bounds can skip, pause, and release buffered groups", async ( // deliver it; a sequence cursor would skip it permanently. test("recvGroup serves a late arrival after a newer group", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ delay: { max: Milli(5000) } }); + const track = producer.subscribe({ delay: { max: Duration.millis(5000) } }); producer.createGroup(2n); expect((await track.recvGroup())?.sequence).toBe(2n); @@ -2229,7 +2248,7 @@ test("recvGroup serves a late arrival after a newer group", async () => { // Both cursors retain beyond-cap groups for widening, even after a clean close. test("withRange parks recvGroup beyond the cap and a raised cap re-offers", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ delay: { max: Milli(5000) } }); + const track = producer.subscribe({ delay: { max: Duration.millis(5000) } }); for (let sequence = 0n; sequence < 3n; sequence++) producer.createGroup(sequence).finish(); @@ -2254,7 +2273,7 @@ test("withRange parks recvGroup beyond the cap and a raised cap re-offers", asyn // a relay can ingest a burst micro-reordered (newest first). test("recvGroup serves in-range groups that arrive behind a capped one", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ delay: { max: Milli(5000) } }); + const track = producer.subscribe({ delay: { max: Duration.millis(5000) } }); track.withRange({ end: { excluded: 2n } }); @@ -2323,7 +2342,7 @@ test("createGroup rejects a duplicate live sequence", async () => { // leaving is what releases it: widening after close() finds nothing. test("closing the subscriber releases a group retained across a clean close", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ delay: { max: Milli(5000) } }); + const track = producer.subscribe({ delay: { max: Duration.millis(5000) } }); track.withRange({ end: { excluded: 1n } }); producer.createGroup(1n).finish(); @@ -2358,8 +2377,8 @@ test("closing the subscriber releases a recvGroup parked while the producer is l test("the ordered and arrival cursors are independent", async () => { const producer = new TrackProducer("test"); - const ordered = producer.subscribe({ delay: { max: Milli(5000) } }).ordered(); - const arrival = producer.subscribe({ delay: { max: Milli(5000) } }); + const ordered = producer.subscribe({ delay: { max: Duration.millis(5000) } }).ordered(); + const arrival = producer.subscribe({ delay: { max: Duration.millis(5000) } }); producer.createGroup(5n); expect((await ordered.nextGroup())?.sequence).toBe(5n); @@ -2377,7 +2396,7 @@ test("the first group read commits the cursor and refuses the other order", asyn const producer = new TrackProducer("test"); // An arrival read commits to arrival order; ordered() is refused afterwards. - const arrival = producer.subscribe({ delay: { max: Milli(5000) } }); + const arrival = producer.subscribe({ delay: { max: Duration.millis(5000) } }); producer.createGroup(5n); expect((await arrival.recvGroup())?.sequence).toBe(5n); expect(() => arrival.ordered()).toThrow("arrival order"); @@ -2388,7 +2407,7 @@ test("the first group read commits the cursor and refuses the other order", asyn expect((await arrival.recvGroup())?.sequence).toBe(3n); // The other direction: ordered() takes the subscription and arrival reads throw. - const inert = producer.subscribe({ delay: { max: Milli(5000) } }); + const inert = producer.subscribe({ delay: { max: Duration.millis(5000) } }); const ordered = inert.ordered(); expect(inert.recvGroup()).rejects.toThrow("sequence order"); expect(() => inert.ordered()).toThrow("sequence order"); @@ -2409,7 +2428,7 @@ test("nextGroup returns undefined when track closes", async () => { // A clean close ends a pending ordered read without erasing beyond-cap frames. test("a closed track still delivers a group parked above the cap once the cap is raised", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ delay: { max: Milli(5000) } }).ordered(); + const track = producer.subscribe({ delay: { max: Duration.millis(5000) } }).ordered(); for (let sequence = 0n; sequence < 3n; sequence++) { const group = producer.createGroup(sequence); @@ -2477,7 +2496,7 @@ test("readFrame does not livelock when a sole group finishes before the next arr // a group: a filter is applied down to the object. test("largest names the newest frame written", async () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI }); - const subscriber = producer.subscribe({ delay: { max: Milli(1_000) } }); + const subscriber = producer.subscribe({ delay: { max: Duration.millis(1_000) } }); // Nothing published yet, so the first read waits. expect(producer.largest()).toBeUndefined(); @@ -2691,7 +2710,7 @@ test("a live-edge reader starts on an empty largest group", async () => { first.finish(); const empty = producer.appendGroup(); - const reader = producer.subscribe({ delay: { max: Milli(30_000) } }); + const reader = producer.subscribe({ delay: { max: Duration.millis(30_000) } }); const edge = await reader.largest(); expect(edge).toEqual({ group: 1n, frame: 0 }); reader.withRange({ start: { included: edge?.group ?? 0n } }); @@ -2729,7 +2748,7 @@ test("largest survives a mirror replay of a group with a shed front", async () = test("group ranges preserve progress and spell out inclusion", async () => { const producer = new TrackProducer("test"); const track = producer - .subscribe({ delay: { max: Milli(5000) } }) + .subscribe({ delay: { max: Duration.millis(5000) } }) .withRange({ start: { included: 1n }, end: { included: 1n } }); for (let sequence = 0n; sequence < 4n; sequence++) producer.createGroup(sequence); expect(track.tryRecvGroup()?.sequence).toBe(1n); @@ -2745,7 +2764,7 @@ test("group ranges preserve progress and spell out inclusion", async () => { // Mirrors the Rust `a_lowered_range_reoffers_the_unread_cached_groups`. test("a lowered range re-offers the unread cached groups", () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ delay: { max: Milli(5000) } }).withRange({ start: { included: 10n } }); + const track = producer.subscribe({ delay: { max: Duration.millis(5000) } }).withRange({ start: { included: 10n } }); for (const sequence of [5n, 6n, 10n]) producer.createGroup(sequence); expect(track.tryRecvGroup()?.sequence).toBe(10n); expect(track.tryRecvGroup()).toBeUndefined(); @@ -2763,7 +2782,7 @@ test("a lowered range re-offers the unread cached groups", () => { test("a lowered range re-offers a cached cut with its error", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ delay: { max: Milli(5000) } }).withRange({ start: { included: 1n } }); + const track = producer.subscribe({ delay: { max: Duration.millis(5000) } }).withRange({ start: { included: 1n } }); const cut = producer.createGroup(0n); const error = new StreamError(StreamCode(70), { message: "cut" }); cut.abort(error); @@ -2781,7 +2800,7 @@ test("a lowered range re-offers a cached cut with its error", async () => { test("a lowered range still re-offers after the producer closes", () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ delay: { max: Milli(5000) } }).withRange({ start: { included: 1n } }); + const track = producer.subscribe({ delay: { max: Duration.millis(5000) } }).withRange({ start: { included: 1n } }); for (const sequence of [0n, 1n]) producer.createGroup(sequence).finish(); expect(track.tryRecvGroup()?.sequence).toBe(1n); producer.finish(); @@ -2796,7 +2815,9 @@ test("a lowered range still re-offers after the producer closes", () => { for (const abort of [undefined, new Error("gone")]) { test(`a lowered range offers nothing to a reader that ${abort ? "aborted" : "closed"}`, () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ delay: { max: Milli(5000) } }).withRange({ start: { included: 1n } }); + const track = producer + .subscribe({ delay: { max: Duration.millis(5000) } }) + .withRange({ start: { included: 1n } }); for (const sequence of [0n, 1n]) producer.createGroup(sequence); expect(track.tryRecvGroup()?.sequence).toBe(1n); track.close(abort); @@ -2810,7 +2831,7 @@ for (const abort of [undefined, new Error("gone")]) { test("malformed group bounds do not partially advance the cursor", () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ delay: { max: Milli(5000) } }); + const track = producer.subscribe({ delay: { max: Duration.millis(5000) } }); producer.createGroup(0n); expect(() => track.withRange({ start: { included: 3n }, end: { excluded: -1n } })).toThrow(); expect(track.tryRecvGroup()?.sequence).toBe(0n); @@ -2819,7 +2840,7 @@ test("malformed group bounds do not partially advance the cursor", () => { test("finishAt declares an end ahead of the live edge without ending the track", async () => { const producer = new TrackProducer("test"); - const track = producer.subscribe({ delay: { max: Milli(60_000) } }); + const track = producer.subscribe({ delay: { max: Duration.millis(60_000) } }); producer.createGroup(5n); const first = await track.recvGroup(); expect(first?.sequence).toBe(5n); @@ -2849,7 +2870,7 @@ test("finishAt declares an end ahead of the live edge without ending the track", for (const ordered of [false, true]) { test(`a ${ordered ? "sequence" : "arrival"} reader ends at the declared boundary before closure`, async () => { const producer = new TrackProducer("test"); - const subscriber = producer.subscribe({ delay: { max: Milli(60_000) } }); + const subscriber = producer.subscribe({ delay: { max: Duration.millis(60_000) } }); const track = ordered ? subscriber.ordered() : subscriber; const receive = () => ("nextGroup" in track ? track.nextGroup() : track.recvGroup()); try { @@ -2917,20 +2938,20 @@ test("no publisher limit still ages idle groups out", async () => { source.finish(); clock.set(10_000 + CACHE_WINDOW_MS - 1_000); producer.appendGroup(); - const within = producer.subscribe({ delay: { max: Milli(100_000) } }); + const within = producer.subscribe({ delay: { max: Duration.millis(100_000) } }); expect(await (await within.recvGroup())?.readString()).toBe("old"); within.close(); // The read was an access, as in Rust: past the write's window, the group stays. Taking it // again is another access. clock.set(10_000 + CACHE_WINDOW_MS + 1_000); - const read = producer.subscribe({ delay: { max: Milli(100_000) } }); + const read = producer.subscribe({ delay: { max: Duration.millis(100_000) } }); expect(read.tryRecvGroup()?.sequence).toBe(0n); read.close(); // Past that delivery's window, a subscribe's own scan reclaims it. clock.set(10_000 + 2 * CACHE_WINDOW_MS + 2_000); - const after = producer.subscribe({ delay: { max: Milli(100_000) } }); + const after = producer.subscribe({ delay: { max: Duration.millis(100_000) } }); expect(after.tryRecvGroup()?.sequence).toBe(1n); expect(after.tryRecvGroup()).toBeUndefined(); after.close(); @@ -2953,7 +2974,7 @@ test("a live track does not pin an aborted newest group", () => { reset.abort(new Error("reset")); clock.set(10_000 + CACHE_WINDOW_MS + CACHE_WINDOW_MS / 8); - const late = producer.subscribe({ delay: { max: Milli(100_000) } }); + const late = producer.subscribe({ delay: { max: Duration.millis(100_000) } }); expect(late.tryRecvGroup()).toBeUndefined(); late.close(); } finally { @@ -2967,7 +2988,7 @@ test("closing a track keeps an idle newest group for subscribers to drain", asyn const clock = manualTime(10_000); try { const producer = new TrackProducer("catalog").accept({ timescale: Timescale.MILLI }); - const subscriber = producer.subscribe({ delay: { max: Milli(100_000) } }); + const subscriber = producer.subscribe({ delay: { max: Duration.millis(100_000) } }); const snapshot = producer.appendGroup(); snapshot.writeFrame(textFrame("snapshot")); snapshot.finish(); @@ -2981,7 +3002,7 @@ test("closing a track keeps an idle newest group for subscribers to drain", asyn // The close restarted its window, which now runs out like any other. clock.set(10_000 + 2 * (CACHE_WINDOW_MS + CACHE_WINDOW_MS / 8)); - const late = producer.subscribe({ delay: { max: Milli(100_000) } }); + const late = producer.subscribe({ delay: { max: Duration.millis(100_000) } }); expect(late.tryRecvGroup()).toBeUndefined(); late.close(); } finally { @@ -3029,9 +3050,9 @@ test("a late subscriber to a closed unlimited track is released once the cache a }); test("an abort keeps finished groups for a slow reader, then reports it", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(10_000) }); - const arrival = producer.subscribe({ delay: { max: Milli(10_000) } }); - const ordered = producer.subscribe({ delay: { max: Milli(10_000) } }).ordered(); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(10_000) }); + const arrival = producer.subscribe({ delay: { max: Duration.millis(10_000) } }); + const ordered = producer.subscribe({ delay: { max: Duration.millis(10_000) } }).ordered(); for (let i = 0; i < 2; i++) { const group = producer.appendGroup(); group.writeFrame(textFrame(`g${i}`)); @@ -3053,9 +3074,9 @@ test("an abort keeps finished groups for a slow reader, then reports it", async }); test("an abort after the declared end settles ends clean", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(10_000) }); - const arrival = producer.subscribe({ delay: { max: Milli(10_000) } }); - const ordered = producer.subscribe({ delay: { max: Milli(10_000) } }).ordered(); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(10_000) }); + const arrival = producer.subscribe({ delay: { max: Duration.millis(10_000) } }); + const ordered = producer.subscribe({ delay: { max: Duration.millis(10_000) } }).ordered(); for (let i = 0; i < 2; i++) { const group = producer.appendGroup(); group.writeFrame(textFrame(`g${i}`)); @@ -3155,9 +3176,9 @@ test("close without finish aborts with a cancel", () => { test("an ended track's buffered groups age out for a stale subscriber", async () => { for (const abort of [undefined, new Error("boom")]) { const clock = manualTime(10_000); - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(30) }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(30) }); try { - const stale = producer.subscribe({ delay: { max: Milli(30) } }); + const stale = producer.subscribe({ delay: { max: Duration.millis(30) } }); const group = producer.appendGroup(); group.writeFrame(textFrame("x")); group.finish(); @@ -3180,9 +3201,9 @@ test("an ended track's buffered groups age out for a stale subscriber", async () }); test("an abort leaves a group already taken readable, then reports the abort", async () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(10_000) }); - const arrival = producer.subscribe({ delay: { max: Milli(10_000) } }); - const ordered = producer.subscribe({ delay: { max: Milli(10_000) } }).ordered(); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(10_000) }); + const arrival = producer.subscribe({ delay: { max: Duration.millis(10_000) } }); + const ordered = producer.subscribe({ delay: { max: Duration.millis(10_000) } }).ordered(); producer.appendGroup().writeFrame(textFrame("held")); const held = [await arrival.recvGroup(), await ordered.nextGroup()]; const boom = new Error("boom"); @@ -3239,9 +3260,9 @@ test("unknown track metadata keeps presentation-time expiry until accepted", () } // No wall time passes. Until metadata is accepted, buffered timestamps still // prove that the two oldest groups are outside this reader's media budget. - expect(drain(producer.subscribe({ delay: { max: Milli(500) } }))).toEqual([2n, 3n]); + expect(drain(producer.subscribe({ delay: { max: Duration.millis(500) } }))).toEqual([2n, 3n]); producer.accept({ timescale: Timescale.MILLI, maxAge: null }); - expect(drain(producer.subscribe({ delay: { max: Milli(500) } }))).toEqual([2n, 3n]); + expect(drain(producer.subscribe({ delay: { max: Duration.millis(500) } }))).toEqual([2n, 3n]); } finally { producer.finish(); producer.close(); @@ -3264,11 +3285,11 @@ test("an untimed subscriber starts at the oldest fresh group", () => { // Four seconds after group 4 arrived, groups 0 to 2 were superseded 4, 3, and 2 // seconds ago: past a 1.5s budget. Group 3 was superseded 1s ago. - expect(drain(producer.subscribe({ delay: { max: Milli(1500) } }))).toEqual([3n, 4n]); + expect(drain(producer.subscribe({ delay: { max: Duration.millis(1500) } }))).toEqual([3n, 4n]); // No budget takes the newest group alone, which is never stale. const live = producer.subscribe(); expect(drain(live)).toEqual([4n]); - expect(drain(producer.subscribe({ delay: { max: Milli(60_000) } }))).toEqual([0n, 1n, 2n, 3n, 4n]); + expect(drain(producer.subscribe({ delay: { max: Duration.millis(60_000) } }))).toEqual([0n, 1n, 2n, 3n, 4n]); producer.writeFrame({ payload: enc.encode("5") }); expect(drain(live)).toEqual([5n]); @@ -3282,14 +3303,14 @@ test("an untimed subscriber starts at the oldest fresh group", () => { test("an untimed subscriber without a start begins at the latest group under its end", () => { const producer = untimedTrack(5); // As the lite publisher serves a SUBSCRIBE with an end and no start. - const subscriber = producer.subscribe({ delay: { max: Milli.zero }, ranges: [{ end: { absolute: 3n } }] }); + const subscriber = producer.subscribe({ delay: { max: Duration.ZERO }, ranges: [{ end: { absolute: 3n } }] }); subscriber.withRange({ end: { excluded: 3n } }); expect(drain(subscriber)).toEqual([2n]); }); test("a single-frame write that throws aborts its group", () => { const producer = new TrackProducer("test").accept({ maxAge: null }); - const subscriber = producer.subscribe({ delay: { max: Milli(60_000) } }); + const subscriber = producer.subscribe({ delay: { max: Duration.millis(60_000) } }); // A timestamped frame is refused by an untimed track. expect(() => producer.writeFrame({ payload: enc.encode("x"), timestamp: Timestamp.fromMillis(1) })).toThrow( TimestampMismatch, @@ -3308,9 +3329,12 @@ test("a single-frame write that throws aborts its group", () => { test("an explicit start floors an untimed track", () => { const producer = untimedTrack(5); - const resumed = producer.subscribe({ delay: { max: Milli(60_000) }, ranges: [{ start: { absolute: 2n } }] }); + const resumed = producer.subscribe({ + delay: { max: Duration.millis(60_000) }, + ranges: [{ start: { absolute: 2n } }], + }); expect(drain(resumed)).toEqual([2n, 3n, 4n]); - const live = producer.subscribe({ delay: { max: Milli.zero }, ranges: [{ start: { absolute: 2n } }] }); + const live = producer.subscribe({ delay: { max: Duration.ZERO }, ranges: [{ start: { absolute: 2n } }] }); expect(drain(live)).toEqual([4n]); }); @@ -3319,7 +3343,7 @@ const DROPPED = new StreamError(StreamCode.NotFound, { message: "dropped" }); test("explicit and producer-cut drops survive outside the group cache", async () => { const producer = new TrackProducer("video").accept({}); - const reader = producer.subscribe({ delay: { max: Milli(60_000) } }); + const reader = producer.subscribe({ delay: { max: Duration.millis(60_000) } }); hooks.dropTrackGroups(producer, 3n, 4n, { error: DROPPED }); expect(hooks.tryRecvGroup(reader, true)).toEqual({ kind: "drop", start: 3n, end: 4n, error: DROPPED }); @@ -3336,7 +3360,7 @@ test("explicit and producer-cut drops survive outside the group cache", async () test("a group ended by a cancel or cache policy is a hole, not a drop", async () => { const producer = new TrackProducer("video").accept({}); - const reader = producer.subscribe({ delay: { max: Milli(60_000) } }); + const reader = producer.subscribe({ delay: { max: Duration.millis(60_000) } }); const holes = [ new StreamError(StreamCode.Cancel, { message: "cancel" }), new StreamError(StreamCode.Old, { message: "old" }), @@ -3358,7 +3382,7 @@ test("a group ended by a cancel or cache policy is a hole, not a drop", async () test("an upstream drop ends a group still arriving with its error", async () => { const producer = new TrackProducer("video").accept({ maxAge: null }); - const reader = producer.subscribe({ delay: { max: Milli(60_000) } }); + const reader = producer.subscribe({ delay: { max: Duration.millis(60_000) } }); const arriving = producer.createGroup(3n); arriving.writeFrame({ payload: enc.encode("3") }); const finished = producer.createGroup(4n); @@ -3383,7 +3407,9 @@ test("an upstream drop ends a group still arriving with its error", async () => test("a drop below the window is reported once the window lowers to it", () => { const producer = new TrackProducer("video").accept({}); - const reader = producer.subscribe({ delay: { max: Milli(60_000) } }).withRange({ start: { included: 5n } }); + const reader = producer + .subscribe({ delay: { max: Duration.millis(60_000) } }) + .withRange({ start: { included: 5n } }); hooks.dropTrackGroups(producer, 2n, 3n, { error: DROPPED }); expect(hooks.tryRecvGroup(reader, true)).toEqual({ kind: "idle" }); @@ -3397,7 +3423,7 @@ test("a drop below the window is reported once the window lowers to it", () => { test("a re-created cut group is served, not dropped", async () => { const producer = new TrackProducer("video").accept({}); - const reader = producer.subscribe({ delay: { max: Milli(60_000) } }); + const reader = producer.subscribe({ delay: { max: Duration.millis(60_000) } }); const cut = producer.createGroup(4n); cut.abort(new Error("cut")); await settle(); @@ -3414,7 +3440,7 @@ test("a re-created cut group is served, not dropped", async () => { test("a reported drop still allows a late group, handed out once", () => { const producer = new TrackProducer("video").accept({}); - const reader = producer.subscribe({ delay: { max: Milli(60_000) } }); + const reader = producer.subscribe({ delay: { max: Duration.millis(60_000) } }); hooks.dropTrackGroups(producer, 2n, 4n, { error: DROPPED }); expect(hooks.tryRecvGroup(reader, true)).toEqual({ kind: "drop", start: 2n, end: 4n, error: DROPPED }); expect(hooks.tryRecvGroup(reader, true)).toEqual({ kind: "idle" }); @@ -3432,7 +3458,7 @@ test("a received stale drop settles only the readers it covers", () => { const producer = new TrackProducer("video").accept({ maxAge: null }); const reader = (max: number, start: bigint, end?: bigint) => producer.subscribe({ - delay: { max: Milli(max) }, + delay: { max: Duration.millis(max) }, ranges: [{ start: { absolute: start }, end: end === undefined ? undefined : { absolute: end } }], }); const covering = reader(500, 0n); @@ -3466,7 +3492,7 @@ test("a received stale drop settles only the readers it covers", () => { test("a superseded stale run is unknown again, and its group is handed out", () => { const producer = new TrackProducer("video").accept({}); - const reader = producer.subscribe({ delay: { max: Milli(500) }, ranges: [{ start: { absolute: 0n } }] }); + const reader = producer.subscribe({ delay: { max: Duration.millis(500) }, ranges: [{ start: { absolute: 0n } }] }); hooks.dropTrackGroups(producer, 1n, 2n, staleHole(500)); hooks.supersedeStale(producer, undefined); expect(hooks.tryDrop(reader)).toBeUndefined(); @@ -3481,7 +3507,7 @@ test("a superseded stale run is unknown again, and its group is handed out", () test("superseding withdraws a partly reported stale run", () => { const producer = new TrackProducer("video").accept({}); - const reader = producer.subscribe({ delay: { max: Milli(500) }, ranges: [{ start: { absolute: 0n } }] }); + const reader = producer.subscribe({ delay: { max: Duration.millis(500) }, ranges: [{ start: { absolute: 0n } }] }); hooks.dropTrackGroups(producer, 4n, 5n, { error: DROPPED }); expect(hooks.tryDrop(reader)).toMatchObject({ start: 4n, end: 5n }); hooks.dropTrackGroups(producer, 3n, 7n, staleHole(500)); @@ -3499,7 +3525,7 @@ test("superseding withdraws a partly reported stale run", () => { // dropping it again as if the reader had judged it stale itself. Mirrors Rust. test("a superseded received stale report stays owed after an update", () => { const producer = new TrackProducer("video").accept({}); - const reader = producer.subscribe({ delay: { max: Milli(500) }, ranges: [{ start: { absolute: 0n } }] }); + const reader = producer.subscribe({ delay: { max: Duration.millis(500) }, ranges: [{ start: { absolute: 0n } }] }); hooks.dropTrackGroups(producer, 1n, 3n, staleHole(500)); expect(hooks.tryDrop(reader)).toMatchObject({ start: 1n, end: 3n, stale: 500 }); hooks.supersedeStale(producer, undefined); @@ -3518,7 +3544,7 @@ test("a received stale run settles a bounded reader only through the judged rang hooks.receiveTrack(producer); const bounded = (max: number) => producer.subscribe({ - delay: { max: Milli(max) }, + delay: { max: Duration.millis(max) }, ranges: [{ start: { absolute: 0n }, end: { absolute: 2n } }], }); const wider = bounded(5000); @@ -3549,7 +3575,7 @@ test("a superseded stale run leaves a bounded reader waiting, and a later reader hooks.receiveTrack(producer); const bounded = (max: number) => producer.subscribe({ - delay: { max: Milli(max) }, + delay: { max: Duration.millis(max) }, ranges: [{ start: { absolute: 0n }, end: { absolute: 2n } }], }); const wider = bounded(5000); @@ -3570,7 +3596,7 @@ test("a superseded stale run leaves a bounded reader waiting, and a later reader test("a wide drop is held and reported as one run", () => { const producer = new TrackProducer("video").accept({}); - const reader = producer.subscribe({ delay: { max: Milli(60_000) } }); + const reader = producer.subscribe({ delay: { max: Duration.millis(60_000) } }); hooks.dropTrackGroups(producer, 2n, 2n ** 40n, { error: DROPPED }); expect(hooks.tryRecvGroup(reader, true)).toEqual({ kind: "drop", start: 2n, end: 2n ** 40n, error: DROPPED }); @@ -3593,7 +3619,7 @@ test("a wide drop is held and reported as one run", () => { test("adjacent drops with the same code merge into one run", () => { const producer = new TrackProducer("video").accept({}); - const reader = producer.subscribe({ delay: { max: Milli(60_000) } }); + const reader = producer.subscribe({ delay: { max: Duration.millis(60_000) } }); // Each DROP decodes to its own error, so runs must merge by code, not identity. for (let sequence = 2n; sequence < 5n; sequence++) { hooks.dropTrackGroups(producer, sequence, sequence + 1n, { @@ -3703,8 +3729,8 @@ function drainGroups(subscriber: ReturnType): bigint } test("a re-created group is handed out once", () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(30_000) }); - const subscriber = producer.subscribe({ delay: { max: Milli(30_000) } }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(30_000) }); + const subscriber = producer.subscribe({ delay: { max: Duration.millis(30_000) } }); stampGroup(producer, 0n, 0); const aborted = producer.createGroup(1n); expect(drainGroups(subscriber)).toEqual([0n, 1n]); @@ -3721,8 +3747,8 @@ test("a gap is forgotten once a group above it is past the budget", () => { const time = manualTime(1_000); try { const readers = [ - { info: { timescale: Timescale.MILLI, maxAge: Milli(30_000) }, maxDelay: Milli(10) }, - { info: { timescale: Timescale.MILLI, maxAge: Milli(10) }, maxDelay: Milli(3_600_000) }, + { info: { timescale: Timescale.MILLI, maxAge: Duration.millis(30_000) }, maxDelay: Duration.millis(10) }, + { info: { timescale: Timescale.MILLI, maxAge: Duration.millis(10) }, maxDelay: Duration.millis(3_600_000) }, ]; for (const { info, maxDelay } of readers) { const producer = new TrackProducer("test").accept(info); @@ -3749,9 +3775,12 @@ test("a gap is forgotten once a group above it is past the budget", () => { test("an endless track with gaps remembers only those within the budget", () => { const time = manualTime(1_000); try { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(30_000) }); + const producer = new TrackProducer("test").accept({ + timescale: Timescale.MILLI, + maxAge: Duration.millis(30_000), + }); // Groups present 1ms apart, so the budget spans ten of them. - const subscriber = producer.subscribe({ delay: { max: Milli(10) } }); + const subscriber = producer.subscribe({ delay: { max: Duration.millis(10) } }); let most = 0; for (let sequence = 0n; sequence < 3000n; sequence++) { // Every third group never arrives. @@ -3856,7 +3885,10 @@ test("a group's first frame is checked against the group below it", () => { test("an evicted group still bounds, and a late group below it is unverified", async () => { const clock = manualTime(10_000); try { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(60_000) }); + const producer = new TrackProducer("test").accept({ + timescale: Timescale.MILLI, + maxAge: Duration.millis(60_000), + }); for (const [sequence, ms] of [ [0n, 1000], [1n, 2000], @@ -3875,7 +3907,7 @@ test("an evicted group still bounds, and a late group below it is unverified", a // At or below the watermark the lower neighbor may be gone, so the watermark only caps // the group and it is accepted without being trusted to time anything. - const track = producer.subscribe({ delay: { max: Milli(60_000) } }); + const track = producer.subscribe({ delay: { max: Duration.millis(60_000) } }); expect(() => stampGroup(producer, 1n, 4000)).toThrow(TimestampMismatch); stampGroup(producer, 1n, 500).finish(); edge.finish(); @@ -3942,7 +3974,7 @@ test("replay and backlogs deliver sparse out-of-order arrivals ascending without // A received track as a wire subscription leaves it: the feed starts at group 0 and its end is // pending, so lower groups may still arrive behind a higher one. -function pendingTail(end: bigint, maxDelay = Milli(60_000)) { +function pendingTail(end: bigint, maxDelay = Duration.millis(60_000)) { const producer = new TrackProducer("test"); // A received copy, whose groups arrive in any order. hooks.receiveTrack(producer); @@ -3970,7 +4002,7 @@ async function settled(read: Promise): Promise { // The end arrives after a higher group did, with lower ones still owed: it must not settle. test("a received end behind a hole settles only once the hole fills", async () => { const producer = new TrackProducer("test"); - const reader = producer.subscribe({ delay: { max: Milli(60_000) } }); + const reader = producer.subscribe({ delay: { max: Duration.millis(60_000) } }); hooks.receiveTrack(producer); hooks.startTrack(producer, { start: 0n }); const late = producer.createGroup(2n); @@ -4025,11 +4057,14 @@ test("a pending tail ends readers at the boundary once the track closes", async // reader above the groups another reader's floor still lacks ends at the boundary. test("an end no subscription feeds owes no tail", async () => { const producer = new TrackProducer("test"); - const history = producer.subscribe({ ranges: [{ start: { absolute: 0n } }], delay: { max: Milli(60_000) } }); + const history = producer.subscribe({ + ranges: [{ start: { absolute: 0n } }], + delay: { max: Duration.millis(60_000) }, + }); const group = producer.createGroup(2n); group.finish(); hooks.endTrack(producer, { group: 3n, frame: 0 }); - const live = producer.subscribe({ ranges: [{ start: { absolute: 2n } }], delay: { max: Milli(60_000) } }); + const live = producer.subscribe({ ranges: [{ start: { absolute: 2n } }], delay: { max: Duration.millis(60_000) } }); expect((await live.recvGroup())?.sequence).toBe(2n); const next = live.recvGroup(); expect(await settled(next)).toBe(true); @@ -4044,14 +4079,17 @@ test("an end no subscription feeds owes no tail", async () => { test("an end refined after the subscription ended owes no tail", async () => { const producer = new TrackProducer("test"); hooks.receiveTrack(producer); - const history = producer.subscribe({ ranges: [{ start: { absolute: 0n } }], delay: { max: Milli(60_000) } }); + const history = producer.subscribe({ + ranges: [{ start: { absolute: 0n } }], + delay: { max: Duration.millis(60_000) }, + }); const group = producer.createGroup(2n); group.writeFrame({ payload: new Uint8Array([1]) }); group.finish(); hooks.endTrack(producer, { group: 3n, frame: 0 }); hooks.cacheTrack(producer); hooks.endTrack(producer, { group: 2n, frame: 1 }); - const live = producer.subscribe({ ranges: [{ start: { absolute: 2n } }], delay: { max: Milli(60_000) } }); + const live = producer.subscribe({ ranges: [{ start: { absolute: 2n } }], delay: { max: Duration.millis(60_000) } }); expect((await live.recvGroup())?.sequence).toBe(2n); const next = live.recvGroup(); expect(await settled(next)).toBe(true); @@ -4063,7 +4101,7 @@ test("an end refined after the subscription ended owes no tail", async () => { test("without a declared start, the first arrival stands in for it", async () => { const producer = new TrackProducer("test"); - const reader = producer.subscribe({ delay: { max: Milli(60_000) } }); + const reader = producer.subscribe({ delay: { max: Duration.millis(60_000) } }); hooks.endTrack(producer, { group: 3n, frame: 0 }); const group = producer.createGroup(2n); group.finish(); @@ -4105,7 +4143,10 @@ test("a source start follows the current requested floor after an update", async // keeps that floor: a lowered floor owes the groups it newly asks for. test("a pending tail owes from SUBSCRIBE_START while the demand keeps its floor", async () => { const producer = new TrackProducer("test"); - const reader = producer.subscribe({ delay: { max: Milli(60_000) }, ranges: [{ start: { absolute: 1n } }] }); + const reader = producer.subscribe({ + delay: { max: Duration.millis(60_000) }, + ranges: [{ start: { absolute: 1n } }], + }); hooks.receiveTrack(producer); hooks.startTrack(producer, { start: 3n, requested: 1n }); hooks.endTrack(producer, { group: 4n, frame: 0 }); @@ -4114,7 +4155,10 @@ test("a pending tail owes from SUBSCRIBE_START while the demand keeps its floor" expect((await reader.recvGroup())?.sequence).toBe(3n); expect(await reader.recvGroup()).toBeUndefined(); - const lower = producer.subscribe({ delay: { max: Milli(60_000) }, ranges: [{ start: { absolute: 0n } }] }); + const lower = producer.subscribe({ + delay: { max: Duration.millis(60_000) }, + ranges: [{ start: { absolute: 0n } }], + }); expect((await lower.recvGroup())?.sequence).toBe(3n); const next = lower.recvGroup(); expect(await settled(next)).toBe(false); @@ -4126,7 +4170,7 @@ test("a pending tail owes from SUBSCRIBE_START while the demand keeps its floor" // The wire's end can land after the highest group, with lower groups still owed. test("an end after the highest group holds the reader at the hole", async () => { const producer = new TrackProducer("test"); - const reader = producer.subscribe({ delay: { max: Milli(60_000) } }); + const reader = producer.subscribe({ delay: { max: Duration.millis(60_000) } }); hooks.receiveTrack(producer); hooks.startTrack(producer, { start: 0n }); const high = producer.createGroup(2n); @@ -4181,7 +4225,7 @@ for (const [waited, clean] of [ const clock = manualTime(0); try { // The subscription's max delay is the grace the hole is waited for. - const { producer, reader, write } = pendingTail(3n, Milli(1000)); + const { producer, reader, write } = pendingTail(3n, Duration.millis(1000)); write(0n); write(2n); expect((await reader.recvGroup())?.sequence).toBe(0n); @@ -4211,7 +4255,7 @@ test("an evicted group still fills a pending tail", async () => { clock.set(CACHE_WINDOW_MS + 1000); write(2n); // A late subscriber replays only what the cache still holds. - expect(producer.subscribe({ delay: { max: Milli(60_000) } }).tryRecvGroup()?.sequence).toBe(2n); + expect(producer.subscribe({ delay: { max: Duration.millis(60_000) } }).tryRecvGroup()?.sequence).toBe(2n); expect((await reader.recvGroup())?.sequence).toBe(2n); expect(await reader.recvGroup()).toBeUndefined(); producer.finish(); @@ -4245,7 +4289,7 @@ for (const abort of [false, true]) { // already handed out. test("a widened maxDelay re-offers what it skipped as stale", () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: null }); - const subscriber = producer.subscribe({ delay: { max: Milli(1500) } }); + const subscriber = producer.subscribe({ delay: { max: Duration.millis(1500) } }); stampGroup(producer, 0n, 0); expect(drainGroups(subscriber)).toEqual([0n]); for (const [sequence, ms] of [ @@ -4259,7 +4303,7 @@ test("a widened maxDelay re-offers what it skipped as stale", () => { // Groups 1 and 2 reach 2s and 3s, at least 1.5s behind the 6s edge. expect(drainGroups(subscriber)).toEqual([3n, 4n]); - subscriber.update({ delay: { max: Milli(10_000) } }); + subscriber.update({ delay: { max: Duration.millis(10_000) } }); expect(drainGroups(subscriber)).toEqual([1n, 2n]); expect(drainGroups(subscriber)).toEqual([]); producer.close(); @@ -4268,7 +4312,7 @@ test("a widened maxDelay re-offers what it skipped as stale", () => { // A read already parked when the budget widens wakes for the re-offer. test("a widened maxDelay wakes a parked read", async () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: null }); - const subscriber = producer.subscribe({ delay: { max: Milli(1500) } }); + const subscriber = producer.subscribe({ delay: { max: Duration.millis(1500) } }); stampGroup(producer, 0n, 0); expect(drainGroups(subscriber)).toEqual([0n]); for (const [sequence, ms] of [ @@ -4282,7 +4326,7 @@ test("a widened maxDelay wakes a parked read", async () => { expect(drainGroups(subscriber)).toEqual([2n, 3n]); const parked = subscriber.recvGroup(); - subscriber.update({ delay: { max: Milli(10_000) } }); + subscriber.update({ delay: { max: Duration.millis(10_000) } }); expect((await parked)?.sequence).toBe(1n); producer.close(); }); @@ -4292,8 +4336,11 @@ test("a widened maxDelay wakes a parked read", async () => { test("an evicted stale skip lets the delivered gaps fold", () => { const time = manualTime(1_000); try { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(30_000) }); - const subscriber = producer.subscribe({ delay: { max: Milli(10) } }); + const producer = new TrackProducer("test").accept({ + timescale: Timescale.MILLI, + maxAge: Duration.millis(30_000), + }); + const subscriber = producer.subscribe({ delay: { max: Duration.millis(10) } }); stampGroup(producer, 0n, 0); expect(drainGroups(subscriber)).toEqual([0n]); // Group 1 reaches 5ms, past the 10ms budget behind the 30ms edge. @@ -4321,7 +4368,7 @@ test("an evicted stale skip lets the delivered gaps fold", () => { // A re-offer never hands out a group below a floor raised in the same update. test("a widened maxDelay re-offers nothing below a raised floor", () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: null }); - const subscriber = producer.subscribe({ delay: { max: Milli(1500) } }); + const subscriber = producer.subscribe({ delay: { max: Duration.millis(1500) } }); stampGroup(producer, 0n, 0); expect(drainGroups(subscriber)).toEqual([0n]); for (const [sequence, ms] of [ @@ -4334,7 +4381,7 @@ test("a widened maxDelay re-offers nothing below a raised floor", () => { } expect(drainGroups(subscriber)).toEqual([3n, 4n]); - subscriber.update({ delay: { max: Milli(10_000) }, ranges: [{ start: { absolute: 2n } }] }); + subscriber.update({ delay: { max: Duration.millis(10_000) }, ranges: [{ start: { absolute: 2n } }] }); expect(drainGroups(subscriber)).toEqual([2n]); producer.close(); }); @@ -4344,7 +4391,7 @@ test("a widened maxDelay re-offers nothing below a raised floor", () => { for (const reported of [false, true]) { test(`a widened maxDelay re-offers a stale group after its drop was ${reported ? "reported" : "pending"}`, () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: null }); - const subscriber = producer.subscribe({ delay: { max: Milli(1500) } }); + const subscriber = producer.subscribe({ delay: { max: Duration.millis(1500) } }); expect(hooks.tryDrop(subscriber)).toBeUndefined(); stampGroup(producer, 0n, 0); expect(drainGroups(subscriber)).toEqual([0n]); @@ -4363,7 +4410,7 @@ for (const reported of [false, true]) { expect(hooks.tryDrop(subscriber)).toBeUndefined(); } - subscriber.update({ delay: { max: Milli(10_000) } }); + subscriber.update({ delay: { max: Duration.millis(10_000) } }); expect(drainGroups(subscriber)).toEqual([1n]); expect(hooks.tryDrop(subscriber)).toBeUndefined(); producer.close(); @@ -4374,7 +4421,7 @@ for (const reported of [false, true]) { // older one into the delivered floor: a further widening still re-offers it. test("a partial maxDelay widening keeps the older skip owed", () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: null }); - const subscriber = producer.subscribe({ delay: { max: Milli(1500) } }); + const subscriber = producer.subscribe({ delay: { max: Duration.millis(1500) } }); stampGroup(producer, 0n, 0); expect(drainGroups(subscriber)).toEqual([0n]); for (const [sequence, ms] of [ @@ -4395,9 +4442,9 @@ test("a partial maxDelay widening keeps the older skip owed", () => { expect(drainGroups(subscriber)).toEqual([5n, 6n]); // Group 4 reaches 6s, 3s behind the 9s edge; group 1 reaches 2s, 7s behind. - subscriber.update({ delay: { max: Milli(4000) } }); + subscriber.update({ delay: { max: Duration.millis(4000) } }); expect(drainGroups(subscriber)).toEqual([4n]); - subscriber.update({ delay: { max: Milli(10_000) } }); + subscriber.update({ delay: { max: Duration.millis(10_000) } }); expect(drainGroups(subscriber)).toEqual([1n]); producer.close(); }); @@ -4457,7 +4504,7 @@ test("an errored end keeps its history", async () => { producer.close(); expect(producer.closed.peek()).toBe(failed); - const replay = { ranges: [{ start: { absolute: 0n } }], delay: { max: Milli(30_000) } }; + const replay = { ranges: [{ start: { absolute: 0n } }], delay: { max: Duration.millis(30_000) } }; const arrival = producer.subscribe(replay); expect((await arrival.recvGroup())?.sequence).toBe(0n); expect((await arrival.recvGroup())?.sequence).toBe(1n); @@ -4643,7 +4690,7 @@ test("a received stale run settles the suffix a narrower range asks for", () => hooks.receiveTrack(producer); hooks.supersedeStale(producer, [{ start: 0n, end: 10n }]); const reader = producer.subscribe({ - delay: { max: Milli(500) }, + delay: { max: Duration.millis(500) }, ranges: [{ start: { absolute: 5n }, end: { absolute: 10n } }], }); hooks.dropTrackGroups(producer, 0n, 10n, staleHole(500)); @@ -4688,8 +4735,8 @@ test("a huge skip costs one run", () => { // its stale drop must report it again rather than leave it owed: no skip offers it again. Mirrors // Rust. test("reopening stale drops reports again what is stale at the max age bound", () => { - const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(1500) }); - const reader = producer.subscribe({ delay: { max: Milli(1500) } }); + const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Duration.millis(1500) }); + const reader = producer.subscribe({ delay: { max: Duration.millis(1500) } }); const drain = () => { const got: unknown[] = []; for ( diff --git a/js/net/src/track.ts b/js/net/src/track.ts index 805bf6b2d20..c6586935fc3 100644 --- a/js/net/src/track.ts +++ b/js/net/src/track.ts @@ -4,7 +4,7 @@ * @module */ -import { Instant, Milli, Nano, now, sleepUntil } from "@moq/clock"; +import { Duration, Instant, now, sleepUntil } from "@moq/clock"; import { Derived, type Dispose, type GetPromise, type Getter, Once, Signal } from "@moq/signals"; import * as cache from "./cache.ts"; import { Delivered } from "./delivered.ts"; @@ -153,7 +153,7 @@ export interface Info { * {@link infoDefaults}, which refuses a negative or non-finite value and a result past * `Number.MAX_SAFE_INTEGER`. */ - maxAge?: Milli; + maxAge?: Duration; /** Tie-break priority between subscriptions of equal subscriber priority (`-128..=127`, higher first). Defaults to `0`. */ priority: number; /** @@ -187,7 +187,7 @@ export interface InfoInit extends Partial> { * get only the live edge; `null` sets no publisher limit (the wire omits it), and a number * is that bound. A track whose readers reach back for superseded groups sets it explicitly. */ - maxAge?: Milli | null; + maxAge?: Duration | null; } /** @@ -196,7 +196,7 @@ export interface InfoInit extends Partial> { */ export function authoredInfo(init: InfoInit = {}): Info { const { maxAge, ...rest } = init; - return infoDefaults({ ...rest, maxAge: maxAge === undefined ? Milli.zero : (maxAge ?? undefined) }); + return infoDefaults({ ...rest, maxAge: maxAge === undefined ? Duration.ZERO : (maxAge ?? undefined) }); } export { rescale }; @@ -207,15 +207,12 @@ export { rescale }; // millisecond is expected; ceil rather than round, because a budget shortened by rounding // skips a group the subscriber still wants. Anything that is not a duration is refused // here, where the field is named, rather than deep in the encoder. -function wireMillis(field: string, value: Milli): Milli { - if (!Number.isFinite(value) || value < 0) { - throw new RangeError(`${field} must be a non-negative number of milliseconds: ${value}`); - } - const millis = Math.ceil(value); +function wireMillis(field: string, value: Duration): Duration { + const millis = Math.ceil(value.asMillis()); if (!Number.isSafeInteger(millis)) { throw new RangeError(`${field} exceeds the safe integer millisecond range: ${value}`); } - return Milli(millis); + return Duration.millis(millis); } function priorityValue(value: number): number { @@ -322,7 +319,7 @@ export interface Delay { * pulls it to zero, and it is forwarded upstream as is. A publisher may use it, such as to * start a cold join that far back; nothing reads it there yet. */ - min?: Milli | null; + min?: Duration | null; /** * How long a non-latest group stays worth delivering, by the same two clocks as * {@link Info.maxAge}: it is skipped once its successor arrived this long ago or starts this @@ -331,7 +328,7 @@ export interface Delay { * publisher's {@link Info.maxAge} alone bounds it, which is what a reader reaching back for * history wants; read in order, see {@link Ordered} for where that can block. */ - max?: Milli | null; + max?: Duration | null; } /** @@ -395,7 +392,7 @@ export const Subscription: { } = { default: () => ({ priority: DEFAULT_PRIORITY, - delay: { min: Milli.zero, max: Milli.zero }, + delay: { min: Duration.ZERO, max: Duration.ZERO }, order: "descending", }), }; @@ -411,8 +408,11 @@ function subscriptionDefaults(subscription: Subscription = Subscription.default( return { priority: priorityValue(subscription.priority ?? DEFAULT_PRIORITY), delay: { - min: delay.min === null ? null : wireMillis("delay.min", delay.min ?? Milli.zero), - max: delay.max === null ? NO_MAX_DELAY : wireMillis("delay.max", delay.max ?? Milli.zero), + min: delay.min === null ? null : wireMillis("delay.min", delay.min ?? Duration.ZERO), + max: + delay.max === null + ? Duration.millis(NO_MAX_DELAY) + : wireMillis("delay.max", delay.max ?? Duration.ZERO), }, order: orderOf(subscription.order), ranges: subscription.ranges === undefined ? [{}] : rangesOf(subscription.ranges), @@ -427,10 +427,10 @@ function orderOf(order: Order | undefined): Order { } // The smaller of two minimums, ignoring one that went unstated (`null`). -function smallest(a: Milli | null | undefined, b: Milli | null | undefined): Milli | null { +function smallest(a: Duration | null | undefined, b: Duration | null | undefined): Duration | null { if (a === null || a === undefined) return b ?? null; if (b === null || b === undefined) return a; - return Milli(Math.min(a, b)); + return a.min(b); } // Aggregate the preferences of `states`, matching Rust's Subscription::poll_combined. @@ -446,7 +446,7 @@ function combineSubscriptions(states: Iterable): Subscription | unde combined.priority = Math.max(combined.priority ?? 0, subscription.priority ?? 0); combined.delay = { - max: Milli(Math.max(maxDelayOf(combined), maxDelayOf(subscription))), + max: Duration.millis(Math.max(maxDelayOf(combined), maxDelayOf(subscription))), // Only stated minimums count, so one that went unstated never pulls the smallest to zero. min: smallest(combined.delay?.min, subscription.delay?.min), }; @@ -563,7 +563,7 @@ export interface FetchGroupOptions { priority?: number; /** Maximum age behind the live edge this caller accepts. Omission leaves the publisher's {@link Info.maxAge} as the only bound. */ - maxDelay?: Milli; + maxDelay?: Duration; /** * Abandons this fetch, rejecting with the signal's reason. Concurrent fetches of the same @@ -850,8 +850,8 @@ let mayLand: (producer: Producer, land: Land) => boolean; // Recompute the producer's aggregates now, for a sink that just became a fetch; assigned in its // static block. let resubscribe: (producer: Producer) => void; -let owedRuns: (producer: Producer, start: bigint, end: bigint) => Iterable; -let owedGroup: (producer: Producer, start: bigint, end: bigint) => { sequence: bigint; folds?: number } | undefined; +let owedRuns: (producer: Producer, start: bigint, end: bigint) => Iterable; +let owedGroup: (producer: Producer, start: bigint, end: bigint) => { sequence: bigint; folds?: Instant } | undefined; let fillEdge: (producer: Producer) => bigint | undefined; let sourceStart: (producer: Producer) => bigint | "pending" | undefined; // The lowest group a reader naming `named` asks a fill for; see `Producer.#fillFloor`. @@ -1246,14 +1246,14 @@ export class Producer { // The first group that may still land from the live feed, by the rule a pending tail is judged // by; see {@link Land}. Mirrors the Rust `TrackState::may_land`. - #landable(land: Land): { sequence: bigint; folds?: number } | undefined { + #landable(land: Land): { sequence: bigint; folds?: Instant } | undefined { for (const run of this.#landing(land)) { if (!land.delivered?.covers(run.start, run.end)) return { sequence: run.start, folds: run.folds }; } return undefined; } - *#landing(land: Land): Generator { + *#landing(land: Land): Generator { if (this.#state.closed.peek() !== undefined) return; let start = land.start; if (!land.floor) { @@ -1265,11 +1265,11 @@ export class Producer { const declared = this.#state.end.peek()?.at; const end = declared === undefined ? land.end : min(land.end, finalSequence(declared)); const at = now(); - const limit = Nano.fromMilli(land.grace); + const limit = land.grace; const drops = this.#state.drops.peek(); for (const gap of this.#arrivals.gaps(start, end)) { - const folds = gap.since === undefined ? undefined : gap.since + limit; - if (folds !== undefined && at >= folds) continue; + const folds = gap.since?.add(limit); + if (folds !== undefined && at.ge(folds)) continue; for (const open of runGaps(drops, gap.start, gap.end)) { yield { ...open, folds }; } @@ -2020,11 +2020,11 @@ export class Producer { // The grace the session's tail uses, from the max delay the track's subscribers ask for, // bounded by how long the publisher keeps a superseded group fresh. The demand asked upstream is not. - #grace(): Milli { + #grace(): Duration { const update = this.#state.update.peek(); - const maxDelay = update ? maxDelayOf(update) : Milli.zero; + const maxDelay = Duration.millis(update ? maxDelayOf(update) : 0); const maxAge = this.#state.info.peek()?.maxAge; - return grace(maxAge === undefined ? maxDelay : Milli(Math.min(maxDelay, maxAge))); + return grace(maxAge === undefined ? maxDelay : maxDelay.min(maxAge)); } // Tell every reader whether the pending tail still owes a group below the end. @@ -2377,7 +2377,7 @@ export class Subscriber { const update = this.#state.update.peek(); const requested = this.#fetchBudget ?? (update ? maxDelayOf(update) : 0); - const fresh = info?.maxAge; + const fresh = info?.maxAge?.asMillis(); return { budget: fresh === undefined ? requested : Math.min(requested, fresh), bounded: fresh !== undefined && requested >= fresh, @@ -2460,8 +2460,8 @@ export class Subscriber { : this.#supersededAt(this.#arrival(sequence, drift.end), drift, held); if (arrived === undefined) return false; // Plain arithmetic: an unenforced budget is infinite, which no duration brand holds. - const deadline = arrived + drift.budget * 1_000_000; - if (now() >= deadline) return true; + const deadline = arrived.since(Instant.ZERO).asNanos() + drift.budget * 1_000_000; + if (now().since(Instant.ZERO).asNanos() >= deadline) return true; if (wake) this.#wakeAt(deadline); // A closed subscriber keeps no timeline to bound the reach with. if (this.#arrivals) return false; @@ -2497,7 +2497,7 @@ export class Subscriber { } if (!arrival || arrived === undefined) { held.successor = undefined; - } else if (recorded?.sequence !== arrival.sequence || recorded.arrived !== arrived || failed(recorded)) { + } else if (recorded?.sequence !== arrival.sequence || !recorded.arrived.eq(arrived) || failed(recorded)) { // Re-recorded only on a change, so judging the same successor again allocates nothing. held.successor = { sequence: arrival.sequence, arrived, fate: hooks.groupFate(arrival) }; } @@ -2529,7 +2529,7 @@ export class Subscriber { wall.timer?.abort(); const timer = new AbortController(); // A staleness wakeup is never a reason to hold a Node/Bun process open. - void sleepUntil(Instant(at), { signal: timer.signal, ref: false }).then( + void sleepUntil(Instant.ZERO.add(Duration.nanos(at)), { signal: timer.signal, ref: false }).then( () => { if (timer.signal.aborted) return; wall.timer = undefined; @@ -2941,7 +2941,7 @@ export class Subscriber { // Reordered streams still owed by the live feed are not cache misses. for (const run of owedRuns(producer, start, end)) { insertRun(accounted, run.start, run.end); - if (run.folds !== undefined) this.#wakeAt(run.folds); + if (run.folds !== undefined) this.#wakeAt(run.folds.since(Instant.ZERO).asNanos()); } // Below where the feed starts, only the history the copy's start rule leaves fillable. const floor = fillFloor(producer, this.#window.start()); @@ -3123,7 +3123,7 @@ export class Subscriber { if (held[index] && held[index].sequence < open.end) return false; const owed = producer && owedGroup(producer, open.start, open.end); if (owed) { - if (owed.folds !== undefined) this.#wakeAt(owed.folds); + if (owed.folds !== undefined) this.#wakeAt(owed.folds.since(Instant.ZERO).asNanos()); return false; } } @@ -3321,7 +3321,7 @@ export class Subscriber { hooks.groupChanged = (subscriber, fn) => subscriber.#groupChanged(fn); hooks.askFetch = (subscriber, sequence) => subscriber.#askFetch(sequence); hooks.fetchBudget = (subscriber, maxDelay) => { - subscriber.#fetchBudget = maxDelay ?? Number.POSITIVE_INFINITY; + subscriber.#fetchBudget = maxDelay?.asMillis() ?? Number.POSITIVE_INFINITY; subscriber.#state.fetch = true; // The sink joined as a live subscriber; leave the live aggregate before anyone sees it. if (subscriber.#state.producer) resubscribe(subscriber.#state.producer); @@ -3922,7 +3922,7 @@ export class Subscriber { const producer = this.#state.producer; if (start >= end || !producer) return false; // Only a hole in this reader's ranges is owed to it. - let owed: { sequence: bigint; folds?: number } | undefined; + let owed: { sequence: bigint; folds?: Instant } | undefined; for (const run of this.#window.runs(start, end)) { owed = owedGroup(producer, run.start, run.end); if (owed) break; @@ -3935,7 +3935,7 @@ export class Subscriber { return true; } if (this.#staleAt(owed.sequence, drift, true)) return false; - if (owed.folds !== undefined) this.#wakeAt(owed.folds); + if (owed.folds !== undefined) this.#wakeAt(owed.folds.since(Instant.ZERO).asNanos()); this.#state.waitingOrdered = true; return true; } diff --git a/js/net/src/util/deadline.ts b/js/net/src/util/deadline.ts index 284e3791e7e..d73d3927b14 100644 --- a/js/net/src/util/deadline.ts +++ b/js/net/src/util/deadline.ts @@ -1,4 +1,4 @@ -import { type Milli, Nano, sleep } from "@moq/clock"; +import { Duration, sleep } from "@moq/clock"; import { race } from "@moq/signals"; import { controlTimeout, error } from "../error.ts"; import type { Stream } from "../stream.ts"; @@ -26,9 +26,9 @@ export class Deadline { #owners: Abortable[] = []; #failure?: Error; - #budget?: Milli; + #budget?: Duration; - constructor(budget?: Milli) { + constructor(budget?: Duration) { this.#budget = budget; this.#rearm(); } @@ -99,8 +99,8 @@ export class Deadline { } /** Reject once the request goes the whole budget with none of its streams waiting to open. */ - async #expire(limit: Milli, done: AbortSignal): Promise { - const budget = Nano.fromMilli(limit); + async #expire(limit: Duration, done: AbortSignal): Promise { + const budget = limit; const answered = new Promise((resolve) => done.addEventListener("abort", () => resolve(), { once: true }), ); diff --git a/js/net/src/util/timeout.test.ts b/js/net/src/util/timeout.test.ts index a204222eed2..b83af8a2e8d 100644 --- a/js/net/src/util/timeout.test.ts +++ b/js/net/src/util/timeout.test.ts @@ -1,9 +1,9 @@ import { expect, test } from "bun:test"; -import { Manual, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { TimeoutError, withTimeout } from "./timeout.ts"; test("withTimeout: resolves before deadline", async () => { - const result = await withTimeout(Promise.resolve(42), Nano(100), "should not fire"); + const result = await withTimeout(Promise.resolve(42), Duration.nanos(100), "should not fire"); expect(result).toBe(42); }); @@ -14,10 +14,10 @@ test("withTimeout: rejects with TimeoutError after deadline", async () => { const clock = new Manual(); const installed = clock.install(); try { - const timed = withTimeout(pending, Nano(10), "timed out").catch((err: unknown) => err); - await clock.advance(Nano(9)); + const timed = withTimeout(pending, Duration.nanos(10), "timed out").catch((err: unknown) => err); + await clock.advance(Duration.nanos(9)); expect(await Promise.race([timed, "pending"])).toBe("pending"); - await clock.advance(Nano(1)); + await clock.advance(Duration.nanos(1)); expect(await timed).toBeInstanceOf(TimeoutError); } finally { installed.close(); @@ -26,5 +26,5 @@ test("withTimeout: rejects with TimeoutError after deadline", async () => { test("withTimeout: passes through promise rejection", async () => { const failure = Promise.reject(new Error("boom")); - await expect(withTimeout(failure, Nano(100), "should not fire")).rejects.toThrow("boom"); + await expect(withTimeout(failure, Duration.nanos(100), "should not fire")).rejects.toThrow("boom"); }); diff --git a/js/net/src/util/timeout.ts b/js/net/src/util/timeout.ts index a728a6fae7d..ab79830b13a 100644 --- a/js/net/src/util/timeout.ts +++ b/js/net/src/util/timeout.ts @@ -1,4 +1,4 @@ -import { Elapsed, type Nano, timeout } from "@moq/clock"; +import { Duration, Elapsed, timeout } from "@moq/clock"; export class TimeoutError extends Error { constructor(message: string) { @@ -10,7 +10,7 @@ export class TimeoutError extends Error { // Race `promise` against a timeout on the installed clock. There's no cancellation; if // `promise` settles after the timeout fires the caller is responsible for cleaning up any // side effects (open streams, etc.) it may produce. -export async function withTimeout(promise: Promise, duration: Nano, message: string): Promise { +export async function withTimeout(promise: Promise, duration: Duration, message: string): Promise { try { return await timeout(duration, promise); } catch (err) { diff --git a/js/net/src/util/timer.ts b/js/net/src/util/timer.ts index 73dfde0c320..28dc489b195 100644 --- a/js/net/src/util/timer.ts +++ b/js/net/src/util/timer.ts @@ -1,4 +1,4 @@ -import { type Nano, sleep } from "@moq/clock"; +import { Duration, sleep } from "@moq/clock"; /** * Run `fn` after `duration` on the installed clock, and return the call that cancels it. @@ -7,7 +7,7 @@ import { type Nano, sleep } from "@moq/clock"; * * @internal */ -export function after(duration: Nano, fn: () => void, options?: { ref?: boolean }): () => void { +export function after(duration: Duration, fn: () => void, options?: { ref?: boolean }): () => void { const abort = new AbortController(); void sleep(duration, { signal: abort.signal, ref: options?.ref }).then(() => { // The wakeup can already be queued when the timer is cancelled. diff --git a/js/qmux/src/session.test.ts b/js/qmux/src/session.test.ts index 4cd81df4589..c150bdba868 100644 --- a/js/qmux/src/session.test.ts +++ b/js/qmux/src/session.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; -import { type Installed, Instant, Manual, Milli, Nano, now, yieldNow } from "@moq/clock"; +import { Duration, type Installed, Manual, now, yieldNow } from "@moq/clock"; import { SessionError, StreamError } from "./error.ts"; import * as Frame from "./frame.ts"; import { DEFAULT_MAX_RECORD_SIZE, type TransportParams } from "./frame.ts"; @@ -177,9 +177,9 @@ class FakeServerSocket implements WebSocketLike { /** Poll an observable condition with a bounded timeout (no fixed-yield sleeps). */ async function waitFor(check: () => boolean, timeoutMs = 1000): Promise { - const deadline = Instant.add(now(), Nano.fromMilli(Milli(timeoutMs))); + const deadline = now().add(Duration.millis(timeoutMs)); while (!check()) { - if (now() > deadline) throw new Error("timed out waiting for condition"); + if (now().gt(deadline)) throw new Error("timed out waiting for condition"); await yieldNow(); } } @@ -877,7 +877,7 @@ describe("Session integration (scripted peer)", () => { const clock = new Manual(); const installed = clock.install(); try { - const { session, peer } = connect({ idleTimeout: 300 }); + const { session, peer } = connect({ idleTimeout: Duration.millis(300) }); await started(peer); await waitFor(() => peer.has("transport_parameters")); peer.send({ type: "transport_parameters", params: peerParams() }); @@ -887,7 +887,7 @@ describe("Session integration (scripted peer)", () => { // every keep-alive tick finds our send side silent. peer.blockWrites(); for (let i = 0; i < 40; i++) { - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); peer.send({ type: "ping_response", sequence: 0n }); await settle(); } @@ -950,7 +950,12 @@ describe("Session integration (scripted peer)", () => { }); test("disabled config uses null and invalid durations fail before opening", () => { - for (const value of [0, -1, 1.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1]) { + // A plain number is the old millisecond config, refused rather than misread. + for (const value of [ + Duration.ZERO, + Duration.millis(Number.MAX_SAFE_INTEGER + 1), + 30_000 as unknown as Duration, + ]) { expect(() => new Session("https://example/test", { config: { idleTimeout: value } })).toThrow( "idleTimeout", ); @@ -1191,7 +1196,7 @@ describe("Session integration (scripted peer)", () => { const before = await wedge(session, peer); session.close({ closeCode: 42, reason: "bye" }); - await clock.advance(Nano.fromMilli(Milli(1000))); + await clock.advance(Duration.millis(1000)); await settle(); expect(peer.closeInfo).toBeUndefined(); @@ -1208,11 +1213,11 @@ describe("Session integration (scripted peer)", () => { await wedge(session, peer); session.close({ closeCode: 42, reason: "bye" }); - await clock.advance(Nano.fromMilli(Milli(2999))); + await clock.advance(Duration.millis(2999)); await settle(); expect(peer.closeInfo).toBeUndefined(); - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); await settle(); expect(peer.closeInfo).toBeDefined(); expect(peer.has("application_close")).toBe(false); @@ -1294,7 +1299,7 @@ describe("Session integration (scripted peer)", () => { const clock = new Manual(); const installed = clock.install(); try { - const { session, peer } = connect({ idleTimeout: 150 }); + const { session, peer } = connect({ idleTimeout: Duration.millis(150) }); await started(peer); await waitFor(() => peer.has("transport_parameters")); // A successfully written keep-alive is send activity under QMux. Block the @@ -1314,10 +1319,10 @@ describe("Session integration (scripted peer)", () => { ); // Exactly at the deadline the session is still open; one tick past it closes. - await clock.advance(Nano.fromMilli(Milli(150))); + await clock.advance(Duration.millis(150)); await settle(); expect(settled).toBe(false); - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); const err = await expectSessionFailure(session); expect(err.message).toContain("idle timeout"); @@ -1331,11 +1336,11 @@ describe("Session integration (scripted peer)", () => { const clock = new Manual(); const installed = clock.install(); try { - const { session, peer } = connect({ idleTimeout: 150 }); + const { session, peer } = connect({ idleTimeout: Duration.millis(150) }); await started(peer); await waitFor(() => peer.has("transport_parameters")); - await clock.advance(Nano.fromMilli(Milli(200))); + await clock.advance(Duration.millis(200)); const err = await expectSessionFailure(session); expect(err.message).toContain("idle timeout"); expect(peer.has("ping_request")).toBe(false); @@ -1348,14 +1353,14 @@ describe("Session integration (scripted peer)", () => { const clock = new Manual(); const installed = clock.install(); try { - const { session, peer } = connect({ idleTimeout: 120 }); + const { session, peer } = connect({ idleTimeout: Duration.millis(120) }); peer.send({ type: "transport_parameters", params: peerParams() }); await session.ready; const writable = await session.createUnidirectionalStream(); const writer = writable.getWriter(); for (let i = 0; i < 6; i++) { - await clock.advance(Nano.fromMilli(Milli(45))); + await clock.advance(Duration.millis(45)); await writer.write(new Uint8Array([i])); // The peer answers every other write, as a live peer responding to the // keep-alive would. A send restarts the deadline only once per receive @@ -1382,7 +1387,7 @@ describe("Session integration (scripted peer)", () => { const clock = new Manual(); const installed = clock.install(); try { - const { session, peer } = connect({ idleTimeout: 120 }); + const { session, peer } = connect({ idleTimeout: Duration.millis(120) }); peer.send({ type: "transport_parameters", params: peerParams() }); await session.ready; @@ -1390,7 +1395,7 @@ describe("Session integration (scripted peer)", () => { const writer = writable.getWriter(); try { for (let i = 0; i < 12; i++) { - await clock.advance(Nano.fromMilli(Milli(45))); + await clock.advance(Duration.millis(45)); await writer.write(new Uint8Array([i])); await settle(); } @@ -2723,14 +2728,17 @@ describe("STREAM frame size", () => { const clock = new Manual(); const installed = clock.install(); try { - const { session, peer } = accept({ protocol: "qmux-00", config: { handshakeTimeout: 150 } }); + const { session, peer } = accept({ + protocol: "qmux-00", + config: { handshakeTimeout: Duration.millis(150) }, + }); await started(peer); const ready = settleTo(session.ready); - await clock.advance(Nano.fromMilli(Milli(150))); + await clock.advance(Duration.millis(150)); await settle(); expect(peer.has("connection_close")).toBe(false); - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); const err = await expectSessionFailure(session); expect(err.message).toContain("handshake timeout"); diff --git a/js/qmux/src/session.ts b/js/qmux/src/session.ts index 8c62c907eca..8b546408a5e 100644 --- a/js/qmux/src/session.ts +++ b/js/qmux/src/session.ts @@ -1,15 +1,4 @@ -import { - Elapsed, - Instant, - type Interval, - interval, - Milli, - MissedTickBehavior, - Nano, - now, - Second, - timeout, -} from "@moq/clock"; +import { Duration, Elapsed, Instant, type Interval, interval, MissedTickBehavior, now, timeout } from "@moq/clock"; import { Credit, StreamLimit, Window } from "./credit.ts"; import { resetCode, SessionError, StreamError, streamCode } from "./error.ts"; import type { TransportParams, WireFormat } from "./frame.ts"; @@ -47,11 +36,11 @@ export interface Config { receiveWindow?: bigint; /** Receive window in bytes for every stream. */ streamReceiveWindow?: bigint; - /** Idle timeout in milliseconds, or null to disable it; zero is refused. */ - idleTimeout?: number | null; - /** How long `ready` waits for the peer's transport parameters, in milliseconds, or null to wait - * indefinitely; zero is refused. The session closes when it passes. */ - handshakeTimeout?: number | null; + /** Idle timeout, sent as whole milliseconds rounded up, or null to disable it; zero is refused. */ + idleTimeout?: Duration | null; + /** How long `ready` waits for the peer's transport parameters, or null to wait indefinitely; + * zero is refused. The session closes when it passes. */ + handshakeTimeout?: Duration | null; /** Maximum QMux Record size in bytes (draft-01). */ maxRecordSize?: bigint; /** Largest DATAGRAM *frame* (RFC 9221: type + length + payload) we advertise @@ -68,8 +57,8 @@ const DEFAULT_CONFIG: Required = { maxStreamsUni: 100n, receiveWindow: 1_048_576n, streamReceiveWindow: 262_144n, - idleTimeout: 30_000, - handshakeTimeout: 10_000, + idleTimeout: Duration.secs(30), + handshakeTimeout: Duration.secs(10), maxRecordSize: Frame.DEFAULT_MAX_RECORD_SIZE, // Fill a full record by default; the record layer bounds the size. maxDatagramFrameSize: Frame.DEFAULT_MAX_RECORD_SIZE, @@ -89,8 +78,11 @@ function resolveConfig(config?: Config): Required { } for (const [key, value] of Object.entries(resolved)) { if (key === "idleTimeout" || key === "handshakeTimeout") { - if (value !== null && (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0)) { - throw new TypeError(`${key} must be a positive safe integer or null`); + if (value !== null && (!(value instanceof Duration) || value.isZero())) { + throw new TypeError(`${key} must be a positive Duration or null`); + } + if (value !== null && !Number.isSafeInteger(Math.ceil(value.asMillis()))) { + throw new TypeError(`${key} exceeds the safe integer millisecond range`); } } else if (key !== "maxDatagramFrameSize" || value !== null) { if (typeof value !== "bigint") throw new TypeError(`${key} must be a bigint`); @@ -106,7 +98,7 @@ function resolveConfig(config?: Config): Required { function configToTransportParams(config: Required): TransportParams { return { - maxIdleTimeout: BigInt(config.idleTimeout ?? 0), + maxIdleTimeout: BigInt(config.idleTimeout === null ? 0 : Math.ceil(config.idleTimeout.asMillis())), initialMaxData: config.receiveWindow, initialMaxStreamDataBidiLocal: config.streamReceiveWindow, initialMaxStreamDataBidiRemote: config.streamReceiveWindow, @@ -464,7 +456,7 @@ const DEFAULT_SEND_BUFFER_SIZE = 64 * 1024; /** How long a closing session waits for a backed-up socket to take its close * frame, matching Rust's `CLOSE_TIMEOUT`. A peer that stopped reading can't * hold the socket open past it. */ -const CLOSE_TIMEOUT = Nano.fromSecond(Second(3)); +const CLOSE_TIMEOUT = Duration.secs(3); /** Present the caller's socket as a `WebSocketStreamLike`, whichever they passed. * @@ -731,8 +723,8 @@ export default class Session implements WebTransport { #lastSendAt = now(); // Deadline bookkeeping for #idleActivityAt: the newest receive observed, the // send last allowed to restart the deadline, and whether a send may restart it. - #recvSeen = Instant.zero; - #sendResetAt = Instant.zero; + #recvSeen = Instant.ZERO; + #sendResetAt = Instant.ZERO; #sendCredit = true; #nextPingSeq = 0; // Highest sequence seen in a received QX_PING request (draft-02 requires them @@ -985,7 +977,7 @@ export default class Session implements WebTransport { // a peer that never sends its parameters can't hold `ready` forever. const handshake = this.#config.handshakeTimeout; if (handshake !== null) { - timeout(Nano.fromMilli(Milli(handshake)), this.ready).catch((err) => { + timeout(handshake, this.ready).catch((err) => { if (!(err instanceof Elapsed)) return; this.#closeReason ??= new Error("handshake timeout"); this.#abort(0, "handshake timeout"); @@ -1195,14 +1187,14 @@ export default class Session implements WebTransport { if (timeoutMs === 0n) return; // Poll at a fraction of the timeout - frequent enough to trigger pings on time // but not so frequent it burns CPU on otherwise-quiet sessions. - const timeout = Nano.fromMilli(Milli(Number(timeoutMs))); - const timer = interval(Nano.fromMilli(Milli(Math.max(50, Number(timeoutMs) / 6)))); + const timeout = Duration.millis(Number(timeoutMs)); + const timer = interval(Duration.millis(Math.max(50, Number(timeoutMs) / 6))); timer.setMissedTickBehavior(MissedTickBehavior.Delay); this.#idleTimer = timer; void this.#idleLoop(timer, timeout); } - async #idleLoop(timer: Interval, timeout: Nano) { + async #idleLoop(timer: Interval, timeout: Duration) { // The first tick is immediate; the first check belongs one period in. let first = true; for (;;) { @@ -1235,21 +1227,20 @@ export default class Session implements WebTransport { * re-arms the credit. */ #idleActivityAt(): Instant { - if (this.#lastRecvAt > this.#recvSeen) { + if (this.#lastRecvAt.gt(this.#recvSeen)) { this.#recvSeen = this.#lastRecvAt; this.#sendCredit = true; } - if (this.#sendCredit && this.#lastSendAt > this.#sendResetAt) { + if (this.#sendCredit && this.#lastSendAt.gt(this.#sendResetAt)) { this.#sendResetAt = this.#lastSendAt; this.#sendCredit = false; } - // biome-ignore lint/complexity/useMathMinMax: bigint operands; Math.min/max throw on bigint. - return this.#recvSeen > this.#sendResetAt ? this.#recvSeen : this.#sendResetAt; + return this.#recvSeen.max(this.#sendResetAt); } - #idleTick(timeout: Nano) { + #idleTick(timeout: Duration) { const at = now(); - if (Instant.durationSince(at, this.#idleActivityAt()) > timeout) { + if (at.since(this.#idleActivityAt()).gt(timeout)) { // No frames have been sent or received within the negotiated limit. Abnormal: // without a rejection this is indistinguishable from a graceful close(), which // also settles with closeCode 0. @@ -1261,7 +1252,7 @@ export default class Session implements WebTransport { // Keep-alive: nudge the peer when our outbound side has been silent for a third // of the timeout. Any frame counts as activity, so this only fires when truly idle. // Nothing to keep alive before the peer has spoken at all. - if (this.#paramsReceived && Instant.durationSince(at, this.#lastSendAt) > timeout / 3) { + if (this.#paramsReceived && at.since(this.#lastSendAt).gt(timeout.div(3))) { const seq = this.#nextPingSeq; // Monotonic (never wraps within a session's life): the draft-02 // strictly-increasing rule requires it, and it must not wrap earlier diff --git a/js/qmux/src/web-socket-stream.test.ts b/js/qmux/src/web-socket-stream.test.ts index 2d85516ec2f..6a19b4a88fc 100644 --- a/js/qmux/src/web-socket-stream.test.ts +++ b/js/qmux/src/web-socket-stream.test.ts @@ -1,5 +1,5 @@ import { describe, expect, onTestFinished, test } from "bun:test"; -import { Manual, Milli, Nano, yieldNow } from "@moq/clock"; +import { Duration, Manual, yieldNow } from "@moq/clock"; import { openWebSocketStream, type WebSocketConstructor, @@ -69,7 +69,7 @@ function manual(): Manual { } /** Long enough for the ponyfill to poll `bufferedAmount` many times. */ -const POLLS = Nano.fromMilli(Milli(1000)); +const POLLS = Duration.millis(1000); describe("WebSocketStream ponyfill", () => { test("opened resolves with streams and negotiated protocol", async () => { diff --git a/js/qmux/src/web-socket-stream.ts b/js/qmux/src/web-socket-stream.ts index b02520968d9..75aaf9f4330 100644 --- a/js/qmux/src/web-socket-stream.ts +++ b/js/qmux/src/web-socket-stream.ts @@ -13,7 +13,7 @@ * [spec]: https://github.com/ricea/websocketstream-explainer */ -import { Milli, Nano, sleep } from "@moq/clock"; +import { Duration, sleep } from "@moq/clock"; /** The data yielded by the readable / accepted by the writable. */ export type WebSocketStreamData = Uint8Array | string; @@ -152,7 +152,7 @@ function drain(ws: WebSocketLike, highWaterMark: () => number): Promise | // The socket closed mid-write: reject so the failure propagates rather // than resolving the write as if it had succeeded. if (ws.readyState > OPEN) throw new Error("WebSocket is closing"); - await sleep(Nano.fromMilli(Milli(10))); + await sleep(Duration.millis(10)); } })(); } From 541e3fef6efe252b205c9e0ffca704d43b5a4a8c Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 09:55:57 -0800 Subject: [PATCH 04/17] feat(hang,loc)!: media timestamps are Clock Durations Co-Authored-By: Claude Opus 5.5 --- js/hang/bench/buffered.ts | 14 +- js/hang/bench/jitter.ts | 7 +- js/hang/bench/slow-group.ts | 10 +- js/hang/src/cmaf/format.test.ts | 9 +- js/hang/src/cmaf/format.ts | 6 +- .../container/consumer.backpressure.test.ts | 118 ++-- js/hang/src/container/consumer.holes.test.ts | 88 +-- .../container/consumer.nonsequential.test.ts | 22 +- .../src/container/consumer.outoforder.test.ts | 34 +- js/hang/src/container/consumer.rewind.test.ts | 52 +- js/hang/src/container/consumer.skips.test.ts | 48 +- .../src/container/consumer.startup.test.ts | 16 +- js/hang/src/container/consumer.test.ts | 612 +++++++++--------- js/hang/src/container/consumer.ts | 124 ++-- js/hang/src/container/consumer.warmup.test.ts | 22 +- js/hang/src/container/format.ts | 4 +- js/hang/src/container/jitter.test.ts | 25 +- js/hang/src/container/jitter.ts | 13 +- js/hang/src/container/legacy.ts | 54 +- js/hang/src/container/track.test.ts | 12 +- js/hang/src/container/track.ts | 6 +- js/hang/src/container/types.ts | 28 +- js/loc/src/index.test.ts | 14 +- js/loc/src/index.ts | 10 +- 24 files changed, 677 insertions(+), 671 deletions(-) diff --git a/js/hang/bench/buffered.ts b/js/hang/bench/buffered.ts index 4573bacf5fa..acce7700681 100644 --- a/js/hang/bench/buffered.ts +++ b/js/hang/bench/buffered.ts @@ -1,12 +1,12 @@ /** Sweep buffered groups, frames per group, publishers and players through the container consumer. */ -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { type Group, Time, Track, Varint } from "@moq/net"; import { Signal } from "@moq/signals"; import { Consumer } from "../src/container/consumer.ts"; import { Format } from "../src/container/legacy.ts"; // Far past every fixture's span, so only the burst case skips anything. -const HOLD = Milli(1_000_000_000); +const HOLD = Duration.millis(1_000_000_000); // One group per second at 30 fps. const FRAME_US = 33_333; const GROUP_US = 1_000_000; @@ -82,7 +82,7 @@ async function drain(player: Player, expected: number[]): Promise { gaps++; continue; } - if (read.kind !== "frame" || read.frame.timestamp !== want || read.frame.payload[0] !== PAYLOAD[0]) + if (read.kind !== "frame" || read.frame.timestamp.asMicros() !== want || read.frame.payload[0] !== PAYLOAD[0]) throw new Error("frame missing or reordered"); break; } @@ -91,7 +91,7 @@ async function drain(player: Player, expected: number[]): Promise { } function ranges(player: Player): string { - return JSON.stringify(player.consumer.buffered.peek()); + return JSON.stringify(player.consumer.buffered.peek().map((r) => ({ start: r.start.asMillis(), end: r.end.asMillis() }))); } /** Return elapsed ns, the measured operations, gaps and warnings for one case. */ @@ -129,7 +129,7 @@ async function measure( const reads = players.map((player) => player.consumer.next()); for (const source of sources) source.writeFrame(wire(i, frame)); for (const read of await Promise.all(reads)) - if (read?.kind !== "frame" || read.frame.timestamp !== timestamp(i, frame)) + if (read?.kind !== "frame" || read.frame.timestamp.asMicros() !== timestamp(i, frame)) throw new Error("frame missing or reordered"); } for (const source of sources) source.finish(); @@ -161,7 +161,7 @@ async function measure( if (scenario === "burst") { // The budget drops to nothing, so the next arrival makes every older group too stale to keep. - delay.set({ max: Milli.zero }); + delay.set({ max: Duration.ZERO }); start = performance.now(); const sources = tracks.map((track) => track.createGroup(BigInt(groups))); await arrive(sources, players, groups, 0); @@ -173,7 +173,7 @@ async function measure( if (player.received.slice(0, groups).some((group) => !group.isClosed)) throw new Error("skipped group left open"); const read = await player.consumer.next(); - if (read?.kind !== "frame" || read.frame.timestamp !== timestamp(groups, 0)) + if (read?.kind !== "frame" || read.frame.timestamp.asMicros() !== timestamp(groups, 0)) throw new Error("newest frame missing"); } return { ns: elapsed, ops: groups * players.length, gaps, warnings }; diff --git a/js/hang/bench/jitter.ts b/js/hang/bench/jitter.ts index 35da4373424..2adf4b7a7ed 100644 --- a/js/hang/bench/jitter.ts +++ b/js/hang/bench/jitter.ts @@ -1,7 +1,6 @@ // Sweep the jitter estimator's held history against in-order and reordered frames, the per-frame // cost a publisher controls through its timestamp rate. -import type { Milli } from "@moq/clock"; import { Jitter } from "../src/container/jitter.ts"; const FRAMES = 100_000; @@ -13,16 +12,16 @@ for (const held of [64, 512, 4096, 8192]) { // Spaced so `held` frames fit inside the two-second window. const step = 2000 / held; let media = 0; - for (let i = 0; i < held; i++, media += step) jitter.observe(media as Milli, media as Milli); + for (let i = 0; i < held; i++, media += step) jitter.observe(media, media); const started = performance.now(); for (let i = 0; i < FRAMES; i++) { if (order === "in") { - jitter.observe(media as Milli, media as Milli); + jitter.observe(media, media); media += step; } else { // Just behind the newest, so the reference covers almost the whole history. - jitter.observe(media as Milli, (media - 2 * step) as Milli); + jitter.observe(media, media - 2 * step); } } const ns = ((performance.now() - started) * 1e6) / FRAMES; diff --git a/js/hang/bench/slow-group.ts b/js/hang/bench/slow-group.ts index a082161bba1..4004d48f30d 100644 --- a/js/hang/bench/slow-group.ts +++ b/js/hang/bench/slow-group.ts @@ -1,6 +1,6 @@ // Measure warning traffic and catch-up time over the groups a slow consumer skips. -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { Time, Track, Varint } from "@moq/net"; import { Signal } from "@moq/signals"; import { Consumer } from "../src/container/consumer.ts"; @@ -9,8 +9,8 @@ import { Format } from "../src/container/legacy.ts"; console.log("groups,warnings,bytes,catchup_ms"); for (const count of [1, 16, 256, 1024]) { const track = new Track.Producer("tone"); - const delay = new Signal({ max: Milli(30_000) }); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const delay = new Signal({ max: Duration.millis(30_000) }); + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), delay, }); @@ -19,7 +19,7 @@ for (const count of [1, 16, 256, 1024]) { group.writeFrame({ payload: Varint.encode(Number(sequence) * 1000), timestamp: Time.Timestamp.now() }); }; const buffered = async (timestamp: number) => { - while (consumer.buffered.peek().at(-1)?.end !== timestamp) await consumer.buffered.changed(); + while (consumer.buffered.peek().at(-1)?.end.asMillis() !== timestamp) await consumer.buffered.changed(); }; let warnings = 0; let bytes = 0; @@ -31,7 +31,7 @@ for (const count of [1, 16, 256, 1024]) { try { for (let i = 0n; i < BigInt(count); i++) write(i); await buffered(count - 1); - delay.set({ max: Milli.zero }); + delay.set({ max: Duration.ZERO }); const started = performance.now(); write(BigInt(count)); await buffered(count); diff --git a/js/hang/src/cmaf/format.test.ts b/js/hang/src/cmaf/format.test.ts index ffbeccf15f4..8eada5dd01c 100644 --- a/js/hang/src/cmaf/format.test.ts +++ b/js/hang/src/cmaf/format.test.ts @@ -1,5 +1,4 @@ import { expect, test } from "bun:test"; -import type { Micro } from "@moq/clock"; import { Time } from "@moq/net"; import type { InitSegment } from "./decode.ts"; import { Format } from "./format.ts"; @@ -75,7 +74,7 @@ test("CmafFormat times samples from the frame timestamp", () => { ]); const frames = new Format(INIT).decode(segment, Time.Timestamp.fromMillis(10_000)); - expect(frames.map((f) => f.timestamp)).toEqual([10_000_000, 10_066_667, 10_033_333] as Micro[]); + expect(frames.map((f) => f.timestamp.asMicros())).toEqual([10_000_000, 10_066_667, 10_033_333]); }); // A fragment can open on a sample that presents after a later one (open-GOP leading pictures, @@ -87,7 +86,7 @@ test("CmafFormat anchors the earliest presentation time", () => { ]); const frames = new Format(INIT).decode(segment, Time.Timestamp.fromMillis(5_000)); - expect(frames.map((f) => f.timestamp)).toEqual([5_033_333, 5_000_000] as Micro[]); + expect(frames.map((f) => f.timestamp.asMicros())).toEqual([5_033_333, 5_000_000]); }); // Runs continue one decode timeline, so the anchor is the earliest sample across all of them. @@ -95,7 +94,7 @@ test("CmafFormat anchors the earliest sample across runs", () => { const segment = fragment(0, [[3000, 6000]], [[3000, 0]]); const frames = new Format(INIT).decode(segment, at(3000)); - expect(frames.map((f) => f.timestamp)).toEqual([66_667, 33_333] as Micro[]); + expect(frames.map((f) => f.timestamp.asMicros())).toEqual([66_667, 33_333]); }); // An untimed track's frames carry no broadcast time, so their samples present at `tfdt`. @@ -107,7 +106,7 @@ test("CmafFormat times an untimed fragment from its tfdt", () => { ]); const frames = new Format(INIT).decode(segment, undefined); - expect(frames.map((f) => f.timestamp)).toEqual([1_033_333, 1_100_000, 1_066_667] as Micro[]); + expect(frames.map((f) => f.timestamp.asMicros())).toEqual([1_033_333, 1_100_000, 1_066_667]); }); // Samples are read front to back, so a run that skips bytes is refused rather than sliced wrong. diff --git a/js/hang/src/cmaf/format.ts b/js/hang/src/cmaf/format.ts index 34a474cad00..97641c70540 100644 --- a/js/hang/src/cmaf/format.ts +++ b/js/hang/src/cmaf/format.ts @@ -1,4 +1,4 @@ -import type { Micro } from "@moq/clock"; +import { Duration } from "@moq/clock"; import type { Time } from "@moq/net"; import type { Format as ContainerFormat } from "../container/format"; import type { Frame } from "../container/types"; @@ -17,9 +17,9 @@ export class Format implements ContainerFormat { decode(payload: Uint8Array, timestamp: Time.Timestamp | undefined): Frame[] { return decodeDataSegment(payload, this.#init, timestamp).map((s) => ({ payload: s.data, - timestamp: s.timestamp as Micro, + timestamp: Duration.micros(s.timestamp), keyframe: s.keyframe, - duration: s.duration as Micro, + duration: Duration.micros(s.duration), })); } } diff --git a/js/hang/src/container/consumer.backpressure.test.ts b/js/hang/src/container/consumer.backpressure.test.ts index 35711904f8e..c9c9a0ff33b 100644 --- a/js/hang/src/container/consumer.backpressure.test.ts +++ b/js/hang/src/container/consumer.backpressure.test.ts @@ -1,5 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { Elapsed, Manual, type Micro, Milli, Nano, timeout } from "@moq/clock"; +import { Duration, Elapsed, Instant, Manual, timeout } from "@moq/clock"; import { Time, Track } from "@moq/net"; import { Consumer, type Read } from "./consumer.ts"; import { encodeFrame, Format } from "./legacy.ts"; @@ -22,7 +22,7 @@ const PAYLOAD = new Uint8Array([0xde, 0xad]); const flush = () => new Promise((resolve) => setImmediate(resolve)); function write(group: { writeFrame(frame: { payload: Uint8Array; timestamp: Time.Timestamp }): void }, ts: number) { - group.writeFrame({ payload: encodeFrame(PAYLOAD, ts as Micro), timestamp: Time.Timestamp.now() }); + group.writeFrame({ payload: encodeFrame(PAYLOAD, Duration.micros(ts)), timestamp: Time.Timestamp.now() }); } // The most frames the consumer may hold: past the max buffer, one more wire frame. Each held frame @@ -47,7 +47,7 @@ async function readAll(consumer: Consumer, format: Counting, bounded?: number): } function timestamps(reads: Read[]): number[] { - return reads.flatMap((read) => (read.kind === "frame" ? [read.frame.timestamp] : [])); + return reads.flatMap((read) => (read.kind === "frame" ? [read.frame.timestamp.asMicros()] : [])); } test("Consumer holds frames sharing a timestamp within the max buffer", async () => { @@ -55,9 +55,9 @@ test("Consumer holds frames sharing a timestamp within the max buffer", async () const maxBuffer = 4096; const format = new Counting("data"); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format, - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, maxBuffer, }); try { @@ -90,9 +90,9 @@ test("Consumer holds many groups within the max buffer and reaches the live edge const maxBuffer = 8192; const format = new Counting("data"); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format, - delay: { max: Milli(100) }, + delay: { max: Duration.millis(100) }, maxBuffer, }); try { @@ -125,9 +125,9 @@ test("Consumer skips a stalled group once group overhead alone fills the max buf const warn = spyOn(console, "warn").mockImplementation(() => {}); const format = new Counting("data"); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format, - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, // Two groups' overhead, so nothing past the stalled head would decode without its successor leading. maxBuffer: 512, }); @@ -138,9 +138,9 @@ test("Consumer skips a stalled group once group overhead alone fills the max buf write(next, 10_000); next.finish(); - expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: 0 } }); + expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(0) } }); expect(await consumer.next()).toMatchObject({ kind: "gap" }); - expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: 10_000 } }); + expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(10_000) } }); } finally { consumer.close(); track.close(); @@ -152,9 +152,9 @@ test("Consumer reaches a readable group past a stalled successor once group over const warn = spyOn(console, "warn").mockImplementation(() => {}); const format = new Counting("data"); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format, - delay: { max: Milli.zero }, + delay: { max: Duration.ZERO }, // Three groups' overhead: the readable group cannot decode until the stalled ones are moved past. maxBuffer: 768, }); @@ -167,10 +167,10 @@ test("Consumer reaches a readable group past a stalled successor once group over write(readable, 20_000); readable.finish(); - expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: 0 } }); + expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(0) } }); expect(await consumer.next()).toMatchObject({ kind: "gap" }); - expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: 10_000 } }); - expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: 20_000 } }); + expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(10_000) } }); + expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(20_000) } }); } finally { consumer.close(); track.close(); @@ -181,9 +181,9 @@ test("Consumer reaches a readable group past a stalled successor once group over test("Consumer admits reads completing together one at a time against the max buffer", async () => { const format = new Counting("data"); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format, - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, maxBuffer: 4096, }); try { @@ -193,7 +193,7 @@ test("Consumer admits reads completing together one at a time against the max bu await flush(); const large = new Uint8Array(2_000); for (const group of groups) { - group.writeFrame({ payload: encodeFrame(large, 0 as Micro), timestamp: Time.Timestamp.now() }); + group.writeFrame({ payload: encodeFrame(large, Duration.micros(0)), timestamp: Time.Timestamp.now() }); } await flush(); @@ -216,9 +216,9 @@ class Header extends Format { test("Consumer charges a small view of a large wire frame the wire frame", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Header("data"), - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, maxBuffer: 16 * 1024, }); try { @@ -228,7 +228,7 @@ test("Consumer charges a small view of a large wire frame the wire frame", async const padding = new Uint8Array(60_000); for (let i = 0; i < 8; i++) { padded.writeFrame({ - payload: encodeFrame(padding, (10_000 + i) as Micro), + payload: encodeFrame(padding, Duration.micros((10_000 + i))), timestamp: Time.Timestamp.now(), }); } @@ -236,10 +236,10 @@ test("Consumer charges a small view of a large wire frame the wire frame", async // The padded frames fill the max buffer behind the stalled group, which moves the cursor on to them. // Charging only the one byte views, the buffer never fills and the reader waits on the stall. - expect(await within(consumer.next())).toMatchObject({ kind: "frame", frame: { timestamp: 0 } }); + expect(await within(consumer.next())).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(0) } }); expect(await within(consumer.next())).toMatchObject({ kind: "gap" }); for (let i = 0; i < 8; i++) { - expect(await within(consumer.next())).toMatchObject({ kind: "frame", frame: { timestamp: 10_000 + i } }); + expect(await within(consumer.next())).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(10_000 + i) } }); } } finally { consumer.close(); @@ -252,24 +252,24 @@ test("Consumer stamps frames the max buffer held back with when they landed, not const clock = new Manual(); const installed = clock.install(); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, // One group's overhead and one frame: the second frame waits in the transport until the first is read. maxBuffer: 300, }); try { const group = track.createGroup(0n); write(group, 0); - await clock.advance(Nano.fromMilli(Milli(250))); + await clock.advance(Duration.millis(250)); write(group, 10_000); group.finish(); track.finish(); // The reader is slow: nothing is read until well after both frames landed. - await clock.advance(Nano.fromMilli(Milli(750))); + await clock.advance(Duration.millis(750)); - expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: 0, arrival: 0 } }); - expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: 10_000, arrival: 250 } }); + expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(0), arrival: Instant.ZERO } }); + expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(10_000), arrival: Instant.ZERO.add(Duration.millis(250)) } }); } finally { consumer.close(); track.close(); @@ -281,9 +281,9 @@ test("Consumer expires a hole behind a full max buffer from when the group past const clock = new Manual(); const installed = clock.install(); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(500) }, + delay: { max: Duration.millis(500) }, // Two groups' overhead: group 3 waits in the transport until groups 0 and 1 are read. maxBuffer: 512, }); @@ -297,7 +297,7 @@ test("Consumer expires a hole behind a full max buffer from when the group past marker.writeFrame({ payload: new Uint8Array(), timestamp: Time.Timestamp.now() }); marker.finish(); // The reader is slow: the hole before group 3 expired before anything is read. - await clock.advance(Nano.fromMilli(Milli(1_000))); + await clock.advance(Duration.millis(1_000)); expect(await within(consumer.next())).toMatchObject({ kind: "frame", group: 0n }); expect(await within(consumer.next())).toMatchObject({ kind: "frame", group: 1n }); @@ -314,9 +314,9 @@ for (const maxBuffer of [0, 256]) { test(`Consumer moves past a stalled group with a ${maxBuffer} byte max buffer`, async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, // No more than one group's overhead: the successor is pulled anyway, so the head can be skipped. maxBuffer, }); @@ -327,9 +327,9 @@ for (const maxBuffer of [0, 256]) { write(next, 10_000); next.finish(); - expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: 0 } }); + expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(0) } }); expect(await consumer.next()).toMatchObject({ kind: "gap" }); - expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: 10_000 } }); + expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(10_000) } }); } finally { consumer.close(); track.close(); @@ -341,9 +341,9 @@ for (const maxBuffer of [0, 256]) { test("Consumer moves past a stalled backlog group below the cursor once the max buffer is full", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, // Two groups' overhead: the backlog group and the active one leave no room for the newer group. maxBuffer: 512, }); @@ -358,7 +358,7 @@ test("Consumer moves past a stalled backlog group below the cursor once the max newer.finish(); expect(await consumer.next()).toMatchObject({ kind: "gap" }); - expect(await consumer.next()).toMatchObject({ kind: "frame", group: 4n, frame: { timestamp: 40_000 } }); + expect(await consumer.next()).toMatchObject({ kind: "frame", group: 4n, frame: { timestamp: Duration.micros(40_000) } }); } finally { consumer.close(); track.close(); @@ -369,9 +369,9 @@ test("Consumer moves past a stalled backlog group below the cursor once the max test("Consumer reads what a promoted head already holds before skipping it under pressure", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, maxBuffer: 1024, }); try { @@ -385,15 +385,15 @@ test("Consumer reads what a promoted head already holds before skipping it under const later = track.createGroup(2n); const early = Time.Timestamp.now(); later.writeFrame({ - payload: encodeFrame(new Uint8Array(2_000), 20_000 as Micro), + payload: encodeFrame(new Uint8Array(2_000), Duration.micros(20_000)), timestamp: Time.Timestamp.now(), }); await flush(); - between.writeFrame({ payload: encodeFrame(PAYLOAD, 10_000 as Micro), timestamp: early }); + between.writeFrame({ payload: encodeFrame(PAYLOAD, Duration.micros(10_000)), timestamp: early }); // Group 0 is skipped, but group 1 is read once promoted rather than skipped before its task runs. expect(await consumer.next()).toMatchObject({ kind: "gap" }); - expect(await consumer.next()).toMatchObject({ kind: "frame", group: 1n, frame: { timestamp: 10_000 } }); + expect(await consumer.next()).toMatchObject({ kind: "frame", group: 1n, frame: { timestamp: Duration.micros(10_000) } }); } finally { consumer.close(); track.close(); @@ -404,7 +404,7 @@ test("Consumer reads what a promoted head already holds before skipping it under // Settle `promise` within a second, so a reader that hangs fails the test instead of timing it out. async function within(promise: Promise): Promise { try { - return await timeout(Nano.fromMilli(Milli(1_000)), promise); + return await timeout(Duration.millis(1_000), promise); } catch (error) { if (error instanceof Elapsed) throw new Error("the reader hung"); throw error; @@ -414,9 +414,9 @@ async function within(promise: Promise): Promise { test("Consumer raises a malformed frame in a head promoted under pressure", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, maxBuffer: 1024, }); try { @@ -429,7 +429,7 @@ test("Consumer raises a malformed frame in a head promoted under pressure", asyn const later = track.createGroup(2n); const early = Time.Timestamp.now(); later.writeFrame({ - payload: encodeFrame(new Uint8Array(2_000), 20_000 as Micro), + payload: encodeFrame(new Uint8Array(2_000), Duration.micros(20_000)), timestamp: Time.Timestamp.now(), }); await flush(); @@ -447,9 +447,9 @@ test("Consumer raises a malformed frame in a head promoted under pressure", asyn test("Consumer raises a malformed group an age skip passes after the track finished", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(500) }, + delay: { max: Duration.millis(500) }, }); try { const first = track.createGroup(0n); @@ -478,9 +478,9 @@ test("Consumer raises a malformed group an age skip passes after the track finis test("Consumer reads a finished marker group's end before skipping under pressure", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, maxBuffer: 1024, }); try { @@ -493,7 +493,7 @@ test("Consumer reads a finished marker group's end before skipping under pressur const later = track.createGroup(2n); const early = Time.Timestamp.now(); later.writeFrame({ - payload: encodeFrame(new Uint8Array(2_000), 20_000 as Micro), + payload: encodeFrame(new Uint8Array(2_000), Duration.micros(20_000)), timestamp: Time.Timestamp.now(), }); await flush(); @@ -503,7 +503,7 @@ test("Consumer reads a finished marker group's end before skipping under pressur // Group 0 is skipped, and group 1 declares its end before group 2 is read. expect(await within(consumer.next())).toMatchObject({ kind: "gap" }); expect(await within(consumer.next())).toMatchObject({ kind: "end", group: 1n }); - expect(await within(consumer.next())).toMatchObject({ kind: "frame", group: 2n, frame: { timestamp: 20_000 } }); + expect(await within(consumer.next())).toMatchObject({ kind: "frame", group: 2n, frame: { timestamp: Duration.micros(20_000) } }); } finally { consumer.close(); track.close(); @@ -514,9 +514,9 @@ test("Consumer reads a finished marker group's end before skipping under pressur test("Consumer reads a group whose frame fails to read as cut short while the reader waits", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(5_000) }, + delay: { max: Duration.millis(5_000) }, }); try { const stalled = track.createGroup(0n); @@ -530,7 +530,7 @@ test("Consumer reads a group whose frame fails to read as cut short while the re // slice that will not inflate does. The read that takes it fails the group. const pending = within(consumer.next()); await flush(); - const payload = encodeFrame(PAYLOAD, 5_000 as Micro); + const payload = encodeFrame(PAYLOAD, Duration.micros(5_000)); let armed = false; stalled.writeFrame({ get payload() { @@ -542,7 +542,7 @@ test("Consumer reads a group whose frame fails to read as cut short while the re armed = true; expect(await pending).toMatchObject({ kind: "gap" }); - expect(await within(consumer.next())).toMatchObject({ kind: "frame", group: 1n, frame: { timestamp: 10_000 } }); + expect(await within(consumer.next())).toMatchObject({ kind: "frame", group: 1n, frame: { timestamp: Duration.micros(10_000) } }); } finally { consumer.close(); track.close(); diff --git a/js/hang/src/container/consumer.holes.test.ts b/js/hang/src/container/consumer.holes.test.ts index fd68adc5d6c..37b4a8184ae 100644 --- a/js/hang/src/container/consumer.holes.test.ts +++ b/js/hang/src/container/consumer.holes.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Manual, Micro, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { Time, Track } from "@moq/net"; import { Consumer, type Read } from "./consumer.ts"; import { encodeFrame, Format } from "./legacy.ts"; @@ -10,9 +10,9 @@ test.each([0, 100])("a sequence hole before a paused data marker expires at %sms const clock = new Manual(); const installed = clock.install(); const track = new Track.Producer("data"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(budget) }, + delay: { max: Duration.millis(budget) }, }); const results: Read[] = []; const reading = (async () => { @@ -24,7 +24,7 @@ test.each([0, 100])("a sequence hole before a paused data marker expires at %sms })(); try { const first = track.createGroup(0n); - first.writeFrame({ payload: encodeFrame(new Uint8Array([1]), Micro(10_000)), timestamp: Time.Timestamp.now() }); + first.writeFrame({ payload: encodeFrame(new Uint8Array([1]), Duration.micros(10_000)), timestamp: Time.Timestamp.now() }); first.finish(); await flush(); expect(results).toHaveLength(1); @@ -34,13 +34,13 @@ test.each([0, 100])("a sequence hole before a paused data marker expires at %sms await flush(); if (budget > 0) { expect(results).toHaveLength(1); - await clock.advance(Nano.fromMilli(Milli(budget - 1))); + await clock.advance(Duration.millis(budget - 1)); expect(results).toHaveLength(1); - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); } expect(results.slice(1)).toEqual([ - { kind: "gap", timestamp: Micro(10_000), duration: Micro.zero }, - { kind: "end", group: 2n, end: Micro(10_000) }, + { kind: "gap", timestamp: Duration.micros(10_000), duration: Duration.ZERO }, + { kind: "end", group: 2n, end: Duration.micros(10_000) }, ]); } finally { consumer.close(); @@ -58,9 +58,9 @@ test("a filled hole cancels its timer and the next hole gets a fresh budget", as const clock = new Manual(); const installed = clock.install(); const track = new Track.Producer("data"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(100) }, + delay: { max: Duration.millis(100) }, }); const results: Read[] = []; const reading = (async () => { @@ -73,7 +73,7 @@ test("a filled hole cancels its timer and the next hole gets a fresh budget", as const write = (sequence: bigint, timestamp?: number) => { const group = track.createGroup(sequence); group.writeFrame({ - payload: timestamp === undefined ? new Uint8Array() : encodeFrame(new Uint8Array([1]), Micro(timestamp)), + payload: timestamp === undefined ? new Uint8Array() : encodeFrame(new Uint8Array([1]), Duration.micros(timestamp)), timestamp: Time.Timestamp.fromMicros(timestamp ?? 20_000), }); group.finish(); @@ -83,18 +83,18 @@ test("a filled hole cancels its timer and the next hole gets a fresh budget", as await flush(); write(2n, 20_000); await flush(); - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); write(1n, 10_000); await flush(); expect(results.map((read) => read.kind)).toEqual(["frame", "frame", "frame"]); write(4n); await flush(); - await clock.advance(Nano.fromMilli(Milli(99))); + await clock.advance(Duration.millis(99)); expect(results).toHaveLength(3); - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); expect(results.slice(3)).toEqual([ - { kind: "gap", timestamp: Micro(20_000), duration: Micro.zero }, - { kind: "end", group: 4n, end: Micro(20_000) }, + { kind: "gap", timestamp: Duration.micros(20_000), duration: Duration.ZERO }, + { kind: "end", group: 4n, end: Duration.micros(20_000) }, ]); } finally { consumer.close(); @@ -112,9 +112,9 @@ test("the holes a stalled source left behind share one budget", async () => { const clock = new Manual(); const installed = clock.install(); const track = new Track.Producer("data"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(100) }, + delay: { max: Duration.millis(100) }, }); const results: Read[] = []; const reading = (async () => { @@ -127,7 +127,7 @@ test("the holes a stalled source left behind share one budget", async () => { const write = (sequence: bigint) => { const group = track.createGroup(sequence); group.writeFrame({ - payload: encodeFrame(new Uint8Array([1]), Micro(Number(sequence) * 10_000)), + payload: encodeFrame(new Uint8Array([1]), Duration.micros(Number(sequence) * 10_000)), timestamp: Time.Timestamp.fromMicros(Number(sequence) * 10_000), }); group.finish(); @@ -138,7 +138,7 @@ test("the holes a stalled source left behind share one budget", async () => { for (const sequence of [2n, 4n, 6n]) write(sequence); await flush(); expect(results).toHaveLength(1); - await clock.advance(Nano.fromMilli(Milli(100))); + await clock.advance(Duration.millis(100)); expect(results.map((read) => read.kind)).toEqual(["frame", "gap", "frame", "gap", "frame", "gap", "frame"]); } finally { consumer.close(); @@ -156,9 +156,9 @@ test("a hole is late from the earliest arrival past it", async () => { const clock = new Manual(); const installed = clock.install(); const track = new Track.Producer("data"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(100) }, + delay: { max: Duration.millis(100) }, }); const results: Read[] = []; const reading = (async () => { @@ -171,7 +171,7 @@ test("a hole is late from the earliest arrival past it", async () => { const write = (sequence: bigint) => { const group = track.createGroup(sequence); group.writeFrame({ - payload: encodeFrame(new Uint8Array([1]), Micro(Number(sequence) * 10_000)), + payload: encodeFrame(new Uint8Array([1]), Duration.micros(Number(sequence) * 10_000)), timestamp: Time.Timestamp.fromMicros(Number(sequence) * 10_000), }); group.finish(); @@ -181,11 +181,11 @@ test("a hole is late from the earliest arrival past it", async () => { await flush(); write(4n); await flush(); - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); write(2n); await flush(); expect(results).toHaveLength(1); - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); expect(results.map((read) => read.kind)).toEqual(["frame", "gap", "frame", "gap", "frame"]); } finally { consumer.close(); @@ -212,17 +212,17 @@ test("a hole in a drained backlog is late from the earliest arrival past it, not group.finish(); }; const first = track.createGroup(0n); - first.writeFrame({ payload: encodeFrame(new Uint8Array([1]), Micro(0)), timestamp: Time.Timestamp.fromMicros(0) }); + first.writeFrame({ payload: encodeFrame(new Uint8Array([1]), Duration.micros(0)), timestamp: Time.Timestamp.fromMicros(0) }); first.finish(); marker(5n); - await clock.advance(Nano.fromMilli(Milli(900))); + await clock.advance(Duration.millis(900)); marker(3n); - await clock.advance(Nano.fromMilli(Milli(100))); + await clock.advance(Duration.millis(100)); // Joined now, the backlog drains in sequence order: group 3 before group 5, which landed first. - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(500) }, + delay: { max: Duration.millis(500) }, }); const results: Read[] = []; const reading = (async () => { @@ -260,9 +260,9 @@ test.each([true, false])("the head after a declared end is waited for (arrives: const clock = new Manual(); const installed = clock.install(); const track = new Track.Producer("audio"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("audio"), - delay: { max: Milli(300) }, + delay: { max: Duration.millis(300) }, }); const results: Read[] = []; const reading = (async () => { @@ -276,8 +276,8 @@ test.each([true, false])("the head after a declared end is waited for (arrives: const group = track.createGroup(sequence); for (const [timestamp, payload = new Uint8Array([1])] of frames) { group.writeFrame({ - payload: encodeFrame(payload, Micro(timestamp)), - timestamp: Time.Timestamp.fromMicros(Micro(timestamp)), + payload: encodeFrame(payload, Duration.micros(timestamp)), + timestamp: Time.Timestamp.fromMicros(timestamp), }); } group.finish(); @@ -285,17 +285,17 @@ test.each([true, false])("the head after a declared end is waited for (arrives: const frame = (group: bigint, timestamp: number) => ({ kind: "frame" as const, group, - frame: expect.objectContaining({ timestamp }), + frame: expect.objectContaining({ timestamp: Duration.micros(timestamp) }), }); try { write(0n, [0]); // The end, then the stopped encoder's final packet, as a native publisher writes them. write(1n, [60_000, new Uint8Array()], [40_000]); await flush(); - expect(results).toEqual([frame(0n, 0), { kind: "end", group: 1n, end: Micro(60_000) }, frame(1n, 40_000)]); + expect(results).toEqual([frame(0n, 0), { kind: "end", group: 1n, end: Duration.micros(60_000) }, frame(1n, 40_000)]); write(3n, [60_060_000]); await flush(); - await clock.advance(Nano.fromMilli(Milli(299))); + await clock.advance(Duration.millis(299)); expect(results).toHaveLength(3); if (arrives) { write(2n, [60_000_000]); @@ -305,14 +305,14 @@ test.each([true, false])("the head after a declared end is waited for (arrives: write(5n, [61_000_000], [61_300_000]); await flush(); expect(results.slice(5)).toEqual([ - { kind: "gap", timestamp: Micro(60_060_000), duration: Micro(940_000) }, + { kind: "gap", timestamp: Duration.micros(60_060_000), duration: Duration.micros(940_000) }, frame(5n, 61_000_000), frame(5n, 61_300_000), ]); } else { - await clock.advance(Nano.fromMilli(Milli(1))); + await clock.advance(Duration.millis(1)); expect(results.slice(3)).toEqual([ - { kind: "gap", timestamp: Micro(60_000), duration: Micro(60_000_000) }, + { kind: "gap", timestamp: Duration.micros(60_000), duration: Duration.micros(60_000_000) }, frame(3n, 60_060_000), ]); } @@ -336,9 +336,9 @@ test("a newest-first flush past a hole delivers the groups landing behind its ne const clock = new Manual(); const installed = clock.install(); const track = new Track.Producer("audio"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("audio"), - delay: { max: Milli(80) }, + delay: { max: Duration.millis(80) }, }); const results: Read[] = []; const reading = (async () => { @@ -352,7 +352,7 @@ test("a newest-first flush past a hole delivers the groups landing behind its ne const sent = Time.Timestamp.now(); const write = (sequence: number) => { const group = track.createGroup(BigInt(sequence)); - const timestamp = Micro(sequence * 20_000); + const timestamp = Duration.micros(sequence * 20_000); group.writeFrame({ payload: encodeFrame(new Uint8Array([1]), timestamp), timestamp: sent }); group.finish(); }; @@ -367,7 +367,7 @@ test("a newest-first flush past a hole delivers the groups landing behind its ne [0, 1, 2, 3, 4, 5, 6, 7].map((sequence) => ({ kind: "frame", group: BigInt(sequence), - frame: expect.objectContaining({ timestamp: Micro(sequence * 20_000) }), + frame: expect.objectContaining({ timestamp: Duration.micros(sequence * 20_000) }), })), ); } finally { diff --git a/js/hang/src/container/consumer.nonsequential.test.ts b/js/hang/src/container/consumer.nonsequential.test.ts index c0240f07f64..7fed8b3bcbd 100644 --- a/js/hang/src/container/consumer.nonsequential.test.ts +++ b/js/hang/src/container/consumer.nonsequential.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, expect, test } from "bun:test"; -import { type Installed, Manual, type Micro, Milli, Nano } from "@moq/clock"; +import { Duration, type Installed, Manual } from "@moq/clock"; import { type Group, Time, Track, Varint } from "@moq/net"; import { Consumer } from "./consumer.ts"; import { Format as LegacyFormat } from "./legacy.ts"; @@ -19,7 +19,7 @@ afterEach(() => { /** Flush the consumer's readers without moving time, then return what `read` settled with, or "pending". */ async function poll(read: Promise): Promise { - const flushed = clock.advance(Nano.zero); + const flushed = clock.advance(Duration.ZERO); try { return await Promise.race([read, flushed.then(() => "pending" as const)]); } finally { @@ -35,7 +35,7 @@ async function nextFrame(consumer: Consumer) { } } -function encodeLegacyFrame(timestamp: Micro, payload: Uint8Array): Uint8Array { +function encodeLegacyFrame(timestamp: number, payload: Uint8Array): Uint8Array { const tsBytes = Varint.encode(timestamp); const data = new Uint8Array(tsBytes.byteLength + payload.byteLength); data.set(tsBytes, 0); @@ -58,13 +58,13 @@ test("Consumer waits on a non-sequential hang group because it has no per-frame const track = new Track.Producer("test"); const consumer = new Consumer(track.subscribe(), { format: new LegacyFormat("data"), - delay: { max: 5000 as Milli }, + delay: { max: Duration.millis(5000) }, }); // Group A at a large sequence, completed so the cursor advances past it. const a = track.createGroup(1_000_000n); a.writeFrame({ - payload: encodeLegacyFrame(0 as Micro, new Uint8Array([0x01])), + payload: encodeLegacyFrame(0, new Uint8Array([0x01])), timestamp: Time.Timestamp.now(), }); a.finish(); @@ -81,13 +81,13 @@ test("Consumer waits on a non-sequential hang group because it has no per-frame // could still be coming. We cannot tell, so B must NOT surface yet. const b = track.createGroup(1_090_000n); b.writeFrame({ - payload: encodeLegacyFrame(1_000_000 as Micro, new Uint8Array([0x02])), + payload: encodeLegacyFrame(1_000_000, new Uint8Array([0x02])), timestamp: Time.Timestamp.now(), }); // Within the max delay budget (5s), the parked next() stays parked: no duration means no proof of // contiguity, so the consumer waits instead of eagerly delivering across the gap. - await clock.advance(Nano.fromMilli(Milli(4_999))); + await clock.advance(Duration.millis(4_999)); expect(await poll(pending)).toBe("pending"); consumer.close(); @@ -100,12 +100,12 @@ test("Consumer reads on without a gap past a group it skipped", async () => { const track = new Track.Producer("test"); const consumer = new Consumer(track.subscribe(), { format: new LegacyFormat("audio"), - delay: { max: 500 as Milli }, + delay: { max: Duration.millis(500) }, }); const write = (group: Group.Producer, timestamps: number[]) => { for (const timestamp of timestamps) { group.writeFrame({ - payload: encodeLegacyFrame(timestamp as Micro, new Uint8Array([0x01])), + payload: encodeLegacyFrame(timestamp, new Uint8Array([0x01])), timestamp: Time.Timestamp.now(), }); } @@ -120,12 +120,12 @@ test("Consumer reads on without a gap past a group it skipped", async () => { // frame and leaves only the skipped group's end to show the timeline goes on. first.finish(); const empty = track.createGroup(1n); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); const last = track.createGroup(20n); write(last, [400_000, 1_000_000]); last.finish(); empty.finish(); - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); const next = await poll(consumer.next()); expect(next).toMatchObject({ kind: "frame", group: 20n }); diff --git a/js/hang/src/container/consumer.outoforder.test.ts b/js/hang/src/container/consumer.outoforder.test.ts index 6146646b002..f5acd8de43c 100644 --- a/js/hang/src/container/consumer.outoforder.test.ts +++ b/js/hang/src/container/consumer.outoforder.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, expect, test } from "bun:test"; -import { type Installed, Manual, Micro, Milli, Nano } from "@moq/clock"; +import { Duration, type Installed, Manual } from "@moq/clock"; import { type Group, Time, Track, Varint } from "@moq/net"; import { Consumer } from "./consumer.ts"; import { Format as LegacyFormat } from "./legacy.ts"; @@ -19,7 +19,7 @@ afterEach(() => { /** Flush the consumer's readers without moving time, then return what `read` settled with, or "pending". */ async function poll(read: Promise): Promise { - const flushed = clock.advance(Nano.zero); + const flushed = clock.advance(Duration.ZERO); try { return await Promise.race([read, flushed.then(() => "pending" as const)]); } finally { @@ -35,7 +35,7 @@ async function nextFrame(consumer: Consumer) { } } -function encodeLegacyFrame(timestamp: Micro, payload: Uint8Array): Uint8Array { +function encodeLegacyFrame(timestamp: number, payload: Uint8Array): Uint8Array { const tsBytes = Varint.encode(timestamp); const data = new Uint8Array(tsBytes.byteLength + payload.byteLength); data.set(tsBytes, 0); @@ -46,7 +46,7 @@ function encodeLegacyFrame(timestamp: Micro, payload: Uint8Array): Uint8Array { /** Write one frame into an open group: `millis` on the timeline, tagged `tag`. */ function publishFrame(group: Group.Producer, millis: number, tag: number) { group.writeFrame({ - payload: encodeLegacyFrame(Micro.fromMilli(millis as Milli), new Uint8Array([tag])), + payload: encodeLegacyFrame(millis * 1000, new Uint8Array([tag])), timestamp: Time.Timestamp.fromMillis(millis), }); } @@ -75,16 +75,16 @@ async function drain(consumer: Consumer): Promise<[bigint, number | undefined][] // the budget. A group below that floor is never delivered and adds no gap. Mirrors Rust's // `startup_at_the_publishers_start_over_a_newer_first_arrival`. test("the head of the window arriving after the live edge is delivered first", async () => { - const track = new Track.Producer("test").accept({ timescale: Time.Timescale.MILLI, maxAge: Milli(30_000) }); + const track = new Track.Producer("test").accept({ timescale: Time.Timescale.MILLI, maxAge: Duration.millis(30_000) }); const consumer = new Consumer( - track.subscribe({ delay: { max: Milli(5000) }, ranges: [{ start: { absolute: 1n } }] }), - { format: new LegacyFormat("data"), delay: { max: 5000 as Milli } }, + track.subscribe({ delay: { max: Duration.millis(5000) }, ranges: [{ start: { absolute: 1n } }] }), + { format: new LegacyFormat("data"), delay: { max: Duration.millis(5000) } }, ); // The live edge lands first, and delivery waits for the floor rather than starting there. publish(track, 3n, 30); const waiting = consumer.next(); - await clock.advance(Nano.fromMilli(Milli(4_999))); + await clock.advance(Duration.millis(4_999)); expect(await poll(waiting)).toBe("pending"); // The window's head follows, and a reordered group below the floor with it. @@ -106,10 +106,10 @@ test("the head of the window arriving after the live edge is delivered first", a // loop consumes faster than the network delivers). Removing it at that instant silently truncates // its tail, so removal must wait for the group to finish. test("a head group still downloading is not truncated", async () => { - const track = new Track.Producer("test").accept({ timescale: Time.Timescale.MILLI, maxAge: Milli(30_000) }); + const track = new Track.Producer("test").accept({ timescale: Time.Timescale.MILLI, maxAge: Duration.millis(30_000) }); const consumer = new Consumer( - track.subscribe({ delay: { max: Milli(5000) }, ranges: [{ start: { absolute: 1n } }] }), - { format: new LegacyFormat("data"), delay: { max: 5000 as Milli } }, + track.subscribe({ delay: { max: Duration.millis(5000) }, ranges: [{ start: { absolute: 1n } }] }), + { format: new LegacyFormat("data"), delay: { max: Duration.millis(5000) } }, ); // The live edge group arrives first (still open), and the head after it, one frame at a time. @@ -141,13 +141,13 @@ test("a head group still downloading is not truncated", async () => { // budget, or forever on an open track, for groups it never gets. Mirrors Rust's // `an_excluded_gap_between_ranges_does_not_stall`. test("an excluded gap between ranges does not stall", async () => { - const track = new Track.Producer("test").accept({ timescale: Time.Timescale.MILLI, maxAge: Milli(30_000) }); + const track = new Track.Producer("test").accept({ timescale: Time.Timescale.MILLI, maxAge: Duration.millis(30_000) }); const consumer = new Consumer( track.subscribe({ - delay: { max: Milli(10_000) }, + delay: { max: Duration.millis(10_000) }, ranges: [{ start: { absolute: 0n }, end: { absolute: 1n } }, { start: { absolute: 10n } }], }), - { format: new LegacyFormat("data"), delay: { max: 10_000 as Milli } }, + { format: new LegacyFormat("data"), delay: { max: Duration.millis(10_000) } }, ); for (const sequence of [0n, 5n, 10n]) publish(track, sequence, Number(sequence) * 100); @@ -162,13 +162,13 @@ test("an excluded gap between ranges does not stall", async () => { // which counts a newest group that held no frame yet, rather than wait under the budget for a group // below it that never comes. Mirrors Rust's `a_resolved_relative_floor_rises_to_the_publishers_start`. test("a resolved relative floor rises to the publisher's start", async () => { - const track = new Track.Producer("test").accept({ timescale: Time.Timescale.MILLI, maxAge: Milli(30_000) }); + const track = new Track.Producer("test").accept({ timescale: Time.Timescale.MILLI, maxAge: Duration.millis(30_000) }); for (const sequence of [0n, 1n, 2n, 3n, 4n]) publish(track, sequence, Number(sequence) * 100); - const subscriber = track.subscribe({ delay: { max: Milli(10_000) }, ranges: [{ start: { relative: 0n } }] }); + const subscriber = track.subscribe({ delay: { max: Duration.millis(10_000) }, ranges: [{ start: { relative: 0n } }] }); expect(subscriber.floor()).toBe(4n); // A session declares the publisher's start; a local track has none, so stand in for it. subscriber.start = async () => 5n; - const consumer = new Consumer(subscriber, { format: new LegacyFormat("data"), delay: { max: 10_000 as Milli } }); + const consumer = new Consumer(subscriber, { format: new LegacyFormat("data"), delay: { max: Duration.millis(10_000) } }); publish(track, 5n, 500); expect(await drain(consumer)).toEqual([[5n, 5]]); diff --git a/js/hang/src/container/consumer.rewind.test.ts b/js/hang/src/container/consumer.rewind.test.ts index a22d310bbe7..dbd8b143254 100644 --- a/js/hang/src/container/consumer.rewind.test.ts +++ b/js/hang/src/container/consumer.rewind.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, expect, test } from "bun:test"; -import { type Installed, Manual, Micro, Milli, Nano } from "@moq/clock"; +import { Duration, type Installed, Manual } from "@moq/clock"; import { Time, Track } from "@moq/net"; import { Consumer } from "./consumer"; import { encodeFrame, Format, Producer } from "./legacy"; @@ -8,16 +8,16 @@ import { encodeFrame, Format, Producer } from "./legacy"; let installed: Installed; beforeEach(() => { const clock = new Manual(); - clock.jump(Nano.fromMilli(Milli(200))); + clock.jump(Duration.millis(200)); installed = clock.install(); }); afterEach(() => installed.close()); function setup() { const track = new Track.Producer("rewind"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("video"), - delay: { max: Milli(30_000) }, + delay: { max: Duration.millis(30_000) }, }); return { track, consumer }; } @@ -26,14 +26,14 @@ function group(track: Track.Producer, timestamps: number[], end?: number) { const group = track.appendGroup(); for (const timestamp of timestamps) { group.writeFrame({ - timestamp: Time.Timestamp.fromMicros(Micro(timestamp)), - payload: encodeFrame(new Uint8Array([1]), Micro(timestamp)), + timestamp: Time.Timestamp.fromMicros(timestamp), + payload: encodeFrame(new Uint8Array([1]), Duration.micros(timestamp)), }); } if (end !== undefined) { group.writeFrame({ - timestamp: Time.Timestamp.fromMicros(Micro(end)), - payload: encodeFrame(new Uint8Array(), Micro(end)), + timestamp: Time.Timestamp.fromMicros(end), + payload: encodeFrame(new Uint8Array(), Duration.micros(end)), }); } group.finish(); @@ -52,10 +52,10 @@ test("Consumer accepts a resuming keyframe before the estimated group end", asyn // A cut estimates the final 33ms frame's end at 66ms. Playback consumes that // marker before the encoder resumes at 50ms, so the end cannot be a floor. group(track, [0, 33_000], 66_000); - expect((await frame(consumer))?.frame?.timestamp).toBe(Micro(0)); - expect((await frame(consumer))?.frame?.timestamp).toBe(Micro(33_000)); + expect((await frame(consumer))?.frame?.timestamp.asMicros()).toBe(0); + expect((await frame(consumer))?.frame?.timestamp.asMicros()).toBe(33_000); group(track, [50_000]); - expect((await frame(consumer))?.frame?.timestamp).toBe(Micro(50_000)); + expect((await frame(consumer))?.frame?.timestamp.asMicros()).toBe(50_000); } finally { consumer.close(); track.finish(); @@ -68,11 +68,11 @@ for (const start of [16_000, 0]) { const { track, consumer } = setup(); const producer = new Producer(track, new Format("video")); try { - producer.encode(new Uint8Array([1]), Micro(0), true); - producer.encode(new Uint8Array([1]), Micro(33_000), false); + producer.encode(new Uint8Array([1]), Duration.micros(0), true); + producer.encode(new Uint8Array([1]), Duration.micros(33_000), false); expect((await frame(consumer))?.group).toBe(0n); await frame(consumer); - producer.encode(new Uint8Array([1]), Micro(start), true); + producer.encode(new Uint8Array([1]), Duration.micros(start), true); expect((await frame(consumer))?.group).toBe(1n); } finally { consumer.close(); @@ -88,8 +88,8 @@ test("Consumer accepts leading pictures below the previous group's content", asy await frame(consumer); await frame(consumer); group(track, [200_000, 150_000]); - expect((await frame(consumer))?.frame?.timestamp).toBe(Micro(200_000)); - expect((await frame(consumer))?.frame?.timestamp).toBe(Micro(150_000)); + expect((await frame(consumer))?.frame?.timestamp.asMicros()).toBe(200_000); + expect((await frame(consumer))?.frame?.timestamp.asMicros()).toBe(150_000); } finally { consumer.close(); track.finish(); @@ -104,13 +104,13 @@ test("Consumer rejects a later frame below the previous group start", async () = await frame(consumer); const current = track.appendGroup(); current.writeFrame({ - timestamp: Time.Timestamp.fromMicros(Micro(200_000)), - payload: encodeFrame(new Uint8Array([1]), Micro(200_000)), + timestamp: Time.Timestamp.fromMicros(200_000), + payload: encodeFrame(new Uint8Array([1]), Duration.micros(200_000)), }); await frame(consumer); current.writeFrame({ - timestamp: Time.Timestamp.fromMicros(Micro(99_000)), - payload: encodeFrame(new Uint8Array([1]), Micro(99_000)), + timestamp: Time.Timestamp.fromMicros(99_000), + payload: encodeFrame(new Uint8Array([1]), Duration.micros(99_000)), }); await expect(frame(consumer)).rejects.toThrow("below"); } finally { @@ -124,13 +124,13 @@ test("Producer refuses a rewind before closing the current group", () => { const track = new Track.Producer("rewind"); const producer = new Producer(track, new Format("video")); try { - producer.encode(new Uint8Array([1]), Micro(100_000), true); - expect(() => producer.encode(new Uint8Array([1]), Micro(99_000), true)).toThrow("below"); + producer.encode(new Uint8Array([1]), Duration.micros(100_000), true); + expect(() => producer.encode(new Uint8Array([1]), Duration.micros(99_000), true)).toThrow("below"); // The refused keyframe must not close the group and strand its delta frames. - producer.encode(new Uint8Array([1]), Micro(110_000), false); - producer.encode(new Uint8Array([1]), Micro(200_000), true); - producer.encode(new Uint8Array([1]), Micro(150_000), false); - expect(() => producer.encode(new Uint8Array([1]), Micro(99_000), false)).toThrow("below"); + producer.encode(new Uint8Array([1]), Duration.micros(110_000), false); + producer.encode(new Uint8Array([1]), Duration.micros(200_000), true); + producer.encode(new Uint8Array([1]), Duration.micros(150_000), false); + expect(() => producer.encode(new Uint8Array([1]), Duration.micros(99_000), false)).toThrow("below"); } finally { producer.close(); } diff --git a/js/hang/src/container/consumer.skips.test.ts b/js/hang/src/container/consumer.skips.test.ts index b5f61390881..9b9e6e1b253 100644 --- a/js/hang/src/container/consumer.skips.test.ts +++ b/js/hang/src/container/consumer.skips.test.ts @@ -1,5 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { Time, Track, Varint } from "@moq/net"; import { Signal } from "@moq/signals"; import { Consumer } from "./consumer.ts"; @@ -11,8 +11,8 @@ for (const count of [1, 16, 256]) { test(`Consumer summarizes ${count} skipped groups once per catch-up`, async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("tone"); - const delay = new Signal({ max: Milli(30_000) }); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const delay = new Signal({ max: Duration.millis(30_000) }); + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), delay, }); @@ -22,19 +22,19 @@ for (const count of [1, 16, 256]) { return group; }; const buffered = async (timestamp: number) => { - while (consumer.buffered.peek().at(-1)?.end !== timestamp) await consumer.buffered.changed(); + while (consumer.buffered.peek().at(-1)?.end.asMillis() !== timestamp) await consumer.buffered.changed(); }; try { // Sparse sequence numbers make the count differ from the sequence range. for (let i = 0; i < count; i++) write(BigInt(i) * 2n, i * 1000); await buffered(count - 1); expect(warn).not.toHaveBeenCalled(); - delay.set({ max: Milli.zero }); + delay.set({ max: Duration.ZERO }); const newest = write(BigInt(count) * 2n, count * 1000); await buffered(count); expect(warn).toHaveBeenCalledTimes(1); expect(warn).toHaveBeenLastCalledWith(`skipping slow groups: track=tone 0 -> ${count * 2} count=${count}`); - expect(consumer.buffered.peek()[0]?.start).toBe(Milli(count)); + expect(consumer.buffered.peek()[0]?.start).toEqual(Duration.millis(count)); // The retained group is still delivered, and another catch-up reports separately. expect(await consumer.next()).toMatchObject({ kind: "frame", group: BigInt(count) * 2n }); newest.writeFrame({ payload: Varint.encode(count * 1000), timestamp: Time.Timestamp.now() }); @@ -61,9 +61,9 @@ for (const open of [true, false]) { test(`a buffered backlog starts within the budget (sixth group ${open ? "open" : "finished"})`, async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("backlog"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(1500) }, + delay: { max: Duration.millis(1500) }, }); const frame = (micros: number) => ({ payload: Varint.encode(micros), timestamp: Time.Timestamp.now() }); try { @@ -75,13 +75,13 @@ for (const open of [true, false]) { const last = track.createGroup(5n); last.writeFrame(frame(5_000_000)); if (!open) last.finish(); - while (consumer.buffered.peek().at(-1)?.end !== 5000) await consumer.buffered.changed(); + while (consumer.buffered.peek().at(-1)?.end.asMillis() !== 5000) await consumer.buffered.changed(); const read: number[] = []; for (let i = 0; i < 11; i++) { const next = await consumer.next(); if (next?.kind !== "frame") throw new Error(`unexpected read: ${JSON.stringify(next)}`); - read.push(next.frame.timestamp); + read.push(next.frame.timestamp.asMicros()); } const expected = [...Array.from({ length: 10 }, (_, f) => 4_000_000 + f * 100_000), 5_000_000]; expect(read).toEqual(expected); @@ -101,9 +101,9 @@ for (const open of [true, false]) { test("a backlog start waits on a successor without frames", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("backlog"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(1500) }, + delay: { max: Duration.millis(1500) }, }); const frame = (micros: number) => ({ payload: Varint.encode(micros), timestamp: Time.Timestamp.now() }); const frames = (g: bigint) => Array.from({ length: 10 }, (_, f) => Number(g) * 1_000_000 + f * 100_000); @@ -112,7 +112,7 @@ test("a backlog start waits on a successor without frames", async () => { for (let i = 0; i < n; i++) { const next = await consumer.next(); if (next?.kind !== "frame") throw new Error(`unexpected read: ${JSON.stringify(next)}`); - read.push(next.frame.timestamp); + read.push(next.frame.timestamp.asMicros()); } }; try { @@ -127,7 +127,7 @@ test("a backlog start waits on a successor without frames", async () => { const last = track.createGroup(5n); last.writeFrame(frame(5_000_000)); last.finish(); - while (consumer.buffered.peek().at(-1)?.end !== 5000) await consumer.buffered.changed(); + while (consumer.buffered.peek().at(-1)?.end.asMillis() !== 5000) await consumer.buffered.changed(); await readN(10); for (const micros of frames(4n)) fifth.writeFrame({ payload: Varint.encode(micros), timestamp: sent }); @@ -145,8 +145,8 @@ test("a backlog start waits on a successor without frames", async () => { test("Consumer measures each skip's span over every group left, not just the new oldest", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("tone"); - const delay = new Signal({ max: Milli(30_000) }); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const delay = new Signal({ max: Duration.millis(30_000) }); + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), delay, }); @@ -155,7 +155,7 @@ test("Consumer measures each skip's span over every group left, not just the new group.writeFrame({ payload: Varint.encode(timestamp), timestamp: Time.Timestamp.now() }); }; const buffered = async (timestamp: number) => { - while (consumer.buffered.peek().at(-1)?.end !== timestamp) await consumer.buffered.changed(); + while (consumer.buffered.peek().at(-1)?.end.asMillis() !== timestamp) await consumer.buffered.changed(); }; try { // Group 2 starts below group 1, so the span after skipping group 0 still reaches back to it. @@ -169,13 +169,13 @@ test("Consumer measures each skip's span over every group left, not just the new await buffered(12); // Before the first read, the span alone ages a group out: once reading began, its successor's // start bounds it instead, which the span always reaches past. - delay.set({ max: Milli(5) }); + delay.set({ max: Duration.millis(5) }); write(4n, 13_000); await buffered(13); expect(warn).toHaveBeenLastCalledWith("skipping slow groups: track=tone 0 -> 3 count=3"); expect(consumer.buffered.peek()).toEqual([ - { start: Milli(12), end: Milli(12) }, - { start: Milli(13), end: Milli(13) }, + { start: Duration.millis(12), end: Duration.millis(12) }, + { start: Duration.millis(13), end: Duration.millis(13) }, ]); // Joining mid-track is not a gap: nothing was read before it. expect(await consumer.next()).toMatchObject({ kind: "frame", group: 3n }); @@ -193,9 +193,9 @@ test("Consumer measures each skip's span over every group left, not just the new test("a blocking group is kept until its successor starts a budget behind the newest", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("tone"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(150) }, + delay: { max: Duration.millis(150) }, }); const sent = Time.Timestamp.now(); const write = (sequence: bigint, timestamp: number) => { @@ -232,9 +232,9 @@ test("a blocking group is kept until its successor starts a budget behind the ne test("a blocking group ages out past an unstamped successor", async () => { const warn = spyOn(console, "warn").mockImplementation(() => {}); const track = new Track.Producer("tone"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("data"), - delay: { max: Milli(150) }, + delay: { max: Duration.millis(150) }, }); const sent = Time.Timestamp.now(); try { diff --git a/js/hang/src/container/consumer.startup.test.ts b/js/hang/src/container/consumer.startup.test.ts index 8b9d3935caf..1a7b486249c 100644 --- a/js/hang/src/container/consumer.startup.test.ts +++ b/js/hang/src/container/consumer.startup.test.ts @@ -1,5 +1,5 @@ import { expect, onTestFinished, spyOn, test } from "bun:test"; -import { Manual, Micro, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { type Group, Error as NetError, StreamCode, Time, Track } from "@moq/net"; import { Consumer, type Read } from "./consumer.ts"; import { encodeFrame, Format } from "./legacy.ts"; @@ -8,11 +8,11 @@ function setup(maxDelay = 100) { const clock = new Manual(); const installed = clock.install(); // Drain the in-memory readers and their continuations without moving time. - const flush = () => clock.advance(Nano.zero); + const flush = () => clock.advance(Duration.ZERO); const track = new Track.Producer("video"); - const consumer = new Consumer(track.subscribe({ delay: { max: Milli(30_000) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: Duration.millis(30_000) } }), { format: new Format("video"), - delay: { max: Milli(maxDelay) }, + delay: { max: Duration.millis(maxDelay) }, }); const results: Read[] = []; const warn = spyOn(console, "warn").mockImplementation(() => {}); @@ -40,9 +40,9 @@ function setup(maxDelay = 100) { // Each item as "gap <µs>+<µs>", "@<µs>" for a frame, or "end @<µs>". function items(results: Read[]): string[] { return results.map((read) => { - if (read.kind === "gap") return `gap ${read.timestamp}+${read.duration}`; - if (read.kind === "end") return `end ${read.group}@${read.end}`; - return `${read.group}@${read.frame.timestamp}`; + if (read.kind === "gap") return `gap ${read.timestamp.asMicros()}+${read.duration.asMicros()}`; + if (read.kind === "end") return `end ${read.group}@${read.end.asMicros()}`; + return `${read.group}@${read.frame.timestamp.asMicros()}`; }); } @@ -52,7 +52,7 @@ function frames(results: Read[]) { function write(group: Group.Producer, timestamp: number, marker = false) { group.writeFrame({ - payload: encodeFrame(marker ? new Uint8Array() : new Uint8Array([1]), Micro(timestamp)), + payload: encodeFrame(marker ? new Uint8Array() : new Uint8Array([1]), Duration.micros(timestamp)), timestamp: Time.Timestamp.now(), }); } diff --git a/js/hang/src/container/consumer.test.ts b/js/hang/src/container/consumer.test.ts index 30bf5525266..138ff0f60aa 100644 --- a/js/hang/src/container/consumer.test.ts +++ b/js/hang/src/container/consumer.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; import { readFileSync } from "node:fs"; -import { type Installed, Manual, type Micro, Milli, Nano } from "@moq/clock"; +import { Duration, type Installed, Manual } from "@moq/clock"; import { Format as LocFormat } from "@moq/loc"; import { type Group, Error as NetError, SessionCode, StreamCode, Time, Track, Varint } from "@moq/net"; import { decodeInitSegment, type InitSegment } from "../cmaf/decode.ts"; @@ -24,7 +24,7 @@ const TEST_INIT: InitSegment = { defaultSampleFlags: 0, }; -function encodeLegacyFrame(timestamp: Micro, payload: Uint8Array): Uint8Array { +function encodeLegacyFrame(timestamp: number, payload: Uint8Array): Uint8Array { const tsBytes = Varint.encode(timestamp); const data = new Uint8Array(tsBytes.byteLength + payload.byteLength); data.set(tsBytes, 0); @@ -33,13 +33,13 @@ function encodeLegacyFrame(timestamp: Micro, payload: Uint8Array): Uint8Array { } /** A LOC frame carrying only the timestamp property (0x10). */ -function encodeLocFrame(timestamp: Micro, payload: Uint8Array): Uint8Array { +function encodeLocFrame(timestamp: number, payload: Uint8Array): Uint8Array { const props = new Uint8Array([...Varint.encode(0x10), ...Varint.encode(timestamp)]); return new Uint8Array([...Varint.encode(props.byteLength), ...props, ...payload]); } /** Write each group of `[timestamp, payload]` LOC frames to `track`, then close it. */ -function writeLoc(track: Track.Producer, groups: [Micro, number[]][][]) { +function writeLoc(track: Track.Producer, groups: [number, number[]][][]) { for (const frames of groups) { const group = track.appendGroup(); for (const [timestamp, payload] of frames) { @@ -62,12 +62,12 @@ function at(ticks: number): Time.Timestamp { // Fixed cadence keeps timing-only tests independent of CMAF parsing. const timedLegacy: ContainerFormat = { decode(payload) { - return new LegacyFormat("video").decode(payload).map((frame) => ({ ...frame, duration: 33_333 as Micro })); + return new LegacyFormat("video").decode(payload).map((frame) => ({ ...frame, duration: Duration.micros(33_333) })); }, }; /** A one-byte legacy frame at the test track timestamp. */ function timedFrame(data: number, timestamp: number, _sequence: number): Group.Frame { - const payload = encodeLegacyFrame(Math.round((timestamp / TIMESCALE) * 1_000_000) as Micro, new Uint8Array([data])); + const payload = encodeLegacyFrame(Math.round((timestamp / TIMESCALE) * 1_000_000), new Uint8Array([data])); return { payload, timestamp: at(timestamp) }; } @@ -84,7 +84,7 @@ afterEach(() => { /** Let the consumer's group readers drain what's been written, without moving time. */ function flush(): Promise { - return clock.advance(Nano.zero); + return clock.advance(Duration.ZERO); } /** Flush, then return what `read` settled with, or "pending" if it is still waiting. */ @@ -102,7 +102,7 @@ async function poll(read: Promise): Promise { // These tests write every group up front and only then read, so they ask for history // rather than the live edge. function replay(track: Track.Producer): Track.Subscriber { - return track.subscribe({ delay: { max: Milli(30_000) } }); + return track.subscribe({ delay: { max: Duration.millis(30_000) } }); } // --- LegacyFormat --- @@ -110,30 +110,30 @@ function replay(track: Track.Producer): Track.Subscriber { test("LegacyFormat decodes a valid frame", () => { const format = new LegacyFormat("data"); const payload = new Uint8Array([0xde, 0xad]); - const timestamp = 1000 as Micro; + const timestamp = 1000; const frame = encodeLegacyFrame(timestamp, payload); const result = format.decode(frame); expect(result).toHaveLength(1); - expect(result[0].timestamp).toBe(timestamp); + expect(result[0].timestamp.asMicros()).toBe(timestamp); expect(result[0].payload).toEqual(payload); expect(result[0].keyframe).toBe(false); }); test("LegacyFormat preserves a duration marker", () => { const format = new LegacyFormat("video"); - const frame = encodeLegacyFrame(1000 as Micro, new Uint8Array()); + const frame = encodeLegacyFrame(1000, new Uint8Array()); const [marker] = format.decode(frame); - expect(marker.timestamp).toBe(1000 as Micro); + expect(marker.timestamp.asMicros()).toBe(1000); expect(marker.payload).toHaveLength(0); - expect(format.end(marker)).toBe(1000 as Micro); + expect(format.end(marker)).toEqual(Duration.micros(1000)); }); test("LegacyFormat always returns keyframe: false", () => { const format = new LegacyFormat("data"); - const frame = encodeLegacyFrame(0 as Micro, new Uint8Array([0x01])); + const frame = encodeLegacyFrame(0, new Uint8Array([0x01])); const [decoded] = format.decode(frame); expect(decoded.keyframe).toBe(false); @@ -141,7 +141,7 @@ test("LegacyFormat always returns keyframe: false", () => { test("LegacyFormat always returns exactly one frame", () => { const format = new LegacyFormat("data"); - const frame = encodeLegacyFrame(5000 as Micro, new Uint8Array([0x01, 0x02, 0x03])); + const frame = encodeLegacyFrame(5000, new Uint8Array([0x01, 0x02, 0x03])); const result = format.decode(frame); expect(result).toHaveLength(1); @@ -155,65 +155,65 @@ test("LegacyFormat decodes no frame from a data track's empty object and throws test("Legacy Producer refuses a group below the previous group start", () => { const track = new Track.Producer("test"); const producer = new LegacyProducer(track, new LegacyFormat("video")); - producer.encode(new Uint8Array([1]), 20_000 as Micro, true); - producer.encode(new Uint8Array([1]), 33_000 as Micro, false); - expect(() => producer.encode(new Uint8Array([1]), 16_000 as Micro, true)).toThrow("below the previous group start"); + producer.encode(new Uint8Array([1]), Duration.micros(20_000), true); + producer.encode(new Uint8Array([1]), Duration.micros(33_000), false); + expect(() => producer.encode(new Uint8Array([1]), Duration.micros(16_000), true)).toThrow("below the previous group start"); producer.close(); }); test("Legacy Producer accepts B-frames within a group", () => { const track = new Track.Producer("test"); const producer = new LegacyProducer(track, new LegacyFormat("video")); - producer.encode(new Uint8Array([1]), 0 as Micro, true); - producer.encode(new Uint8Array([1]), 66_000 as Micro, false); - producer.encode(new Uint8Array([1]), 33_000 as Micro, false); + producer.encode(new Uint8Array([1]), Duration.micros(0), true); + producer.encode(new Uint8Array([1]), Duration.micros(66_000), false); + producer.encode(new Uint8Array([1]), Duration.micros(33_000), false); producer.close(); }); test("Legacy Producer accepts open-GOP leading pictures above the previous group", () => { const track = new Track.Producer("test"); const producer = new LegacyProducer(track, new LegacyFormat("video")); - producer.encode(new Uint8Array([1]), 0 as Micro, true); - producer.encode(new Uint8Array([1]), 33_000 as Micro, false); - producer.encode(new Uint8Array([1]), 66_000 as Micro, true); - producer.encode(new Uint8Array([1]), 50_000 as Micro, false); + producer.encode(new Uint8Array([1]), Duration.micros(0), true); + producer.encode(new Uint8Array([1]), Duration.micros(33_000), false); + producer.encode(new Uint8Array([1]), Duration.micros(66_000), true); + producer.encode(new Uint8Array([1]), Duration.micros(50_000), false); producer.close(); }); test("Legacy Producer writes a duration marker at the next keyframe", async () => { const track = new Track.Producer("test"); - const subscriber = track.subscribe({ delay: { max: Milli(30_000) } }); + const subscriber = track.subscribe({ delay: { max: Duration.millis(30_000) } }); const producer = new LegacyProducer(track, new LegacyFormat("video")); - producer.encode(new Uint8Array([0xde, 0xad]), 0 as Micro, true); - producer.encode(new Uint8Array([0xbe, 0xef]), 10_000 as Micro, false); - producer.encode(new Uint8Array([0xca, 0xfe]), 20_000 as Micro, true); + producer.encode(new Uint8Array([0xde, 0xad]), Duration.micros(0), true); + producer.encode(new Uint8Array([0xbe, 0xef]), Duration.micros(10_000), false); + producer.encode(new Uint8Array([0xca, 0xfe]), Duration.micros(20_000), true); producer.close(); const group = await subscriber.recvGroup(); expect(group).toBeDefined(); - const frames: { timestamp: Micro; size: number }[] = []; + const frames: { timestamp: number; size: number }[] = []; for (;;) { const frame = await group?.readFrame(); if (!frame) break; const [timestamp, payload] = Varint.decode(frame.payload); - frames.push({ timestamp: timestamp as Micro, size: payload.byteLength }); + frames.push({ timestamp: timestamp, size: payload.byteLength }); } expect(frames).toEqual([ - { timestamp: 0 as Micro, size: 2 }, - { timestamp: 10_000 as Micro, size: 2 }, - { timestamp: 20_000 as Micro, size: 0 }, + { timestamp: 0, size: 2 }, + { timestamp: 10_000, size: 2 }, + { timestamp: 20_000, size: 0 }, ]); }); test("Legacy Producer omits a reordered group's presentation endpoint marker", async () => { const track = new Track.Producer("test"); - const subscriber = track.subscribe({ delay: { max: Milli(30_000) } }); + const subscriber = track.subscribe({ delay: { max: Duration.millis(30_000) } }); const producer = new LegacyProducer(track, new LegacyFormat("video")); for (const [index, timestamp] of [0, 120_000, 40_000, 80_000].entries()) { - producer.encode(new Uint8Array([1]), timestamp as Micro, index === 0); + producer.encode(new Uint8Array([1]), Duration.micros(timestamp), index === 0); } - producer.encode(new Uint8Array([1]), 160_000 as Micro, true); - producer.discontinuity(200_000 as Micro); + producer.encode(new Uint8Array([1]), Duration.micros(160_000), true); + producer.discontinuity(Duration.micros(200_000)); producer.close(); const group = await subscriber.recvGroup(); expect(group).toBeDefined(); @@ -233,10 +233,10 @@ test("Legacy Producer omits a reordered group's presentation endpoint marker", a test("Legacy Producer estimates the tail from the current cadence", async () => { const track = new Track.Producer("test"); - const subscriber = track.subscribe({ delay: { max: Milli(30_000) } }); + const subscriber = track.subscribe({ delay: { max: Duration.millis(30_000) } }); const producer = new LegacyProducer(track, new LegacyFormat("video")); for (const [index, timestamp] of [0, 16_000, 32_000, 65_000, 98_000].entries()) { - producer.encode(new Uint8Array([1]), timestamp as Micro, index === 0); + producer.encode(new Uint8Array([1]), Duration.micros(timestamp), index === 0); } producer.close(); const group = await subscriber.recvGroup(); @@ -253,12 +253,12 @@ test("Legacy Producer estimates the tail from the current cadence", async () => test("Legacy Producer rejects a backwards discontinuity without closing the group", async () => { const track = new Track.Producer("test"); - const subscriber = track.subscribe({ delay: { max: Milli(30_000) } }); + const subscriber = track.subscribe({ delay: { max: Duration.millis(30_000) } }); const producer = new LegacyProducer(track, new LegacyFormat("video")); - producer.encode(new Uint8Array([1]), 20_000 as Micro, true); - expect(() => producer.discontinuity(10_000 as Micro)).toThrow(); - producer.encode(new Uint8Array([2]), 30_000 as Micro, false); - producer.discontinuity(35_000 as Micro); + producer.encode(new Uint8Array([1]), Duration.micros(20_000), true); + expect(() => producer.discontinuity(Duration.micros(10_000))).toThrow(); + producer.encode(new Uint8Array([2]), Duration.micros(30_000), false); + producer.discontinuity(Duration.micros(35_000)); producer.close(); const group = await subscriber.recvGroup(); const timestamps = []; @@ -272,11 +272,11 @@ test("Legacy Producer rejects a backwards discontinuity without closing the grou test("Legacy Producer keeps the cadence after rejecting a backwards discontinuity", async () => { const track = new Track.Producer("test"); - const subscriber = track.subscribe({ delay: { max: Milli(30_000) } }); + const subscriber = track.subscribe({ delay: { max: Duration.millis(30_000) } }); const producer = new LegacyProducer(track, new LegacyFormat("video")); - producer.encode(new Uint8Array([1]), 20_000 as Micro, true); - producer.encode(new Uint8Array([2]), 30_000 as Micro, false); - expect(() => producer.discontinuity(10_000 as Micro)).toThrow(); + producer.encode(new Uint8Array([1]), Duration.micros(20_000), true); + producer.encode(new Uint8Array([2]), Duration.micros(30_000), false); + expect(() => producer.discontinuity(Duration.micros(10_000))).toThrow(); producer.close(); const group = await subscriber.recvGroup(); const timestamps = []; @@ -291,9 +291,9 @@ test("Legacy Producer keeps the cadence after rejecting a backwards discontinuit test("Legacy Producer refuses a keyframe that rewinds the timeline", () => { const track = new Track.Producer("test"); const producer = new LegacyProducer(track, new LegacyFormat("video")); - producer.encode(new Uint8Array([1]), 20_000 as Micro, true); - producer.encode(new Uint8Array([2]), 30_000 as Micro, false); - expect(() => producer.encode(new Uint8Array([3]), 0 as Micro, true)).toThrow("below the previous group start"); + producer.encode(new Uint8Array([1]), Duration.micros(20_000), true); + producer.encode(new Uint8Array([2]), Duration.micros(30_000), false); + expect(() => producer.encode(new Uint8Array([3]), Duration.micros(0), true)).toThrow("below the previous group start"); producer.close(); }); @@ -319,11 +319,11 @@ test("Legacy Producer discontinuity marks the break with one empty frame at the const track = new Track.Producer("test"); const subscriber = replay(track); const producer = new LegacyProducer(track, new LegacyFormat("audio")); - producer.encode(new Uint8Array([1]), 0 as Micro, true); - producer.encode(new Uint8Array([1]), 20_000 as Micro, true); + producer.encode(new Uint8Array([1]), Duration.micros(0), true); + producer.encode(new Uint8Array([1]), Duration.micros(20_000), true); producer.discontinuity(); producer.discontinuity(); // nothing new to mark - producer.encode(new Uint8Array([1]), 5_000_000 as Micro, true); + producer.encode(new Uint8Array([1]), Duration.micros(5_000_000), true); producer.close(); expect(await readGroups(subscriber, 3n)).toEqual([ @@ -338,8 +338,8 @@ test("Legacy Producer discontinuity marks the break at the caller's end", async const track = new Track.Producer("test"); const subscriber = replay(track); const producer = new LegacyProducer(track, new LegacyFormat("video")); - producer.encode(new Uint8Array([1]), 0 as Micro, true); - producer.discontinuity(33_000 as Micro); + producer.encode(new Uint8Array([1]), Duration.micros(0), true); + producer.discontinuity(Duration.micros(33_000)); producer.close(); expect(await readGroups(subscriber, 1n)).toEqual([ @@ -359,11 +359,11 @@ test("Legacy Producer discontinuity writes no end estimated from the cadence", a const subscriber = replay(track); const producer = new LegacyProducer(track, new LegacyFormat("video")); for (const [index, timestamp] of [0, 33_000, 66_000].entries()) { - producer.encode(new Uint8Array([1]), timestamp as Micro, index === 0); + producer.encode(new Uint8Array([1]), Duration.micros(timestamp), index === 0); } producer.discontinuity(); // The capture swap resumes sooner than one frame later: no end past it, so no rewind. - producer.encode(new Uint8Array([1]), 80_000 as Micro, true); + producer.encode(new Uint8Array([1]), Duration.micros(80_000), true); producer.close(); expect(await readGroups(subscriber, 2n)).toEqual([ @@ -392,13 +392,13 @@ test("Legacy Producer discontinuity on a data track reads as an end at the edge" const track = new Track.Producer("data"); const subscriber = replay(track); const producer = new LegacyProducer(track, new LegacyFormat("data")); - producer.encode(new Uint8Array([1]), 0 as Micro, true); - producer.encode(new Uint8Array(), 20_000 as Micro, true); + producer.encode(new Uint8Array([1]), Duration.micros(0), true); + producer.encode(new Uint8Array(), Duration.micros(20_000), true); producer.discontinuity(); - producer.encode(new Uint8Array([1]), 5_000_000 as Micro, true); + producer.encode(new Uint8Array([1]), Duration.micros(5_000_000), true); producer.close(); - const consumer = new Consumer(subscriber, { format: new LegacyFormat("data"), delay: { max: 30_000 as Milli } }); + const consumer = new Consumer(subscriber, { format: new LegacyFormat("data"), delay: { max: Duration.millis(30_000) } }); const items: string[] = []; for (let read = await consumer.next(); read; read = await consumer.next()) items.push(describe(read)); expect(items).toEqual(["0", "20000", "end 20000", "5000000"]); @@ -410,11 +410,11 @@ test("Legacy Producer discontinuity on a data track reads as an end at the edge" // A data track's marker is alone in its group, so one sharing it is refused rather than read as // a break or dropped in silence. test("Consumer refuses a data marker that shares its group", async () => { - for (const second of [new Uint8Array(), encodeLegacyFrame(10_000 as Micro, new Uint8Array([1]))]) { + for (const second of [new Uint8Array(), encodeLegacyFrame(10_000, new Uint8Array([1]))]) { const track = new Track.Producer("data"); const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), - delay: { max: 500 as Milli }, + delay: { max: Duration.millis(500) }, }); try { const group = track.appendGroup(); @@ -436,13 +436,13 @@ test("Consumer refuses a data marker that shares its group", async () => { test("Legacy Producer discontinuity keeps pre-pause media from reading as live", async () => { const track = new Track.Producer("test"); const producer = new LegacyProducer(track, new LegacyFormat("video")); - producer.encode(new Uint8Array([1]), 0 as Micro, true); - producer.encode(new Uint8Array([1]), 33_000 as Micro, false); + producer.encode(new Uint8Array([1]), Duration.micros(0), true); + producer.encode(new Uint8Array([1]), Duration.micros(33_000), false); producer.discontinuity(); - producer.encode(new Uint8Array([1]), 5_000_000 as Micro, true); + producer.encode(new Uint8Array([1]), Duration.micros(5_000_000), true); producer.close(); - const subscriber = track.subscribe({ delay: { max: Milli(1_000) } }); + const subscriber = track.subscribe({ delay: { max: Duration.millis(1_000) } }); expect((await readGroups(subscriber, 2n)).map(([sequence]) => sequence)).toEqual([1n, 2n]); }); @@ -462,7 +462,7 @@ test("CmafFormat decodes a valid keyframe segment", () => { expect(result).toHaveLength(1); expect(result[0].payload).toEqual(new Uint8Array([0xca, 0xfe])); - expect(result[0].timestamp).toBe(0 as Micro); + expect(result[0].timestamp.asMicros()).toBe(0); expect(result[0].keyframe).toBe(true); }); @@ -504,7 +504,7 @@ test("CmafFormat converts timescale units to microseconds", () => { const segment = fragment("oneSecond"); const result = format.decode(segment, at(TIMESCALE)); - expect(result[0].timestamp).toBe(1_000_000 as Micro); + expect(result[0].timestamp.asMicros()).toBe(1_000_000); }); test("CmafFormat throws on corrupt segment", () => { @@ -514,7 +514,7 @@ test("CmafFormat throws on corrupt segment", () => { // --- Consumer --- -function encodeLegacy(timestamp: Micro): Uint8Array { +function encodeLegacy(timestamp: number): Uint8Array { const tsBytes = Varint.encode(timestamp); const payload = new Uint8Array([0xde, 0xad]); const data = new Uint8Array(tsBytes.byteLength + payload.byteLength); @@ -527,8 +527,8 @@ function encodeLegacy(timestamp: Micro): Uint8Array { function writeGroupWithLegacyFrames( track: Track.Producer, sequence: bigint, - timestamps: Micro[], - stamp: (ts: Micro) => Time.Timestamp = (ts) => Time.Timestamp.fromMicros(ts), + timestamps: number[], + stamp: (ts: number) => Time.Timestamp = (ts) => Time.Timestamp.fromMicros(ts), ) { const group = track.createGroup(sequence); for (const ts of timestamps) { @@ -537,7 +537,7 @@ function writeGroupWithLegacyFrames( group.finish(); } -function writeMarkerGroup(track: Track.Producer, sequence: bigint, timestamp: Micro) { +function writeMarkerGroup(track: Track.Producer, sequence: bigint, timestamp: number) { const group = track.createGroup(sequence); group.writeFrame({ payload: encodeLegacyFrame(timestamp, new Uint8Array()), @@ -547,13 +547,13 @@ function writeMarkerGroup(track: Track.Producer, sequence: bigint, timestamp: Mi } /** Read every frame deliverable without moving time, leaving the read that waits pending. */ -async function drainFrames(consumer: Consumer): Promise<{ timestamp: Micro; group: bigint; keyframe: boolean }[]> { - const frames: { timestamp: Micro; group: bigint; keyframe: boolean }[] = []; +async function drainFrames(consumer: Consumer): Promise<{ timestamp: number; group: bigint; keyframe: boolean }[]> { + const frames: { timestamp: number; group: bigint; keyframe: boolean }[] = []; for (;;) { const result = await poll(consumer.next()); if (result === "pending" || result === undefined) break; if (result.kind === "frame") { - frames.push({ timestamp: result.frame.timestamp, group: result.group, keyframe: result.frame.keyframe }); + frames.push({ timestamp: result.frame.timestamp.asMicros(), group: result.group, keyframe: result.frame.keyframe }); } } return frames; @@ -561,9 +561,9 @@ async function drainFrames(consumer: Consumer): Promise<{ timestamp: Micro; grou /** An item as "gap <µs>+<µs>", a frame's µs, or "end <µs>". */ function describe(read: Read): string { - if (read.kind === "gap") return `gap ${read.timestamp}+${read.duration}`; - if (read.kind === "end") return `end ${read.end}`; - return `${read.frame.timestamp}`; + if (read.kind === "gap") return `gap ${read.timestamp.asMicros()}+${read.duration.asMicros()}`; + if (read.kind === "end") return `end ${read.end.asMicros()}`; + return `${read.frame.timestamp.asMicros()}`; } /** The frame a read carries, failing on anything else. */ @@ -575,24 +575,24 @@ function frameOf(read: Read | string | undefined): Frame { test("Consumer delivers frames from a single group", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(500) } }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro, 33_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0, 33_000]); track.finish(); track.close(); const frames = await drainFrames(consumer); expect(frames).toHaveLength(2); - expect(frames[0].timestamp).toBe(0 as Micro); - expect(frames[1].timestamp).toBe(33_000 as Micro); + expect(frames[0].timestamp).toBe(0); + expect(frames[1].timestamp).toBe(33_000); consumer.close(); }); test("Consumer forces keyframe true at index 0", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(500) } }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro, 33_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0, 33_000]); track.finish(); track.close(); @@ -607,15 +607,15 @@ test("Consumer index spans MoQ frames for keyframe detection", async () => { const multiFormat: ContainerFormat = { decode(_frame: Uint8Array): Frame[] { return [ - { payload: new Uint8Array([1]), timestamp: 0 as Micro, keyframe: false }, - { payload: new Uint8Array([2]), timestamp: 33_000 as Micro, keyframe: false }, - { payload: new Uint8Array([3]), timestamp: 66_000 as Micro, keyframe: false }, + { payload: new Uint8Array([1]), timestamp: Duration.micros(0), keyframe: false }, + { payload: new Uint8Array([2]), timestamp: Duration.micros(33_000), keyframe: false }, + { payload: new Uint8Array([3]), timestamp: Duration.micros(66_000), keyframe: false }, ]; }, }; const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: multiFormat, delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: multiFormat, delay: { max: Duration.millis(500) } }); const group = track.createGroup(0n); group.writeFrame({ payload: new Uint8Array([0x01]), timestamp: Time.Timestamp.now() }); // first MoQ frame → 3 samples @@ -643,12 +643,12 @@ for (const [where, payloads] of [ const failingFormat: ContainerFormat = { decode(frame: Uint8Array): Frame[] { if (frame[0] === 0xff) throw new Error("malformed"); - return [{ payload: frame, timestamp: frame[0] as Micro, keyframe: false }]; + return [{ payload: frame, timestamp: Duration.micros(frame[0]), keyframe: false }]; }, }; const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: failingFormat, delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: failingFormat, delay: { max: Duration.millis(500) } }); const g0 = track.createGroup(0n); for (const byte of payloads) @@ -667,7 +667,7 @@ for (const [where, payloads] of [ for (;;) { const result = await consumer.next(); if (!result) return result; - if (result.kind === "frame") frames.push(result.frame.timestamp); + if (result.kind === "frame") frames.push(result.frame.timestamp.asMicros()); } }; await expect(read()).rejects.toThrow("malformed"); @@ -679,10 +679,10 @@ for (const [where, payloads] of [ // Errors come in delivery order, so a decode error waits behind the items ahead of it, a gap included. test("Consumer delivers everything ahead of a decode error", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 10_000 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(10_000) } }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro]); - writeGroupWithLegacyFrames(track, 2n, [100_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0]); + writeGroupWithLegacyFrames(track, 2n, [100_000]); const malformed = track.createGroup(3n); // A truncated timestamp varint. malformed.writeFrame({ payload: new Uint8Array([0x80]), timestamp: Time.Timestamp.fromMicros(200_000) }); @@ -708,7 +708,7 @@ test("Consumer keeps the first of several decode errors", async () => { }; const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: failingFormat, delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: failingFormat, delay: { max: Duration.millis(500) } }); for (const sequence of [0n, 1n]) { const group = track.createGroup(sequence); @@ -734,12 +734,12 @@ test("Consumer releases its open groups when an error ends it", async () => { decode(frame: Uint8Array): Frame[] { if (frame[0] === 0xff) throw new Error("malformed"); if (frame[0] === 0x01) resolveOpen(); - return [{ payload: frame, timestamp: frame[0] as Micro, keyframe: false }]; + return [{ payload: frame, timestamp: Duration.micros(frame[0]), keyframe: false }]; }, }; const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: failingFormat, delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: failingFormat, delay: { max: Duration.millis(500) } }); const malformed = track.createGroup(0n); malformed.writeFrame({ payload: new Uint8Array([0xff]), timestamp: Time.Timestamp.now() }); @@ -771,19 +771,19 @@ test("Consumer keeps frames decoded before a group reset (truncated GoP)", async }; const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format, delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format, delay: { max: Duration.millis(500) } }); const g0 = track.createGroup(0n); for (const timestamp of [1, 2]) { g0.writeFrame({ - payload: encodeLegacyFrame(timestamp as Micro, new Uint8Array([1])), + payload: encodeLegacyFrame(timestamp, new Uint8Array([1])), timestamp: Time.Timestamp.fromMicros(timestamp), }); } await decoded; g0.abort(new NetError.Stream(StreamCode.Cancel)); - writeGroupWithLegacyFrames(track, 1n, [4 as Micro]); + writeGroupWithLegacyFrames(track, 1n, [4]); track.finish(); track.close(); @@ -795,7 +795,7 @@ test("Consumer keeps frames decoded before a group reset (truncated GoP)", async test("Consumer close returns undefined from next()", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(500) } }); const promise = consumer.next(); consumer.close(); @@ -806,7 +806,7 @@ test("Consumer close returns undefined from next()", async () => { test("Consumer throws on concurrent next() calls", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(500) } }); // First call blocks waiting for data void consumer.next(); @@ -819,12 +819,12 @@ test("Consumer throws on concurrent next() calls", async () => { test("Consumer skips groups via PTS-span when over the max delay", async () => { const track = new Track.Producer("test"); // Zero max delay = skip everything that's not the latest - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 0 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(0) } }); // Write groups with increasing timestamps. With a 0 max delay, any PTS span > 0 triggers skip. - writeGroupWithLegacyFrames(track, 0n, [0 as Micro]); - writeGroupWithLegacyFrames(track, 1n, [100_000 as Micro]); - writeGroupWithLegacyFrames(track, 2n, [200_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0]); + writeGroupWithLegacyFrames(track, 1n, [100_000]); + writeGroupWithLegacyFrames(track, 2n, [200_000]); track.finish(); track.close(); @@ -839,29 +839,29 @@ test("Consumer measures arrivals as they land", async () => { const track = new Track.Producer("test"); const consumer = new Consumer(track.subscribe(), { format: new LegacyFormat("audio"), - delay: { max: 5000 as Milli }, + delay: { max: Duration.millis(5000) }, }); const next = new Track.Producer("next"); try { // Nothing observed yet: the cold-start estimate. - expect(consumer.spread.peek()).toBe(100 as Milli); + expect(consumer.spread.peek()).toEqual(Duration.millis(100)); // Groups arriving exactly as fast as their media, across four resample intervals. Nothing is // late, so the evidence pulls the estimate down from the cold start. for (let i = 0; i < 5; i++) { - writeGroupWithLegacyFrames(track, BigInt(i), [(i * 520_000) as Micro]); - await clock.advance(Nano.fromMilli(Milli(520))); + writeGroupWithLegacyFrames(track, BigInt(i), [(i * 520_000)]); + await clock.advance(Duration.millis(520)); } - expect(consumer.spread.peek()).toBeLessThan(100 as Milli); + expect(consumer.spread.peek().asMillis()).toBeLessThan(100); // A replacement on the same path continues the estimate rather than restarting cold. const replacement = new Consumer(next.subscribe(), { format: new LegacyFormat("audio"), - delay: { max: 5000 as Milli }, + delay: { max: Duration.millis(5000) }, predecessor: consumer, }); - expect(replacement.spread.peek()).toBe(consumer.spread.peek()); + expect(replacement.spread.peek()).toEqual(consumer.spread.peek()); replacement.close(); } finally { track.finish(); @@ -876,7 +876,7 @@ test("Consumer does not relax its measurement across a declared silence", async // Two identical paths, except that one publisher declares its silence and the other just stops. const declared = new Track.Producer("declared"); const undeclared = new Track.Producer("undeclared"); - const options = { format: new LegacyFormat("audio"), delay: { max: 5000 as Milli } }; + const options = { format: new LegacyFormat("audio"), delay: { max: Duration.millis(5000) } }; const quiet = new Consumer(declared.subscribe(), options); const lapsed = new Consumer(undeclared.subscribe(), options); const producers = [new LegacyProducer(declared, options.format), new LegacyProducer(undeclared, options.format)]; @@ -884,9 +884,9 @@ test("Consumer does not relax its measurement across a declared silence", async let media = 0; const send = async (count: number) => { for (let i = 0; i < count; i++) { - for (const producer of producers) producer.encode(payload, (media * 1000) as Micro, true); + for (const producer of producers) producer.encode(payload, Duration.micros((media * 1000)), true); media += 520; - await clock.advance(Nano.fromMilli(Milli(520))); + await clock.advance(Duration.millis(520)); } }; @@ -894,16 +894,16 @@ test("Consumer does not relax its measurement across a declared silence", async // Arrivals exactly as fast as their media until the cold-start prior is spent. await send(40); const settled = quiet.spread.peek(); - expect(lapsed.spread.peek()).toBe(settled); + expect(lapsed.spread.peek()).toEqual(settled); // A minute of silence on both, declared on one. producers[0].discontinuity(); media += 60_000; - await clock.advance(Nano.fromMilli(Milli(60_000))); + await clock.advance(Duration.millis(60_000)); await send(2); - expect(quiet.spread.peek()).toBe(settled); - expect(lapsed.spread.peek()).toBeGreaterThan(settled); + expect(quiet.spread.peek()).toEqual(settled); + expect(lapsed.spread.peek().gt(settled)).toBe(true); } finally { for (const track of [declared, undeclared]) { track.finish(); @@ -918,11 +918,11 @@ test("Consumer does not relax its measurement across a declared silence", async test("Consumer delivers groups in sequence order regardless of arrival order", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(500) } }); - writeGroupWithLegacyFrames(track, 2n, [60_000 as Micro]); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro]); - writeGroupWithLegacyFrames(track, 1n, [30_000 as Micro]); + writeGroupWithLegacyFrames(track, 2n, [60_000]); + writeGroupWithLegacyFrames(track, 0n, [0]); + writeGroupWithLegacyFrames(track, 1n, [30_000]); track.finish(); track.close(); @@ -940,15 +940,15 @@ test("Consumer delivers groups in sequence order regardless of arrival order", a // group arriving there is never delivered and adds no gap. Mirrors Rust's consumer. test("Consumer drops a group that arrives below the cursor", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(500) } }); // Group 5 arrives first, and delivery starts there: the track reports no start. - writeGroupWithLegacyFrames(track, 5n, [100_000 as Micro]); + writeGroupWithLegacyFrames(track, 5n, [100_000]); expect((await nextFrame(consumer))?.group).toBe(5n); // Group 3 lands behind the cursor, and group 6 ahead of it. - writeGroupWithLegacyFrames(track, 3n, [0 as Micro]); - writeGroupWithLegacyFrames(track, 6n, [200_000 as Micro]); + writeGroupWithLegacyFrames(track, 3n, [0]); + writeGroupWithLegacyFrames(track, 6n, [200_000]); track.finish(); track.close(); @@ -966,10 +966,10 @@ test("Consumer drops a group that arrives below the cursor", async () => { test("Consumer next() yields no gap before the first frame", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(500) } }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro, 33_000 as Micro]); - writeGroupWithLegacyFrames(track, 1n, [66_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0, 33_000]); + writeGroupWithLegacyFrames(track, 1n, [66_000]); track.finish(); track.close(); @@ -988,16 +988,16 @@ test("Consumer next() yields no gap before the first frame", async () => { test("Consumer reads nothing after close, even the frame a gap was returned ahead of", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: 0 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: Duration.millis(0) } }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0]); await flush(); - expect(frameOf(await consumer.next()).timestamp).toBe(0 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(0); // Group 1 never arrives, so group 2's frame is deferred behind a gap. - writeGroupWithLegacyFrames(track, 2n, [100_000 as Micro]); + writeGroupWithLegacyFrames(track, 2n, [100_000]); await flush(); - expect(await consumer.next()).toEqual({ kind: "gap", timestamp: 0 as Micro, duration: 100_000 as Micro }); + expect(await consumer.next()).toEqual({ kind: "gap", timestamp: Duration.micros(0), duration: Duration.micros(100_000) }); consumer.close(); expect(await consumer.next()).toBeUndefined(); @@ -1009,16 +1009,16 @@ test("Consumer keeps a trailing duration marker internal", async () => { const track = new Track.Producer("test"); const consumer = new Consumer(track.subscribe(), { format: new LegacyFormat("video"), - delay: { max: 500 as Milli }, + delay: { max: Duration.millis(500) }, }); const group = track.createGroup(0n); group.writeFrame({ - payload: encodeLegacyFrame(0 as Micro, new Uint8Array([0xde, 0xad])), + payload: encodeLegacyFrame(0, new Uint8Array([0xde, 0xad])), timestamp: Time.Timestamp.now(), }); group.writeFrame({ - payload: encodeLegacyFrame(33_000 as Micro, new Uint8Array()), + payload: encodeLegacyFrame(33_000, new Uint8Array()), timestamp: Time.Timestamp.now(), }); group.finish(); @@ -1039,23 +1039,23 @@ test("Consumer reads a leading marker as an end and keeps the first media keyfra const track = new Track.Producer("test"); const consumer = new Consumer(track.subscribe(), { format: new LegacyFormat("video"), - delay: { max: 500 as Milli }, + delay: { max: Duration.millis(500) }, }); const group = track.createGroup(0n); group.writeFrame({ - payload: encodeLegacyFrame(20_000 as Micro, new Uint8Array()), + payload: encodeLegacyFrame(20_000, new Uint8Array()), timestamp: Time.Timestamp.now(), }); group.writeFrame({ - payload: encodeLegacyFrame(20_000 as Micro, new Uint8Array([0xde, 0xad])), + payload: encodeLegacyFrame(20_000, new Uint8Array([0xde, 0xad])), timestamp: Time.Timestamp.now(), }); group.finish(); track.finish(); track.close(); - expect(await consumer.next()).toEqual({ kind: "end", group: 0n, end: 20_000 as Micro }); + expect(await consumer.next()).toEqual({ kind: "end", group: 0n, end: Duration.micros(20_000) }); const media = frameOf(await consumer.next()); expect(media.payload).toEqual(new Uint8Array([0xde, 0xad])); expect(media.keyframe).toBe(true); @@ -1067,13 +1067,13 @@ test("Consumer reads an empty LOC payload as the frame's duration", async () => const track = new Track.Producer("test"); writeLoc(track, [ [ - [0 as Micro, [0xde, 0xad]], - [33_000 as Micro, []], - [66_000 as Micro, []], + [0, [0xde, 0xad]], + [33_000, []], + [66_000, []], ], ]); - const consumer = new Consumer(replay(track), { format: new LocFormat("video"), delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LocFormat("video"), delay: { max: Duration.millis(500) } }); await flush(); const media = frameOf(await consumer.next()); expect(media.payload).toEqual(new Uint8Array([0xde, 0xad])); @@ -1086,17 +1086,17 @@ test("Consumer passes over LOC duration markers", async () => { const track = new Track.Producer("test"); writeLoc(track, [ [ - [0 as Micro, [0xde, 0xad]], - [10_000 as Micro, [0xbe, 0xef]], - [20_000 as Micro, []], + [0, [0xde, 0xad]], + [10_000, [0xbe, 0xef]], + [20_000, []], ], [ - [20_000 as Micro, [0xca, 0xfe]], - [30_000 as Micro, []], + [20_000, [0xca, 0xfe]], + [30_000, []], ], ]); - const consumer = new Consumer(replay(track), { format: new LocFormat("video"), delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LocFormat("video"), delay: { max: Duration.millis(500) } }); await flush(); const first = frameOf(await consumer.next()); expect(first.payload).toEqual(new Uint8Array([0xde, 0xad])); @@ -1114,13 +1114,13 @@ test("Consumer preserves empty Legacy and LOC data frames", async () => { const track = new Track.Producer("data"); if (kind === "legacy") { const producer = new LegacyProducer(track, new LegacyFormat("data")); - producer.encode(new Uint8Array(), 0 as Micro, true); + producer.encode(new Uint8Array(), Duration.micros(0), true); producer.close(); } else { - writeLoc(track, [[[0 as Micro, []]]]); + writeLoc(track, [[[0, []]]]); } const format = kind === "legacy" ? new LegacyFormat("data") : new LocFormat(); - const consumer = new Consumer(replay(track), { format, delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format, delay: { max: Duration.millis(500) } }); const frame = frameOf(await consumer.next()); expect(frame.payload).toEqual(new Uint8Array()); expect(frame.keyframe).toBe(true); @@ -1144,13 +1144,13 @@ const wallClock = () => Time.Timestamp.now(); test("Consumer aborts a group below the previous group start", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 30_000 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(30_000) } }); - writeGroupWithLegacyFrames(track, 0n, [10_000_000 as Micro], wallClock); - writeGroupWithLegacyFrames(track, 1n, [0 as Micro, 100_000 as Micro], wallClock); + writeGroupWithLegacyFrames(track, 0n, [10_000_000], wallClock); + writeGroupWithLegacyFrames(track, 1n, [0, 100_000], wallClock); await flush(); - expect((await nextFrame(consumer))?.frame?.timestamp).toBe(10_000_000 as Micro); + expect((await nextFrame(consumer))?.frame?.timestamp.asMicros()).toBe(10_000_000); await expect(nextFrame(consumer)).rejects.toThrow("below the previous group start"); consumer.close(); @@ -1159,18 +1159,18 @@ test("Consumer aborts a group below the previous group start", async () => { // A later group's rewind does not mask an earlier group's decode error. test("Consumer throws the first error in delivery order", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 30_000 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(30_000) } }); - writeGroupWithLegacyFrames(track, 0n, [10_000_000 as Micro], wallClock); + writeGroupWithLegacyFrames(track, 0n, [10_000_000], wallClock); const malformed = track.createGroup(1n); // A truncated timestamp varint. malformed.writeFrame({ payload: new Uint8Array([0x80]), timestamp: wallClock() }); malformed.finish(); - writeGroupWithLegacyFrames(track, 2n, [0 as Micro, 100_000 as Micro], wallClock); + writeGroupWithLegacyFrames(track, 2n, [0, 100_000], wallClock); track.finish(); track.close(); - expect((await nextFrame(consumer))?.frame?.timestamp).toBe(10_000_000 as Micro); + expect((await nextFrame(consumer))?.frame?.timestamp.asMicros()).toBe(10_000_000); await expect(nextFrame(consumer)).rejects.toThrow("buffer too short"); consumer.close(); }); @@ -1187,7 +1187,7 @@ test("Consumer checks a whole decoded batch before a skip drops its group", asyn decode(frame: Uint8Array): Frame[] { const timestamps = JSON.parse(new TextDecoder().decode(frame)) as number[]; for (const timestamp of timestamps) decoded.get(timestamp)?.(); - return timestamps.map((timestamp) => ({ payload: frame, timestamp: timestamp as Micro, keyframe: true })); + return timestamps.map((timestamp) => ({ payload: frame, timestamp: Duration.micros(timestamp), keyframe: true })); }, }; const write = (sequence: bigint, timestamps: number[]) => { @@ -1201,10 +1201,10 @@ test("Consumer checks a whole decoded batch before a skip drops its group", asyn }; const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: batchFormat, delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: batchFormat, delay: { max: Duration.millis(500) } }); write(0n, [1_000_000]).finish(); - expect((await nextFrame(consumer))?.frame?.timestamp).toBe(1_000_000 as Micro); + expect((await nextFrame(consumer))?.frame?.timestamp.asMicros()).toBe(1_000_000); // Its first sample is fine; the second rewinds below the delivered group's start. write(2n, [2_000_000, 0]).finish(); @@ -1226,15 +1226,15 @@ test("Consumer checks a whole decoded batch before a skip drops its group", asyn test("Consumer aborts a rewind carried by a later arrival", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 30_000 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(30_000) } }); - writeGroupWithLegacyFrames(track, 0n, [10_000_000 as Micro], wallClock); + writeGroupWithLegacyFrames(track, 0n, [10_000_000], wallClock); await flush(); - expect((await nextFrame(consumer))?.frame?.timestamp).toBe(10_000_000 as Micro); + expect((await nextFrame(consumer))?.frame?.timestamp.asMicros()).toBe(10_000_000); const pending = nextFrame(consumer); await flush(); - writeGroupWithLegacyFrames(track, 1n, [0 as Micro, 100_000 as Micro], wallClock); + writeGroupWithLegacyFrames(track, 1n, [0, 100_000], wallClock); await expect(pending).rejects.toThrow("below the previous group start"); @@ -1245,20 +1245,20 @@ test("Consumer aborts a rewind carried by a later arrival", async () => { // rewind, so the detector compares against the previous group's start. test("Consumer treats B-frame reordering within a group as continuous", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 30_000 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(30_000) } }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro, 66_000 as Micro, 33_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0, 66_000, 33_000]); await flush(); for (const timestamp of [0, 66_000, 33_000]) { - expect(frameOf(await consumer.next()).timestamp).toBe(timestamp as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(timestamp); } // The cursor is now on group 1, whose own frames reorder the same way. - writeGroupWithLegacyFrames(track, 1n, [100_000 as Micro, 166_000 as Micro, 133_000 as Micro]); + writeGroupWithLegacyFrames(track, 1n, [100_000, 166_000, 133_000]); await flush(); for (const timestamp of [100_000, 166_000, 133_000]) { // Read directly: a gap here would fail the frame check. - expect(frameOf(await consumer.next()).timestamp).toBe(timestamp as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(timestamp); } consumer.close(); @@ -1266,13 +1266,13 @@ test("Consumer treats B-frame reordering within a group as continuous", async () test("Consumer accepts open-GOP leading pictures above the previous group", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 30_000 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(30_000) } }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro, 33_000 as Micro]); - writeGroupWithLegacyFrames(track, 1n, [66_000 as Micro, 50_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0, 33_000]); + writeGroupWithLegacyFrames(track, 1n, [66_000, 50_000]); await flush(); for (const timestamp of [0, 33_000, 66_000, 50_000]) { - expect(frameOf(await consumer.next()).timestamp).toBe(timestamp as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(timestamp); } consumer.close(); @@ -1282,18 +1282,18 @@ test("Consumer accepts open-GOP leading pictures above the previous group", asyn // the max delay loses nothing. test("Consumer reads no gap when retiring a fully delivered group", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: 150 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: Duration.millis(150) } }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0]); await flush(); - expect(frameOf(await consumer.next()).timestamp).toBe(0 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(0); - writeGroupWithLegacyFrames(track, 1n, [100_000 as Micro]); - writeGroupWithLegacyFrames(track, 2n, [200_000 as Micro]); + writeGroupWithLegacyFrames(track, 1n, [100_000]); + writeGroupWithLegacyFrames(track, 2n, [200_000]); await flush(); // Read directly: a gap here would fail the frame check. - expect(frameOf(await consumer.next()).timestamp).toBe(100_000 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(100_000); consumer.close(); }); @@ -1301,23 +1301,23 @@ test("Consumer reads no gap when retiring a fully delivered group", async () => // An unread trailing endpoint carries no media, so retiring its group loses nothing. test("Consumer reads no gap when retiring a group holding only its endpoint", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("video"), delay: { max: 150 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("video"), delay: { max: Duration.millis(150) } }); const group = track.createGroup(0n); - group.writeFrame({ payload: encodeLegacy(0 as Micro), timestamp: Time.Timestamp.fromMicros(0) }); + group.writeFrame({ payload: encodeLegacy(0), timestamp: Time.Timestamp.fromMicros(0) }); group.writeFrame({ - payload: encodeLegacyFrame(33_000 as Micro, new Uint8Array()), + payload: encodeLegacyFrame(33_000, new Uint8Array()), timestamp: Time.Timestamp.fromMicros(33_000), }); group.finish(); await flush(); - expect(frameOf(await consumer.next()).timestamp).toBe(0 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(0); - writeGroupWithLegacyFrames(track, 1n, [100_000 as Micro]); - writeGroupWithLegacyFrames(track, 2n, [200_000 as Micro]); + writeGroupWithLegacyFrames(track, 1n, [100_000]); + writeGroupWithLegacyFrames(track, 2n, [200_000]); await flush(); - expect(frameOf(await consumer.next()).timestamp).toBe(100_000 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(100_000); consumer.close(); }); @@ -1326,21 +1326,21 @@ test("Consumer reads no gap when retiring a group holding only its endpoint", as // next group is adjacent. test("Consumer reads a gap when retiring a truncated group", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: 150 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: Duration.millis(150) } }); const group = track.createGroup(0n); - group.writeFrame({ payload: encodeLegacy(0 as Micro), timestamp: Time.Timestamp.fromMicros(0) }); + group.writeFrame({ payload: encodeLegacy(0), timestamp: Time.Timestamp.fromMicros(0) }); await flush(); - expect(frameOf(await consumer.next()).timestamp).toBe(0 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(0); group.abort(new NetError.Stream(StreamCode.Cancel)); - writeGroupWithLegacyFrames(track, 1n, [100_000 as Micro]); - writeGroupWithLegacyFrames(track, 2n, [200_000 as Micro]); + writeGroupWithLegacyFrames(track, 1n, [100_000]); + writeGroupWithLegacyFrames(track, 2n, [200_000]); await flush(); // Legacy carries no duration, so the gap starts at the last frame read. - expect(await consumer.next()).toEqual({ kind: "gap", timestamp: 0 as Micro, duration: 100_000 as Micro }); - expect(frameOf(await consumer.next()).timestamp).toBe(100_000 as Micro); + expect(await consumer.next()).toEqual({ kind: "gap", timestamp: Duration.micros(0), duration: Duration.micros(100_000) }); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(100_000); consumer.close(); }); @@ -1348,21 +1348,21 @@ test("Consumer reads a gap when retiring a truncated group", async () => { // An open group may still have a tail in flight, so adjacency proves nothing when it is retired. test("Consumer reads a gap when retiring an open group", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: 150 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: Duration.millis(150) } }); const group = track.createGroup(0n); - group.writeFrame({ payload: encodeLegacy(0 as Micro), timestamp: Time.Timestamp.fromMicros(0) }); + group.writeFrame({ payload: encodeLegacy(0), timestamp: Time.Timestamp.fromMicros(0) }); await flush(); - expect(frameOf(await consumer.next()).timestamp).toBe(0 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(0); // Group 1 starts a whole budget behind the newest content, so the open group is retired. - writeGroupWithLegacyFrames(track, 1n, [100_000 as Micro]); - writeGroupWithLegacyFrames(track, 2n, [250_000 as Micro]); + writeGroupWithLegacyFrames(track, 1n, [100_000]); + writeGroupWithLegacyFrames(track, 2n, [250_000]); await flush(); // Legacy carries no duration, so the gap starts at the last frame read. - expect(await consumer.next()).toEqual({ kind: "gap", timestamp: 0 as Micro, duration: 100_000 as Micro }); - expect(frameOf(await consumer.next()).timestamp).toBe(100_000 as Micro); + expect(await consumer.next()).toEqual({ kind: "gap", timestamp: Duration.micros(0), duration: Duration.micros(100_000) }); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(100_000); group.finish(); consumer.close(); @@ -1372,19 +1372,19 @@ test("Consumer reads a gap when retiring an open group", async () => { test("Consumer buffered signal updates as frames arrive", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(500) } }); expect(consumer.buffered.peek()).toEqual([]); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro, 33_000 as Micro]); - writeGroupWithLegacyFrames(track, 1n, [66_000 as Micro, 99_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0, 33_000]); + writeGroupWithLegacyFrames(track, 1n, [66_000, 99_000]); await flush(); const ranges = consumer.buffered.peek(); expect(ranges.length).toBe(1); - expect(ranges[0].start).toBe(0 as Milli); - expect((ranges[0].end as number) >= 66).toBeTruthy(); + expect(ranges[0].start).toEqual(Duration.millis(0)); + expect(ranges[0].end.asMillis()).toBeGreaterThanOrEqual(66); track.finish(); track.close(); @@ -1395,14 +1395,14 @@ test("Consumer buffered signal updates as frames arrive", async () => { test("Consumer recovers from gap in group sequence numbers", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 100 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(100) } }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro, 20_000 as Micro]); - writeGroupWithLegacyFrames(track, 1n, [40_000 as Micro, 60_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0, 20_000]); + writeGroupWithLegacyFrames(track, 1n, [40_000, 60_000]); // Skip group 2 - writeGroupWithLegacyFrames(track, 3n, [120_000 as Micro, 140_000 as Micro]); - writeGroupWithLegacyFrames(track, 4n, [160_000 as Micro, 180_000 as Micro]); - writeGroupWithLegacyFrames(track, 5n, [200_000 as Micro, 220_000 as Micro]); + writeGroupWithLegacyFrames(track, 3n, [120_000, 140_000]); + writeGroupWithLegacyFrames(track, 4n, [160_000, 180_000]); + writeGroupWithLegacyFrames(track, 5n, [200_000, 220_000]); track.finish(); track.close(); @@ -1421,12 +1421,12 @@ test("Consumer handles empty decode result without deadlock", async () => { decode(_frame: Uint8Array): Frame[] { callCount++; if (callCount === 1) return []; // empty result - return [{ payload: new Uint8Array([1]), timestamp: 33_000 as Micro, keyframe: false }]; + return [{ payload: new Uint8Array([1]), timestamp: Duration.micros(33_000), keyframe: false }]; }, }; const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: emptyThenValid, delay: { max: 500 as Milli } }); + const consumer = new Consumer(replay(track), { format: emptyThenValid, delay: { max: Duration.millis(500) } }); const group = track.createGroup(0n); group.writeFrame({ payload: new Uint8Array([0x01]), timestamp: Time.Timestamp.now() }); // empty decode @@ -1448,11 +1448,11 @@ test("Consumer handles empty decode result without deadlock", async () => { test("Consumer preserves empty media from formats without endpoint markers", async () => { const format: ContainerFormat = { decode(): Frame[] { - return [{ payload: new Uint8Array(), timestamp: 0 as Micro, keyframe: false }]; + return [{ payload: new Uint8Array(), timestamp: Duration.micros(0), keyframe: false }]; }, }; const track = new Track.Producer("test"); - const consumer = new Consumer(track.subscribe(), { format, delay: { max: 500 as Milli } }); + const consumer = new Consumer(track.subscribe(), { format, delay: { max: Duration.millis(500) } }); const group = track.createGroup(0n); group.writeFrame({ payload: new Uint8Array([1]), timestamp: Time.Timestamp.now() }); group.finish(); @@ -1469,7 +1469,7 @@ test("Consumer with CmafFormat delivers correct timestamps", async () => { const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: new CmafFormat(TEST_INIT), - delay: { max: 500 as Milli }, + delay: { max: Duration.millis(500) }, }); const group = track.createGroup(0n); @@ -1489,8 +1489,8 @@ test("Consumer with CmafFormat delivers correct timestamps", async () => { expect(frames).toHaveLength(2); expect(frames[0].keyframe).toBe(true); // index 0 override expect(frames[1].keyframe).toBe(false); // trusts format - expect(frames[0].timestamp).toBe(0 as Micro); - expect(frames[1].timestamp).toBe(33_333 as Micro); // 3000/90000 * 1_000_000 + expect(frames[0].timestamp).toBe(0); + expect(frames[1].timestamp).toBe(33_333); // 3000/90000 * 1_000_000 consumer.close(); }); @@ -1498,7 +1498,7 @@ test("Consumer with CmafFormat times an untimed track from tfdt", async () => { const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: new CmafFormat(TEST_INIT), - delay: { max: 500 as Milli }, + delay: { max: Duration.millis(500) }, }); const group = track.createGroup(0n); @@ -1509,7 +1509,7 @@ test("Consumer with CmafFormat times an untimed track from tfdt", async () => { track.close(); const frames = await drainFrames(consumer); - expect(frames.map((f) => f.timestamp)).toEqual([1_000_000, 1_033_333] as Micro[]); + expect(frames.map((f) => f.timestamp)).toEqual([1_000_000, 1_033_333]); consumer.close(); }); @@ -1519,7 +1519,7 @@ test("CmafFormat decodes the per-sample duration", () => { const [frame] = format.decode(segment, at(0)); // 3000 ticks / 90000 timescale * 1_000_000 = 33333µs - expect(frame.duration).toBe(33_333 as Micro); + expect(frame.duration?.asMicros()).toBe(33_333); }); // --- Duration skipping --- @@ -1530,8 +1530,8 @@ const durationFormat: ContainerFormat = { return [ { payload: frame, - timestamp: (frame[0] * 1000) as Micro, - duration: 33_000 as Micro, + timestamp: Duration.micros((frame[0] * 1000)), + duration: Duration.micros(33_000), keyframe: false, }, ]; @@ -1541,7 +1541,7 @@ const durationFormat: ContainerFormat = { test("Consumer duration-skips a stalled group once it is covered", async () => { const track = new Track.Producer("test"); // Latency dwarfs the gap, so only duration coverage can trigger the skip. - const consumer = new Consumer(replay(track), { format: durationFormat, delay: { max: 10_000 as Milli } }); + const consumer = new Consumer(replay(track), { format: durationFormat, delay: { max: Duration.millis(10_000) } }); // Group.Producer 0: one frame at ts=0 lasting 33ms, never closed (stalled). const g0 = track.createGroup(0n); @@ -1568,8 +1568,8 @@ test("Consumer does not duration-skip when the gap is not covered", async () => return [ { payload: frame, - timestamp: (frame[0] * 1000) as Micro, - duration: 10_000 as Micro, + timestamp: Duration.micros((frame[0] * 1000)), + duration: Duration.micros(10_000), keyframe: false, }, ]; @@ -1577,7 +1577,7 @@ test("Consumer does not duration-skip when the gap is not covered", async () => }; const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: shortFormat, delay: { max: 10_000 as Milli } }); + const consumer = new Consumer(replay(track), { format: shortFormat, delay: { max: Duration.millis(10_000) } }); // Group.Producer 0 stays open and later receives a second frame; nothing covers the gap, // so that late frame must survive rather than being skipped. @@ -1610,13 +1610,13 @@ test("Consumer delivers a PTS-contiguous next group whose sequence jumped (Legac const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: timedLegacy, - delay: { max: 500 as Milli }, + delay: { max: Duration.millis(500) }, }); // Group A (seq 1_000_000): one 3000-tick sample, so its content ends at 33_333µs (3000/90000 * 1e6). const a = track.createGroup(1_000_000n); a.writeFrame({ - payload: encodeLegacyFrame(Math.round((0 / TIMESCALE) * 1_000_000) as Micro, new Uint8Array([0x01])), + payload: encodeLegacyFrame(Math.round((0 / TIMESCALE) * 1_000_000) as number, new Uint8Array([0x01])), timestamp: at(0), }); a.finish(); @@ -1631,7 +1631,7 @@ test("Consumer delivers a PTS-contiguous next group whose sequence jumped (Legac // tolerance, so the timeline is unbroken and B must deliver immediately even while still open. const b = track.createGroup(1_090_000n); b.writeFrame({ - payload: encodeLegacyFrame(Math.round((3045 / TIMESCALE) * 1_000_000) as Micro, new Uint8Array([0x02])), + payload: encodeLegacyFrame(Math.round((3045 / TIMESCALE) * 1_000_000) as number, new Uint8Array([0x02])), timestamp: at(3045), }); @@ -1649,13 +1649,13 @@ test("Consumer waits on a PTS gap instead of skipping to a later buffered group const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: timedLegacy, - delay: { max: 10_000 as Milli }, + delay: { max: Duration.millis(10_000) }, }); // Group A (seq 1_000_000): content ends at 33_333µs. const a = track.createGroup(1_000_000n); a.writeFrame({ - payload: encodeLegacyFrame(Math.round((0 / TIMESCALE) * 1_000_000) as Micro, new Uint8Array([0x01])), + payload: encodeLegacyFrame(Math.round((0 / TIMESCALE) * 1_000_000) as number, new Uint8Array([0x01])), timestamp: at(0), }); a.finish(); @@ -1668,19 +1668,19 @@ test("Consumer waits on a PTS gap instead of skipping to a later buffered group // gap. An intermediate group may still be in transit, so C must NOT be delivered yet. const c = track.createGroup(1_090_000n); c.writeFrame({ - payload: encodeLegacyFrame(Math.round((90_000 / TIMESCALE) * 1_000_000) as Micro, new Uint8Array([0x03])), + payload: encodeLegacyFrame(Math.round((90_000 / TIMESCALE) * 1_000_000) as number, new Uint8Array([0x03])), timestamp: at(90_000), }); // Held until the max delay runs out: the gap is not eagerly skipped. - await clock.advance(Nano.fromMilli(Milli(9_999))); + await clock.advance(Duration.millis(9_999)); expect(await poll(pending)).toBe("pending"); // The missing group B arrives, contiguous with A (first PTS 3000 ticks = 33_333µs = A.end); it // continues the timeline, so delivery resumes with B's frame. const b = track.createGroup(1_045_000n); b.writeFrame({ - payload: encodeLegacyFrame(Math.round((3000 / TIMESCALE) * 1_000_000) as Micro, new Uint8Array([0x02])), + payload: encodeLegacyFrame(Math.round((3000 / TIMESCALE) * 1_000_000) as number, new Uint8Array([0x02])), timestamp: at(3000), }); @@ -1698,7 +1698,7 @@ test("Consumer delivers a contiguous group after one that completed out of order const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: timedLegacy, - delay: { max: 10_000 as Milli }, + delay: { max: Duration.millis(10_000) }, }); // A (seq 1_000_000) stays open so it remains the active group. @@ -1741,7 +1741,7 @@ test("Consumer plays the head once a waited-out gap exceeds the budget (Legacy)" const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: timedLegacy, - delay: { max: 100 as Milli }, + delay: { max: Duration.millis(100) }, }); // A (seq 1000): one frame, ends at 3000 ticks (33_333µs). @@ -1765,7 +1765,7 @@ test("Consumer plays the head once a waited-out gap exceeds the budget (Legacy)" // The missing group's span was never delivered, so a gap from A's end to B comes first. const result = await poll(pending); - expect(result).toEqual({ kind: "gap", timestamp: 33_333 as Micro, duration: 966_667 as Micro }); + expect(result).toEqual({ kind: "gap", timestamp: Duration.micros(33_333), duration: Duration.micros(966_667) }); expect(frameOf(await consumer.next()).payload).toEqual(new Uint8Array([0x02])); consumer.close(); @@ -1776,7 +1776,7 @@ test("Consumer waits on a gap within the budget, then plays the head once it exc const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: timedLegacy, - delay: { max: 100 as Milli }, + delay: { max: Duration.millis(100) }, }); // A (seq 1000): one frame, ends at 3000 ticks (33_333µs). @@ -1791,7 +1791,7 @@ test("Consumer waits on a gap within the budget, then plays the head once it exc // Waited out until just short of the budget. const pending = consumer.next(); - await clock.advance(Nano.fromMilli(Milli(99))); + await clock.advance(Duration.millis(99)); expect(await poll(pending)).toBe("pending"); // B alone grows past the budget (up to 12_000 ticks, 100ms past A's end and beyond). @@ -1801,7 +1801,7 @@ test("Consumer waits on a gap within the budget, then plays the head once it exc } const result = await poll(pending); - expect(result).toEqual({ kind: "gap", timestamp: 33_333 as Micro, duration: 33_334 as Micro }); + expect(result).toEqual({ kind: "gap", timestamp: Duration.micros(33_333), duration: Duration.micros(33_334) }); expect(frameOf(await consumer.next()).payload).toEqual(new Uint8Array([0x02])); consumer.close(); @@ -1814,111 +1814,111 @@ test("Consumer waits on a gap within the budget, then plays the head once it exc // adjacency doesn't rule out a group the max delay check dropped on the way past. test("Consumer yields no gap while nothing is dropped", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 100 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(100) } }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro, 33_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0, 33_000]); await flush(); - expect(frameOf(await consumer.next()).timestamp).toBe(0 as Micro); - expect(frameOf(await consumer.next()).timestamp).toBe(33_000 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(0); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(33_000); - writeGroupWithLegacyFrames(track, 1n, [66_000 as Micro]); + writeGroupWithLegacyFrames(track, 1n, [66_000]); await flush(); - expect(frameOf(await consumer.next()).timestamp).toBe(66_000 as Micro); // group 1 continues group 0 + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(66_000); // group 1 continues group 0 consumer.close(); }); test("Consumer reads a marker group as an end, not a gap", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: 2_000 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: Duration.millis(2_000) } }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro]); - writeMarkerGroup(track, 1n, 0 as Micro); - writeGroupWithLegacyFrames(track, 2n, [1_000_000 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0]); + writeMarkerGroup(track, 1n, 0); + writeGroupWithLegacyFrames(track, 2n, [1_000_000]); await flush(); - expect(frameOf(await consumer.next()).timestamp).toBe(0 as Micro); - expect(await consumer.next()).toEqual({ kind: "end", group: 1n, end: 0 as Micro }); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(0); + expect(await consumer.next()).toEqual({ kind: "end", group: 1n, end: Duration.micros(0) }); // A declared stop loses nothing, so no gap follows it. - expect(frameOf(await consumer.next()).timestamp).toBe(1_000_000 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(1_000_000); consumer.close(); }); test("Consumer empty groups mean nothing", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: 2_000 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: Duration.millis(2_000) } }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0]); const empty = track.createGroup(1n); empty.finish(); - writeGroupWithLegacyFrames(track, 2n, [1_000 as Micro]); + writeGroupWithLegacyFrames(track, 2n, [1_000]); await flush(); - expect(frameOf(await consumer.next()).timestamp).toBe(0 as Micro); - expect(frameOf(await consumer.next()).timestamp).toBe(1_000 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(0); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(1_000); consumer.close(); }); test("Consumer reads a latency skip as one gap", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: 0 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: Duration.millis(0) } }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0]); await flush(); - expect((await nextFrame(consumer))?.frame?.timestamp).toBe(0 as Micro); + expect((await nextFrame(consumer))?.frame?.timestamp.asMicros()).toBe(0); - writeGroupWithLegacyFrames(track, 2n, [100_000 as Micro]); + writeGroupWithLegacyFrames(track, 2n, [100_000]); await flush(); - expect(await consumer.next()).toEqual({ kind: "gap", timestamp: 0 as Micro, duration: 100_000 as Micro }); - expect(frameOf(await consumer.next()).timestamp).toBe(100_000 as Micro); + expect(await consumer.next()).toEqual({ kind: "gap", timestamp: Duration.micros(0), duration: Duration.micros(100_000) }); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(100_000); consumer.close(); }); test("Consumer reads a timestamp hole as a gap", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: 0 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: Duration.millis(0) } }); - writeGroupWithLegacyFrames(track, 0n, [0 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0]); await flush(); - expect((await nextFrame(consumer))?.frame?.timestamp).toBe(0 as Micro); + expect((await nextFrame(consumer))?.frame?.timestamp.asMicros()).toBe(0); - writeGroupWithLegacyFrames(track, 3n, [1_000_000 as Micro]); + writeGroupWithLegacyFrames(track, 3n, [1_000_000]); await flush(); expect(await consumer.next()).toEqual({ kind: "gap", - timestamp: 0 as Micro, - duration: 1_000_000 as Micro, + timestamp: Duration.ZERO, + duration: Duration.micros(1_000_000), }); - expect(frameOf(await consumer.next()).timestamp).toBe(1_000_000 as Micro); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(1_000_000); consumer.close(); }); test("Consumer reads a shed marker group as a gap", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: 0 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: Duration.millis(0) } }); const group0 = track.createGroup(0n); group0.writeFrame({ - payload: encodeLegacy(0 as Micro), + payload: encodeLegacy(0), timestamp: Time.Timestamp.fromMicros(0), }); await flush(); - expect((await nextFrame(consumer))?.frame?.timestamp).toBe(0 as Micro); + expect((await nextFrame(consumer))?.frame?.timestamp.asMicros()).toBe(0); - writeMarkerGroup(track, 1n, 0 as Micro); - writeGroupWithLegacyFrames(track, 2n, [500 as Micro]); + writeMarkerGroup(track, 1n, 0); + writeGroupWithLegacyFrames(track, 2n, [500]); await flush(); // The zero budget sheds the marker unread, and what it declared is lost with it. - expect(await consumer.next()).toEqual({ kind: "gap", timestamp: 0 as Micro, duration: 500 as Micro }); - expect(frameOf(await consumer.next()).timestamp).toBe(500 as Micro); + expect(await consumer.next()).toEqual({ kind: "gap", timestamp: Duration.micros(0), duration: Duration.micros(500) }); + expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(500); group0.finish(); consumer.close(); @@ -1929,7 +1929,7 @@ test("Consumer yields no gap across a PTS-contiguous group id jump (Legacy)", as const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: timedLegacy, - delay: { max: 10_000 as Milli }, + delay: { max: Duration.millis(10_000) }, }); const a = track.createGroup(1_000_000n); @@ -1951,11 +1951,11 @@ test("a live video frame is delivered before its duration marker arrives", async const track = new Track.Producer("test"); const consumer = new Consumer(track.subscribe(), { format: new LegacyFormat("video"), - delay: { max: 500 as Milli }, + delay: { max: Duration.millis(500) }, }); const group = track.appendGroup(); group.writeFrame({ - payload: encodeLegacyFrame(0 as Micro, new Uint8Array([1])), + payload: encodeLegacyFrame(0, new Uint8Array([1])), timestamp: Time.Timestamp.now(), }); let delivered = false; @@ -1965,9 +1965,9 @@ test("a live video frame is delivered before its duration marker arrives", async }); await flush(); expect(delivered).toBe(true); - expect(frameOf(await read).timestamp).toBe(0 as Micro); + expect(frameOf(await read).timestamp.asMicros()).toBe(0); group.writeFrame({ - payload: encodeLegacyFrame(15_000 as Micro, new Uint8Array()), + payload: encodeLegacyFrame(15_000, new Uint8Array()), timestamp: Time.Timestamp.now(), }); group.finish(); @@ -1984,8 +1984,8 @@ test("audio discontinuity writes no duration marker", async () => { const track = new Track.Producer("test"); const subscriber = track.subscribe(); const producer = new LegacyProducer(track, new LegacyFormat("audio")); - producer.encode(new Uint8Array([1]), 0 as Micro, true); - producer.discontinuity(15_000 as Micro); + producer.encode(new Uint8Array([1]), Duration.micros(0), true); + producer.discontinuity(Duration.micros(15_000)); const group = await subscriber.recvGroup(); expect(await group?.readFrame()).toBeDefined(); expect(await group?.readFrame()).toBeUndefined(); @@ -1995,12 +1995,12 @@ test("audio discontinuity writes no duration marker", async () => { for (const code of [StreamCode.Cancel, StreamCode.Internal, StreamCode.Old, StreamCode.Evicted, StreamCode(1234)]) { test(`Consumer preserves frames and continues after group reset ${code}`, async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: 0 as Milli } }); + const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(0) } }); const error = spyOn(console, "error").mockImplementation(() => {}); try { const group = track.appendGroup(); group.writeFrame({ - payload: encodeLegacyFrame(0 as Micro, new Uint8Array([1])), + payload: encodeLegacyFrame(0, new Uint8Array([1])), timestamp: Time.Timestamp.now(), }); await flush(); @@ -2009,15 +2009,15 @@ for (const code of [StreamCode.Cancel, StreamCode.Internal, StreamCode.Old, Stre expect(frameOf(await nextFrame(consumer)).payload).toEqual(new Uint8Array([1])); const next = track.appendGroup(); next.writeFrame({ - payload: encodeLegacyFrame(1 as Micro, new Uint8Array([2])), + payload: encodeLegacyFrame(1, new Uint8Array([2])), timestamp: Time.Timestamp.now(), }); next.finish(); // The reset cut the group's tail. expect(await consumer.next()).toEqual({ kind: "gap", - timestamp: 0 as Micro, - duration: 1 as Micro, + timestamp: Duration.ZERO, + duration: Duration.micros(1), }); const resumed = frameOf(await consumer.next()); expect(resumed.payload).toEqual(new Uint8Array([2])); @@ -2087,12 +2087,12 @@ for (const end of [ const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), - delay: { max: 10_000 as Milli }, + delay: { max: Duration.millis(10_000) }, }); try { - writeGroupWithLegacyFrames(track, 0n, [0 as Micro]); + writeGroupWithLegacyFrames(track, 0n, [0]); expect(await nextFrame(consumer)).toMatchObject({ group: 0n }); - writeGroupWithLegacyFrames(track, 2n, [1_000_000 as Micro]); + writeGroupWithLegacyFrames(track, 2n, [1_000_000]); await flush(); const pending = consumer.next(); if (end) track.abort(end); @@ -2103,8 +2103,8 @@ for (const end of [ const resumed = await poll(pending); expect(resumed).not.toBe("pending"); if (resumed === "pending") return; - expect(resumed).toEqual({ kind: "gap", timestamp: 0 as Micro, duration: 1_000_000 as Micro }); - expect(await consumer.next()).toMatchObject({ kind: "frame", group: 2n, frame: { timestamp: 1_000_000 } }); + expect(resumed).toEqual({ kind: "gap", timestamp: Duration.micros(0), duration: Duration.micros(1_000_000) }); + expect(await consumer.next()).toMatchObject({ kind: "frame", group: 2n, frame: { timestamp: Duration.micros(1_000_000) } }); if (end) await expect(consumer.next()).rejects.toBe(end); else expect(await consumer.next()).toBeUndefined(); } finally { diff --git a/js/hang/src/container/consumer.ts b/js/hang/src/container/consumer.ts index dcb4913d254..bee65b4e3c6 100644 --- a/js/hang/src/container/consumer.ts +++ b/js/hang/src/container/consumer.ts @@ -1,4 +1,4 @@ -import { Instant, Micro, Milli, Nano, now } from "@moq/clock"; +import { Duration, Instant, now } from "@moq/clock"; import type * as Moq from "@moq/net"; import { Effect, type Getter, type GetterInit, getter, Once, Signal } from "@moq/signals"; import type { Format } from "./format"; @@ -58,7 +58,7 @@ export interface ConsumerProps { * covers the reach and tolerates the warmup, so the media leading up to the start is not dropped * as stale. After that, the max delay alone governs it. */ - warmup?: Milli; + warmup?: Duration; /** * The consumer this one replaces on the same path, such as the previous rendition. * @@ -81,13 +81,13 @@ export type Read = * per-frame duration that is the last frame's timestamp, one frame early. `duration` runs to * where the next item resumes, so it also covers any declared pause in between. */ - | { kind: "gap"; timestamp: Micro; duration: Micro } + | { kind: "gap"; timestamp: Duration; duration: Duration } /** * The publisher declared that its media stops at `end`: it paused, switched source, or finished. * Frames that follow from the same `group` are the stopped encoder's final packets (an audio * codec's drain), whose output at or past `end` is padding. The next group starts fresh. */ - | { kind: "end"; group: bigint; end: Micro }; + | { kind: "end"; group: bigint; end: Duration }; // The default max buffer: one group at the transport's size cap. Mirrors Rust's. const DEFAULT_MAX_BUFFER = 32 * 1024 * 1024; @@ -107,10 +107,11 @@ interface Group { empty: boolean; // no wire frame was published; empty groups mean nothing media: boolean; // a decodable (non-marker) frame was buffered bare?: boolean; // a data track's marker group: one object with no bytes - start?: Micro; // First decoded timestamp - minMedia?: Micro; // Lowest decodable timestamp - latest?: Micro; // The timestamp of the latest known frame - end?: Micro; // The furthest presentation point so far, i.e. max(timestamp + duration) + // Timestamps in microseconds, kept as numbers since every frame updates them. + start?: number; // First decoded timestamp + minMedia?: number; // Lowest decodable timestamp + latest?: number; // The timestamp of the latest known frame + end?: number; // The furthest presentation point so far, i.e. max(timestamp + duration) fault?: Error; // The payload that failed to decode, an error after the buffered frames are delivered. index: number; // Media frames decoded so far: the first is a keyframe by protocol invariant charged: number; // What this group holds against the max buffer @@ -128,7 +129,7 @@ interface Spans { // to microseconds independently, so a genuinely contiguous boundary can be off by ~1µs (seen on 48kHz // audio). A real missing group spans ~one group duration (orders of magnitude larger), so 1ms cleanly // separates rounding noise from an actual gap. -const CONTIGUITY_TOLERANCE = Micro.fromMilli(1 as Milli); +const CONTIGUITY_TOLERANCE = 1000; /** * True when `nextStart` continues the timeline that ends at `end`: it lands at or before `end`, @@ -139,7 +140,7 @@ const CONTIGUITY_TOLERANCE = Micro.fromMilli(1 as Milli); * timeline, a start past `end` beyond the tolerance is a gap. Group starts are validated * separately; an overlapping endpoint is not a rewind. */ -function ptsContiguous(end: Micro | undefined, nextStart: Micro | undefined): boolean { +function ptsContiguous(end: number | undefined, nextStart: number | undefined): boolean { return end !== undefined && nextStart !== undefined && nextStart <= end + CONTIGUITY_TOLERANCE; } @@ -152,13 +153,13 @@ function ptsContiguous(end: Micro | undefined, nextStart: Micro | undefined): bo function continues(prev: Group, next: Group | undefined): next is Group { if (next === undefined) return false; return ( - next.consumer.sequence === prev.consumer.sequence + 1n || ptsContiguous(prev.end, next.frames.at(0)?.timestamp) + next.consumer.sequence === prev.consumer.sequence + 1n || ptsContiguous(prev.end, next.frames.at(0)?.timestamp.asMicros()) ); } // The max delay in microseconds, infinite when unlimited. function maxMicros(delay: Moq.Track.Delay): number { - return delay.max === null ? Number.POSITIVE_INFINITY : Micro.fromMilli(delay.max ?? Milli.zero); + return delay.max === null ? Number.POSITIVE_INFINITY : (delay.max?.asMicros() ?? 0); } /** @@ -173,7 +174,7 @@ export class Consumer { #delay: Getter; #maxBuffer: number; // How much further than the min delay the start reaches, and the age skip tolerates while warming. - #warmup: Milli; + #warmup: Duration; // The start may still wait for a group covering the reach, until that wait ends for good. #starting = true; // When the newest group had landed as the first one arrived, once the start waits. @@ -182,7 +183,7 @@ export class Consumer { #target?: number; // Where the warming ends: the warmup past the first frame read, or past the start's target when // that is later. Undefined before the first frame. - #warmed?: Micro; + #warmed?: number; // What the buffered groups hold, against the max buffer. #used = 0; // Group watchers and the track loop parked on a full max buffer. @@ -197,7 +198,7 @@ export class Consumer { // Presentation end (max PTS + duration) of the group we most recently advanced past, so next()'s // promotion guard can tell a timeline-continuous next group from one sitting after a gap. // Written only by #pass, which every move past a group goes through. - #presentedEnd?: Micro; + #presentedEnd?: number; // Group of the last media frame next() returned, so an endpoint after it reads as that frame's // duration rather than a declared stop. #mediaGroup?: bigint; @@ -205,13 +206,13 @@ export class Consumer { #lost = false; // The furthest presentation point read so far: max(timestamp + duration), endpoints included. // Undefined until the first item, so a loss before it is no gap. - #edge?: Micro; + #edge?: number; // The item a gap was returned ahead of. #next?: Read; // The first media timestamp of the latest delivered group, and its predecessor's start. // Endpoints and later frames can overlap the next group without moving this floor. - #start?: { group: bigint; timestamp: Micro }; - #floor?: Micro; + #start?: { group: bigint; timestamp: number }; + #floor?: number; // The error that ended the reader, the first in delivery order: a decode failure or a rewind. #error?: Error; @@ -223,14 +224,14 @@ export class Consumer { readonly buffered: Getter = this.#buffered; #jitter: Jitter; - #spread: Signal; + #spread: Signal; /** * How much buffer late arrivals need, measured as frames come off the transport. * * The measured term of doc/concept/audio-jitter.md, excluding the codec frame and any advertised * floor. Starts at the predecessor's estimate, or the cold-start estimate without one. */ - readonly spread: Getter; + readonly spread: Getter; // The newest group opened by a declared end, until a later group's first frame tells the jitter // estimator the silence is over. Not at the marker itself: the stopped encoder's final packets may // follow it in its own group, and they belong to the speech before the silence. @@ -246,9 +247,9 @@ export class Consumer { this.#format = props.format; this.#delay = getter(props.delay ?? {}); this.#maxBuffer = props.maxBuffer ?? DEFAULT_MAX_BUFFER; - this.#warmup = props.warmup ?? Milli.zero; + this.#warmup = props.warmup ?? Duration.ZERO; this.#jitter = props.predecessor ? props.predecessor.#jitter.fork() : new Jitter(); - this.#spread = new Signal(this.#jitter.measured); + this.#spread = new Signal(Duration.millis(this.#jitter.measured)); this.spread = this.#spread; this.#signals.spawn(this.#run.bind(this)); @@ -321,8 +322,8 @@ export class Consumer { // Each group is late from the earliest arrival among it and the groups past it. A drained // backlog comes in sequence order, not arrival order, so an arrival can lower those below it. const next = this.#groups.at(index); - if (next && next.late < group.late) group.late = next.late; - for (let i = index - 1; i >= 0 && this.#groups[i].late > group.late; i--) + if (next?.late.lt(group.late)) group.late = next.late; + for (let i = index - 1; i >= 0 && this.#groups[i].late.gt(group.late); i--) this.#groups[i].late = group.late; this.#groups.splice(index, 0, group); // Group overhead alone can fill the max buffer, past which next() moves on from a stalled head. @@ -424,7 +425,8 @@ export class Consumer { group.empty = false; // When the frame landed, not when it was decoded: a frame the max buffer left in the transport // would otherwise count the consumer's own wait as network jitter. - const arrival = Nano.toMilli(Nano(wire.arrived ?? now())); + const arrival = wire.arrived ?? now(); + const arrived = arrival.since(Instant.ZERO).asMillis(); // A malformed payload is not loss: it ends the reader where it sits, rather than truncating the group. let decoded: Frame[]; @@ -459,8 +461,9 @@ export class Consumer { this.#jitter.end(); this.#declared = undefined; } - this.#jitter.observe(arrival, Milli.fromMicro(sample.timestamp)); - this.#spread.set(this.#jitter.measured); + this.#jitter.observe(arrived, sample.timestamp.asMillis()); + const spread = this.#jitter.measured; + if (spread !== this.#spread.peek().asMillis()) this.#spread.set(Duration.millis(spread)); } else if (!group.media) { // Only a marker ahead of any media declares an end; one after it is a frame's endpoint. this.#declare(group); @@ -480,26 +483,27 @@ export class Consumer { duration: sample.duration, }; + const at = frame.timestamp.asMicros(); if (!marker) { group.index++; group.media = true; - if (group.minMedia === undefined || frame.timestamp < group.minMedia) { - group.minMedia = frame.timestamp; + if (group.minMedia === undefined || at < group.minMedia) { + group.minMedia = at; } } - group.start ??= frame.timestamp; + group.start ??= at; group.frames.push(frame); const cost = FRAME_COST + frame.payload.byteLength; group.costs.push(cost); this.#charge(group, cost); views += frame.payload.byteLength; - if (group.latest === undefined || frame.timestamp > group.latest) { - group.latest = frame.timestamp; + if (group.latest === undefined || at > group.latest) { + group.latest = at; } - const end = (frame.timestamp + (frame.duration ?? 0)) as Micro; + const end = at + (frame.duration?.asMicros() ?? 0); if (group.end === undefined || end > group.end) { group.end = end; } @@ -554,7 +558,7 @@ export class Consumer { for (const group of this.#groups) { if (group.latest === undefined) continue; - const frame = group.frames.at(0)?.timestamp ?? group.latest; + const frame = group.frames.at(0)?.timestamp.asMicros() ?? group.latest; if (min === undefined || frame < min) min = frame; if (max === undefined || group.latest > max) max = group.latest; } @@ -599,7 +603,7 @@ export class Consumer { this.#pass(first, this.#groups[0]?.consumer.sequence); const next = this.#groups[0]; - const nextStart = next?.frames.at(0)?.timestamp ?? next?.end; + const nextStart = next?.frames.at(0)?.timestamp.asMicros() ?? next?.end; const marker = !first.empty && !first.media; // Unread media is thrown away, and `first.end` counts it, so contiguity alone would hide it. // A trailing endpoint carries no media, so leaving it unread discards nothing. @@ -640,7 +644,7 @@ export class Consumer { for (let i = count - 1; i >= 0; i--) { const group = this.#groups[i]; if (group.latest !== undefined) { - const frame = group.frames.at(0)?.timestamp ?? group.latest; + const frame = group.frames.at(0)?.timestamp.asMicros() ?? group.latest; if (min === undefined || frame < min) min = frame; if (max === undefined || group.latest > max) max = group.latest; } @@ -662,7 +666,7 @@ export class Consumer { if (this.#ended(active) !== undefined || active.frames.length > 0 || active.end === undefined) return false; const next = this.#groups[1]; - const nextStart = next?.frames.at(0)?.timestamp; + const nextStart = next?.frames.at(0)?.timestamp.asMicros(); if (!next || nextStart === undefined || active.end < nextStart) return false; this.#groups.shift(); @@ -696,7 +700,7 @@ export class Consumer { ); // Still open, so its tail is lost unless the next group picks up where it ended, which nothing // proves before its start is read. A marker group stops the timeline, so moving past one loses it. - const nextStart = next.frames.at(0)?.timestamp; + const nextStart = next.frames.at(0)?.timestamp.asMicros(); const marker = !head.empty && !head.media; if (marker || !ptsContiguous(head.end ?? this.#presentedEnd, nextStart)) this.#lost = true; this.#pass(head, next.consumer.sequence); @@ -850,13 +854,13 @@ export class Consumer { this.#hole = head.late; // Joining at the first arrival leaves no hole to wait for; a floor does. const startup = this.#start === undefined && !this.#floored; - const contiguous = ptsContiguous(this.#presentedEnd, head.frames.at(0)?.timestamp); + const contiguous = ptsContiguous(this.#presentedEnd, head.frames.at(0)?.timestamp.asMicros()); const empty = head.empty && head.consumer.done; const maxDelay = maxMicros(this.#delay.peek()); const bound = this.#groups.find((group) => group.start !== undefined)?.start; const edge = this.#liveEdge(); const aged = bound !== undefined && edge !== undefined && edge - bound >= maxDelay; - const elapsed = Instant.durationSince(now(), this.#hole) >= maxDelay * 1000; + const elapsed = now().since(this.#hole).asMicros() >= maxDelay; // The ranges ask for nothing in between, so nothing there is owed. const next = this.#track.nextInRange(this.#active); const excluded = next === undefined || next >= head.consumer.sequence; @@ -893,7 +897,7 @@ export class Consumer { this.#updateBuffered(); // A trailing endpoint is the last frame's duration: it moves the edge, nothing else. if (seq === this.#mediaGroup) { - this.#advance(end); + this.#advance(end.asMicros()); continue; } return this.#emit({ kind: "end", group: seq, end }); @@ -901,14 +905,13 @@ export class Consumer { this.#mediaGroup = seq; // A group covering the target began before it, so the reader warms until the target too. - this.#warmed ??= Micro( - Math.max(frame.timestamp, this.#target ?? frame.timestamp) + Micro.fromMilli(this.#warmup), - ); + const at = frame.timestamp.asMicros(); + this.#warmed ??= Math.max(at, this.#target ?? at) + this.#warmup.asMicros(); if (this.#start === undefined || seq > this.#start.group) { this.#floor = this.#start?.timestamp; - this.#start = { group: seq, timestamp: frame.timestamp }; + this.#start = { group: seq, timestamp: at }; } - if (this.#floor !== undefined && frame.timestamp < this.#floor) { + if (this.#floor !== undefined && at < this.#floor) { this.#abort(new Error("frame timestamp is below the previous group start")); throw this.#error; } @@ -947,7 +950,7 @@ export class Consumer { // A data track's marker carries no timestamp, so it ends where this reader got to. // Before the first item there is nothing to end. if (head.bare && !truncated && this.#edge !== undefined) { - return this.#emit({ kind: "end", group: seq, end: this.#edge }); + return this.#emit({ kind: "end", group: seq, end: Duration.micros(this.#edge) }); } continue; } @@ -976,8 +979,7 @@ export class Consumer { // The start waits out its reach, and a hole the max delay, which an unlimited one never does. const budget = starting === undefined ? maxMicros(delay) : this.#reach(delay); if (!Number.isFinite(budget)) return; - const elapsed = Instant.durationSince(now(), since); - effect.timer(() => this.#notify?.(), Nano(Math.max(0, budget * 1000 - elapsed))); + effect.timer(() => this.#notify?.(), Duration.micros(budget).saturatingSub(now().since(since))); }); } @@ -999,7 +1001,7 @@ export class Consumer { // How far behind the live edge the start reaches, in microseconds: the min delay plus the warmup. // The publisher serves nothing older than the max delay, so a min delay past it reaches no further. #reach(delay: Moq.Track.Delay): number { - return Math.min(Micro.fromMilli(delay.min ?? Milli.zero), maxMicros(delay)) + Micro.fromMilli(this.#warmup); + return Math.min(delay.min?.asMicros() ?? 0, maxMicros(delay)) + this.#warmup.asMicros(); } // While the start still waits for a group covering the live edge less the min delay and the @@ -1023,7 +1025,7 @@ export class Consumer { // Nothing earlier can arrive or be held. const lowest = this.#groups[0].consumer.sequence === 0n; // Wall time: the newest group landed a whole reach ago. - const elapsed = Instant.durationSince(now(), this.#anchor) >= reach * 1000; + const elapsed = now().since(this.#anchor).asMicros() >= reach; if (ended || this.#full() || target === undefined || covered || lowest || elapsed) { this.#started(); this.#target = target; @@ -1062,7 +1064,7 @@ export class Consumer { // the max delay, plus the warmup while the reader warms. #ageBudget(): number { const maxDelay = maxMicros(this.#delay.peek()); - return this.#warming() ? maxDelay + Micro.fromMilli(this.#warmup) : maxDelay; + return this.#warming() ? maxDelay + this.#warmup.asMicros() : maxDelay; } // The reader has not yet read past the start's target and the warmup past its first frame. @@ -1072,20 +1074,20 @@ export class Consumer { // Return `read`, or a gap ahead of it when media went missing after an earlier item. #emit(read: Exclude): Read { - const resume = read.kind === "frame" ? read.frame.timestamp : read.end; + const resume = (read.kind === "frame" ? read.frame.timestamp : read.end).asMicros(); const edge = this.#edge; const lost = this.#lost; this.#lost = false; - this.#advance(read.kind === "frame" ? Micro(resume + (read.frame.duration ?? Micro.zero)) : resume); + this.#advance(read.kind === "frame" ? resume + (read.frame.duration?.asMicros() ?? 0) : resume); if (!lost || edge === undefined) return read; // A next group may start before the edge (an overlapping endpoint), so the span bottoms out at zero. - const timestamp = Micro(Math.min(edge, resume)); + const timestamp = Math.min(edge, resume); this.#next = read; - return { kind: "gap", timestamp, duration: Micro(resume - timestamp) }; + return { kind: "gap", timestamp: Duration.micros(timestamp), duration: Duration.micros(resume - timestamp) }; } - #advance(end: Micro): void { + #advance(end: number): void { if (this.#edge === undefined || end > this.#edge) this.#edge = end; } @@ -1098,13 +1100,13 @@ export class Consumer { const first = group.frames.at(0); if (!first || group.latest === undefined) continue; - const start = Milli.fromMicro(first.timestamp); - const end = Milli.fromMicro(group.latest); + const start = first.timestamp; + const end = Duration.micros(group.latest); const last = ranges.at(-1); const contiguous = prev?.consumer.done && prev.consumer.sequence + 1n === group.consumer.sequence; - if (last && (last.end >= start || contiguous)) { - last.end = Milli(Math.max(last.end, end)); + if (last && (last.end.ge(start) || contiguous)) { + last.end = last.end.max(end); } else { ranges.push({ start, end }); } diff --git a/js/hang/src/container/consumer.warmup.test.ts b/js/hang/src/container/consumer.warmup.test.ts index ec3f3b3f2b1..9a133c3b77d 100644 --- a/js/hang/src/container/consumer.warmup.test.ts +++ b/js/hang/src/container/consumer.warmup.test.ts @@ -1,5 +1,5 @@ import { expect, onTestFinished, spyOn, test } from "bun:test"; -import { Manual, Micro, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { type Group, Time, Track } from "@moq/net"; import { Consumer, type Read } from "./consumer.ts"; import { encodeFrame, Format } from "./legacy.ts"; @@ -11,13 +11,13 @@ function setup(delay = BUDGET, warmup = 0, min = delay, max: number | null = del const clock = new Manual(); const installed = clock.install(); // Drain the in-memory readers and their continuations without moving time. - const flush = () => clock.advance(Nano.zero); + const flush = () => clock.advance(Duration.ZERO); const track = new Track.Producer("video"); // A null max delay sets no subscriber limit; an omitted one is zero. - const consumer = new Consumer(track.subscribe({ delay: { max: max === null ? null : Milli(max + warmup) } }), { + const consumer = new Consumer(track.subscribe({ delay: { max: max === null ? null : Duration.millis(max + warmup) } }), { format: new Format("video"), - delay: { min: Milli(min), max: max === null ? null : Milli(max) }, - warmup: Milli(warmup), + delay: { min: Duration.millis(min), max: max === null ? null : Duration.millis(max) }, + warmup: Duration.millis(warmup), }); const results: Read[] = []; const warn = spyOn(console, "warn").mockImplementation(() => {}); @@ -44,12 +44,12 @@ function setup(delay = BUDGET, warmup = 0, min = delay, max: number | null = del // Each frame as "@<µs>". function frames(results: Read[]): string[] { - return results.flatMap((read) => (read.kind === "frame" ? [`${read.group}@${read.frame.timestamp}`] : [])); + return results.flatMap((read) => (read.kind === "frame" ? [`${read.group}@${read.frame.timestamp.asMicros()}`] : [])); } function write(group: Group.Producer, timestamp: number) { group.writeFrame({ - payload: encodeFrame(new Uint8Array([1]), Micro(timestamp)), + payload: encodeFrame(new Uint8Array([1]), Duration.micros(timestamp)), timestamp: Time.Timestamp.now(), }); } @@ -99,10 +99,10 @@ test("a quiet track starts within one reach", async () => { const { clock, track, results, flush } = setup(200, 300); group(track, 5n, [5_000_000]); await flush(); - await clock.advance(Nano.fromMilli(Milli(BUDGET - 50))); + await clock.advance(Duration.millis(BUDGET - 50)); expect(frames(results)).toEqual([]); - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); expect(frames(results)).toEqual(["5@5000000"]); }); @@ -145,10 +145,10 @@ test("a min delay past the max delay reaches only the max delay", async () => { const { clock, track, results, flush } = setup(200, 0, 2_000); group(track, 5n, [5_000_000]); await flush(); - await clock.advance(Nano.fromMilli(Milli(150))); + await clock.advance(Duration.millis(150)); expect(frames(results)).toEqual([]); - await clock.advance(Nano.fromMilli(Milli(50))); + await clock.advance(Duration.millis(50)); expect(frames(results)).toEqual(["5@5000000"]); }); diff --git a/js/hang/src/container/format.ts b/js/hang/src/container/format.ts index 57ef80c22f1..16ce122a8d9 100644 --- a/js/hang/src/container/format.ts +++ b/js/hang/src/container/format.ts @@ -1,4 +1,4 @@ -import type { Micro } from "@moq/clock"; +import type { Duration } from "@moq/clock"; import type { Time } from "@moq/net"; import type { Frame } from "./types"; @@ -9,5 +9,5 @@ export interface Format { /** Parse one MoQ frame's payload, given its moq-net timestamp (absent on an untimed track), into decoded media frames. On a data track no frames means the discontinuity marker, so a format returns none only for an object with no bytes. */ decode(payload: Uint8Array, timestamp: Time.Timestamp | undefined): Frame[]; /** Return the endpoint timestamp carried by empty-payload metadata. */ - end?(frame: Frame): Micro | undefined; + end?(frame: Frame): Duration | undefined; } diff --git a/js/hang/src/container/jitter.test.ts b/js/hang/src/container/jitter.test.ts index c346af8d378..534e329448e 100644 --- a/js/hang/src/container/jitter.test.ts +++ b/js/hang/src/container/jitter.test.ts @@ -2,7 +2,6 @@ import { describe, expect, it } from "bun:test"; import { readdirSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; -import type { Milli } from "@moq/clock"; import { type Entry, History, Jitter } from "./jitter"; // The conformance corpus beside doc/concept/audio-jitter.md, read directly so this is graded @@ -57,7 +56,7 @@ describe("audio jitter conformance", () => { let current: number | undefined; for (let i = 0; i < c.arrival.length; i++) { if (ends.has(i)) jitter.end(); - jitter.observe(c.arrival[i] as Milli, c.media[i] as Milli); + jitter.observe(c.arrival[i], c.media[i]); const value = target(jitter, c); const listed = expected.get(i); if (listed !== undefined) { @@ -74,18 +73,18 @@ describe("audio jitter conformance", () => { describe("Jitter", () => { it("starts at the prior's 95th percentile", () => { - expect(new Jitter().measured).toBe(100 as Milli); + expect(new Jitter().measured).toBe(100); }); it("is not moved by a stale frame ahead of the live edge", () => { // The #3517 regression: one frame from a stale group, then the live edge 14.5s of media later, // then evenly paced audio with no real jitter. The jump must not read as a delay or a frame. const jitter = new Jitter(); - jitter.observe(0 as Milli, 0 as Milli); + jitter.observe(0, 0); for (let i = 0; i < 500; i++) { - jitter.observe((10 + i * 20) as Milli, (14_500 + i * 20) as Milli); + jitter.observe((10 + i * 20), (14_500 + i * 20)); } - expect(jitter.measured).toBe(20 as Milli); + expect(jitter.measured).toBe(20); }); it("ignores an end before any observation", () => { @@ -93,9 +92,9 @@ describe("Jitter", () => { // excuse the first unexplained gap. const jitter = new Jitter(); jitter.end(); - for (let i = 0; i < 500; i++) jitter.observe((50 + i * 20) as Milli, (i * 20) as Milli); + for (let i = 0; i < 500; i++) jitter.observe((50 + i * 20), (i * 20)); const settled = jitter.measured; - jitter.observe((50 + 500 * 20 + 30_000) as Milli, (500 * 20 + 30_000) as Milli); + jitter.observe((50 + 500 * 20 + 30_000), (500 * 20 + 30_000)); expect(jitter.measured).toBeGreaterThan(settled); }); @@ -104,8 +103,8 @@ describe("Jitter", () => { const near = new Jitter(); const far = new Jitter(); for (let i = 0; i < 500; i++) { - near.observe((10 + i * 20) as Milli, (i * 20) as Milli); - far.observe((2000 + i * 20) as Milli, (i * 20) as Milli); + near.observe((10 + i * 20), (i * 20)); + far.observe((2000 + i * 20), (i * 20)); } expect(far.measured).toBe(near.measured); }); @@ -114,10 +113,10 @@ describe("Jitter", () => { // A path where every tenth frame lands 300ms late. const warm = new Jitter(); for (let i = 0; i < 500; i++) { - warm.observe((i * 20 + (i % 10 === 0 ? 300 : 0)) as Milli, (i * 20) as Milli); + warm.observe((i * 20 + (i % 10 === 0 ? 300 : 0)), (i * 20)); } const learned = warm.measured; - expect(learned).toBeGreaterThan(100 as Milli); + expect(learned).toBeGreaterThan(100); const fork = warm.fork(); expect(fork.measured).toBe(learned); @@ -125,7 +124,7 @@ describe("Jitter", () => { // The replacement opens with a backlog: older media arriving at once, long after the warm // track's frames. Measured against the warm track's arrivals it would read as seconds late. for (let i = 0; i < 100; i++) - fork.observe((20_000 + Math.floor(i / 50) * 1000) as Milli, (8000 + i * 20) as Milli); + fork.observe((20_000 + Math.floor(i / 50) * 1000), (8000 + i * 20)); expect(fork.measured).toBeLessThanOrEqual(learned); expect(warm.measured).toBe(learned); }); diff --git a/js/hang/src/container/jitter.ts b/js/hang/src/container/jitter.ts index 257beda9c2d..5014b9db4a3 100644 --- a/js/hang/src/container/jitter.ts +++ b/js/hang/src/container/jitter.ts @@ -1,4 +1,3 @@ -import type { Milli } from "@moq/clock"; // Implements the estimator in doc/concept/audio-jitter.md, which is normative. The design and // every constant come from WebRTC NetEq's underrun optimizer; this is written from the document, @@ -68,8 +67,8 @@ export class Jitter { /** How much of the histogram is still the prior's rather than evidence. */ #prior = 1; - /** Fold one frame in: `arrival` on the receiver's monotonic clock, `media` its timestamp. */ - observe(arrival: Milli, media: Milli): void { + /** Fold one frame in, in milliseconds: `arrival` on the receiver's monotonic clock, `media` its timestamp. */ + observe(arrival: number, media: number): void { // A reordered frame is measured but never joins the window: it arrived after a newer frame, // so it can never be the fastest, and a later frame must not be measured against it. if (media > this.#newest) { @@ -140,14 +139,14 @@ export class Jitter { return fork; } - /** The measured term: the upper edge of the bucket holding the 95th percentile. */ - get measured(): Milli { + /** The measured term in milliseconds: the upper edge of the bucket holding the 95th percentile. */ + get measured(): number { let cumulative = 0; for (let i = 0; i < BUCKETS; i++) { cumulative += this.#histogram[i]; - if (cumulative > QUANTILE) return ((i + 1) * BUCKET) as Milli; + if (cumulative > QUANTILE) return (i + 1) * BUCKET; } - return (BUCKETS * BUCKET) as Milli; + return BUCKETS * BUCKET; } // Evidence decays by `FORGET` and the prior holds the rest, of which an observation takes up to diff --git a/js/hang/src/container/legacy.ts b/js/hang/src/container/legacy.ts index dd2bc91c7cf..667c1ec77ea 100644 --- a/js/hang/src/container/legacy.ts +++ b/js/hang/src/container/legacy.ts @@ -3,7 +3,7 @@ import { Time } from "@moq/net"; export type { BufferedRange, BufferedRanges, Frame } from "./types"; -import type { Micro } from "@moq/clock"; +import { Duration } from "@moq/clock"; import type { AudioConfig, VideoConfig } from "../catalog"; import type { Format as ContainerFormat } from "./format"; import type { Frame } from "./types"; @@ -19,13 +19,13 @@ export class Format implements ContainerFormat { } /** Write the final video frame's end timestamp before the group closes. */ - finishGroup(group: Moq.Group.Producer, end?: Micro) { + finishGroup(group: Moq.Group.Producer, end?: Duration) { if (this.kind !== "video" || end === undefined) return; - group.writeFrame({ payload: encodeFrame(new Uint8Array(), end), timestamp: Time.Timestamp.fromMicros(end) }); + group.writeFrame({ payload: encodeFrame(new Uint8Array(), end), timestamp: Time.Timestamp.fromMicros(micros(end)) }); } /** Return the video-frame or audio-source endpoint for an empty codec payload. */ - end(frame: Frame): Micro | undefined { + end(frame: Frame): Duration | undefined { return this.kind !== "data" && frame.payload.byteLength === 0 ? frame.timestamp : undefined; } @@ -33,7 +33,7 @@ export class Format implements ContainerFormat { decode(frame: Uint8Array): Frame[] { if (this.kind === "data" && frame.byteLength === 0) return []; const [timestamp, data] = Moq.Varint.decode(frame); - return [{ payload: data, timestamp: timestamp as Micro, keyframe: false }]; + return [{ payload: data, timestamp: Duration.micros(timestamp), keyframe: false }]; } } @@ -46,8 +46,8 @@ export interface Source { } /** Encode a frame as a timestamp varint followed by the payload bytes. */ -export function encodeFrame(source: Uint8Array | Source, timestamp: Micro): Uint8Array { - const timestampBytes = Moq.Varint.encode(timestamp); +export function encodeFrame(source: Uint8Array | Source, timestamp: Duration): Uint8Array { + const timestampBytes = Moq.Varint.encode(micros(timestamp)); const data = new Uint8Array(timestampBytes.byteLength + source.byteLength); data.set(timestampBytes, 0); @@ -60,22 +60,28 @@ export function encodeFrame(source: Uint8Array | Source, timestamp: Micro): Uint return data; } +// The wire carries whole microseconds, rounded down as moq-net's timestamps are. +function micros(timestamp: Duration): number { + return Math.floor(timestamp.asMicros()); +} + /** Writes legacy-container frames into a MoQ track, starting a new group on each keyframe. */ export class Producer { #track: Moq.Track.Producer; #format: Format; - #previous?: Micro; + // Timestamps in whole microseconds. + #previous?: number; #reordered = false; #group?: Moq.Group.Producer; // The newest timestamp written in the current group, which estimates its end. - #end?: Micro; + #end?: number; // Furthest timestamp in finished groups, used only for discontinuity markers. - #liveEdge?: Micro; + #liveEdge?: number; // The current group start and the previous group start, which bounds its frames. - #start?: Micro; - #floor?: Micro; + #start?: number; + #floor?: number; // Gap between consecutive timestamps, used to close the last group when no successor exists. - #interval?: Micro; + #interval?: number; // A discontinuity's marker is the newest group, so another one would say nothing new. #marked = false; @@ -86,7 +92,8 @@ export class Producer { } /** Encode and append a frame; a keyframe starts a new group. Throws if the first frame is not a keyframe, a group start goes backwards, or a frame is below the previous group start. */ - encode(data: Uint8Array | Source, timestamp: Micro, keyframe: boolean) { + encode(data: Uint8Array | Source, pts: Duration, keyframe: boolean) { + const timestamp = micros(pts); const floor = keyframe ? this.#start : this.#floor; if (floor !== undefined && timestamp < floor) { throw new Error("frame timestamp is below the previous group start"); @@ -104,13 +111,13 @@ export class Producer { } this.#group?.writeFrame({ - payload: encodeFrame(data, timestamp), + payload: encodeFrame(data, pts), timestamp: Time.Timestamp.fromMicros(timestamp), }); this.#reordered ||= this.#previous !== undefined && timestamp < this.#previous; if (this.#previous !== undefined && timestamp > this.#previous) { - const delta = (timestamp - this.#previous) as Micro; + const delta = timestamp - this.#previous; this.#interval = delta; } this.#previous = timestamp; @@ -132,7 +139,8 @@ export class Producer { * object with no bytes at all. No marker is written until a frame follows the last one. Throws if * `end` precedes the last video frame. */ - discontinuity(end?: Micro) { + discontinuity(endpoint?: Duration) { + const end = endpoint === undefined ? undefined : micros(endpoint); // Nothing is measured across the break, so a missing end has no cadence to estimate from. // An explicit end keeps the cadence until #close validates it, in case it throws. if (end === undefined) this.#interval = undefined; @@ -143,16 +151,16 @@ export class Producer { const group = this.#track.appendGroup(); group.writeFrame({ - payload: this.#format.kind === "data" ? new Uint8Array() : encodeFrame(new Uint8Array(), timestamp), + payload: this.#format.kind === "data" ? new Uint8Array() : encodeFrame(new Uint8Array(), Duration.micros(timestamp)), timestamp: Time.Timestamp.fromMicros(timestamp), }); group.finish(); - this.#liveEdge = this.#liveEdge === undefined ? timestamp : (Math.max(this.#liveEdge, timestamp) as Micro); + this.#liveEdge = this.#liveEdge === undefined ? timestamp : Math.max(this.#liveEdge, timestamp); this.#marked = true; } // Flush and close the current group at the supplied or estimated end timestamp. - #close(end?: Micro) { + #close(end?: number) { if (!this.#group) return; if ( this.#format.kind === "video" && @@ -165,14 +173,14 @@ export class Producer { } end ??= this.#end !== undefined && this.#interval !== undefined - ? ((this.#end + this.#interval) as Micro) + ? this.#end + this.#interval : undefined; // A presentation endpoint cannot bound the decode-order tail after reordering. - this.#format.finishGroup(this.#group, this.#reordered ? undefined : end); + this.#format.finishGroup(this.#group, this.#reordered || end === undefined ? undefined : Duration.micros(end)); this.#group.finish(); this.#group = undefined; if (this.#end !== undefined) { - this.#liveEdge = this.#liveEdge === undefined ? this.#end : (Math.max(this.#liveEdge, this.#end) as Micro); + this.#liveEdge = this.#liveEdge === undefined ? this.#end : Math.max(this.#liveEdge, this.#end); } this.#end = undefined; this.#previous = undefined; diff --git a/js/hang/src/container/track.test.ts b/js/hang/src/container/track.test.ts index f0523477a4d..a72d8667769 100644 --- a/js/hang/src/container/track.test.ts +++ b/js/hang/src/container/track.test.ts @@ -1,20 +1,20 @@ import { expect, test } from "bun:test"; -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { Time, Track } from "@moq/net"; import { MAX_AGE, trackInfo } from "./track"; test("trackInfo declares the media max age, null is unlimited, and a value is kept", async () => { - expect(MAX_AGE).toBe(Milli(30_000)); + expect(MAX_AGE).toEqual(Duration.millis(30_000)); const omitted = trackInfo({ priority: 1 }); expect(omitted).toEqual({ timescale: Time.Timescale.MICRO, maxAge: MAX_AGE, priority: 1 }); expect(trackInfo({ priority: 1, maxAge: undefined }).maxAge).toBe(MAX_AGE); expect(trackInfo({ priority: 1, maxAge: null }).maxAge).toBeNull(); - expect(trackInfo({ priority: 1, maxAge: Milli(5000) }).maxAge).toBe(Milli(5000)); + expect(trackInfo({ priority: 1, maxAge: Duration.millis(5000) }).maxAge).toEqual(Duration.millis(5000)); // What a producer accepting each commits. - const committed = async (maxAge?: Milli | null) => + const committed = async (maxAge?: Duration | null) => (await new Track.Producer("media").accept(trackInfo({ priority: 1, maxAge })).info()).maxAge; - expect(await committed()).toBe(Milli(30_000)); + expect(await committed()).toEqual(Duration.millis(30_000)); expect(await committed(null)).toBeUndefined(); - expect(await committed(Milli(5000))).toBe(Milli(5000)); + expect(await committed(Duration.millis(5000))).toEqual(Duration.millis(5000)); }); diff --git a/js/hang/src/container/track.ts b/js/hang/src/container/track.ts index be03b97e7da..59e0ad90eab 100644 --- a/js/hang/src/container/track.ts +++ b/js/hang/src/container/track.ts @@ -7,7 +7,7 @@ * @module */ -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { Time, type Track } from "@moq/net"; /** @@ -19,7 +19,7 @@ import { Time, type Track } from "@moq/net"; * target durations behind live, and a recorder absorbs reordering. `@moq/net`'s default of zero * would leave those addressing groups that are already stale. */ -export const MAX_AGE = Milli(30_000); +export const MAX_AGE = Duration.millis(30_000); /** * Track properties for a track carrying media frames, for `Request.accept`. @@ -58,5 +58,5 @@ export type TrackInfoOptions = { * and lowering it does not reduce latency: it only shortens how far back a fetch can reach. * It keeps no bytes either; the cache decides how long a group's payload stays held. */ - maxAge?: Milli | null; + maxAge?: Duration | null; }; diff --git a/js/hang/src/container/types.ts b/js/hang/src/container/types.ts index e6d7edd3f4c..69eb6e42bf6 100644 --- a/js/hang/src/container/types.ts +++ b/js/hang/src/container/types.ts @@ -1,11 +1,11 @@ -import { type Micro, Milli } from "@moq/clock"; +import type { Duration, Instant } from "@moq/clock"; /** A decoded media frame: codec payload plus its presentation timestamp and keyframe flag. */ export interface Frame { /** The codec bitstream payload. */ payload: Uint8Array; - /** Presentation timestamp in microseconds. */ - timestamp: Micro; + /** Presentation timestamp: how far into the media timeline this frame starts. */ + timestamp: Duration; /** Whether this frame opens a group, or is a video keyframe. Audio carries it only on a group start. */ keyframe: boolean; @@ -16,21 +16,21 @@ export interface Frame { * so it can advance to a newer group as soon as the gap is covered instead of * waiting out the max delay budget. */ - duration?: Micro; + duration?: Duration; } /** A media frame carrying its local transport ingress time. */ export interface ReceivedFrame extends Frame { - /** Monotonic ingress time in milliseconds, before reordering or decoder backpressure. */ - arrival: Milli; + /** When the frame came off the transport, before reordering or decoder backpressure. */ + arrival: Instant; } -/** A contiguous span of buffered media, in milliseconds. */ +/** A contiguous span of buffered media, on the presentation timeline. */ export interface BufferedRange { - /** Start of the range in milliseconds. */ - start: Milli; - /** End of the range in milliseconds. */ - end: Milli; + /** Start of the range. */ + start: Duration; + /** End of the range. */ + end: Duration; } /** An ordered list of buffered time ranges. */ @@ -42,12 +42,12 @@ export function mergeBufferedRanges(a: BufferedRanges, b: BufferedRanges): Buffe if (b.length === 0) return a; const result: BufferedRanges = []; - const all = [...a, ...b].sort((x, y) => x.start - y.start); + const all = [...a, ...b].sort((x, y) => x.start.cmp(y.start)); for (const range of all) { const last = result.at(-1); - if (last && last.end >= range.start) { - last.end = Milli(Math.max(last.end, range.end)); + if (last?.end.ge(range.start)) { + last.end = last.end.max(range.end); } else { result.push({ ...range }); } diff --git a/js/loc/src/index.test.ts b/js/loc/src/index.test.ts index 3c68644ebf7..19121102bb3 100644 --- a/js/loc/src/index.test.ts +++ b/js/loc/src/index.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import type { Micro } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { Varint } from "@moq/net"; import { Format } from "./index.ts"; @@ -33,7 +33,7 @@ test("Format treats an empty payload as a duration marker", () => { const fmt = new Format("video"); const [decoded] = fmt.decode(frame); expect(decoded.payload.byteLength).toBe(0); - expect(fmt.end(decoded)).toBe(33_000 as Micro); + expect(fmt.end(decoded)).toEqual(Duration.micros(33_000)); }); test("Format preserves empty data payloads", () => { @@ -57,7 +57,7 @@ test("Format decodes timestamp at default microseconds timescale", () => { const fmt = new Format(); const [decoded] = fmt.decode(frame); - expect(decoded.timestamp).toBe(12_345 as Micro); + expect(decoded.timestamp).toEqual(Duration.micros(12_345)); expect(decoded.payload).toEqual(payload); expect(decoded.keyframe).toBe(false); }); @@ -75,7 +75,7 @@ test("Format honors per-frame timescale property", () => { const fmt = new Format(); const [decoded] = fmt.decode(frame); - expect(decoded.timestamp).toBe(2_000_000 as Micro); + expect(decoded.timestamp).toEqual(Duration.micros(2_000_000)); }); test("Format skips unknown odd-typed properties", () => { @@ -93,7 +93,7 @@ test("Format skips unknown odd-typed properties", () => { const fmt = new Format(); const [decoded] = fmt.decode(frame); - expect(decoded.timestamp).toBe(10 as Micro); + expect(decoded.timestamp).toEqual(Duration.micros(10)); expect(decoded.payload).toEqual(payload); }); @@ -136,7 +136,7 @@ test("Format decodes the draft-03 timestamp property", () => { const fmt = new Format(); const [decoded] = fmt.decode(frame); - expect(decoded.timestamp).toBe(4242 as Micro); + expect(decoded.timestamp).toEqual(Duration.micros(4242)); expect(decoded.payload).toEqual(payload); }); @@ -148,7 +148,7 @@ test("Format skips an unknown property whose value needs all 62 bits", () => { Varint.encode(1_000), ); const [decoded] = new Format().decode(buildFrame(props, new Uint8Array([1]))); - expect(decoded.timestamp).toBe(1_000 as Micro); + expect(decoded.timestamp).toEqual(Duration.micros(1_000)); }); test("Format rejects a timestamp past 2^53 - 1 instead of rounding", () => { diff --git a/js/loc/src/index.ts b/js/loc/src/index.ts index bb954622062..56c1a955430 100644 --- a/js/loc/src/index.ts +++ b/js/loc/src/index.ts @@ -5,15 +5,15 @@ * @module */ -import type { Micro } from "@moq/clock"; +import { Duration } from "@moq/clock"; import * as Moq from "@moq/net"; /** A decoded LOC frame: the codec bitstream plus its timing metadata. */ export interface Frame { /** The codec bitstream payload, with the LOC property block stripped. */ payload: Uint8Array; - /** Presentation timestamp in microseconds. */ - timestamp: Micro; + /** Presentation timestamp, rounded to whole microseconds. */ + timestamp: Duration; /** True if this frame can be decoded without any preceding frames. */ keyframe: boolean; } @@ -47,7 +47,7 @@ export class Format { } /** Return the video-frame or audio-source endpoint for an empty codec payload. */ - end(frame: Frame): Micro | undefined { + end(frame: Frame): Duration | undefined { return this.kind !== "data" && frame.payload.byteLength === 0 ? frame.timestamp : undefined; } @@ -100,7 +100,7 @@ export class Format { } const activeTimescale = timescale ?? DEFAULT_TIMESCALE; - const micros = Math.round((timestamp * DEFAULT_TIMESCALE) / activeTimescale) as Micro; + const micros = Duration.micros(Math.round((timestamp * DEFAULT_TIMESCALE) / activeTimescale)); return [{ payload, timestamp: micros, keyframe: false }]; } From 0f38263e023799595fde1419a3911ea5925fa2fa Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 09:56:33 -0800 Subject: [PATCH 05/17] feat(json,auth)!: adopt Clock Duration, Instant, and Wall Co-Authored-By: Claude Opus 5.5 --- js/auth/src/cli.test.ts | 6 +++--- js/auth/src/cli.ts | 4 ++-- js/auth/src/key.test.ts | 18 +++++++++--------- js/auth/src/key.ts | 4 ++-- js/crypto/bench/pump.ts | 4 ++-- js/crypto/src/e2ee/e2ee.test.ts | 6 +++--- js/crypto/src/e2ee/transport.test.ts | 4 ++-- js/crypto/src/sign/sign.test.ts | 4 ++-- js/json/src/snapshot/consumer.ts | 4 ++-- js/json/src/snapshot/snapshot.test.ts | 10 +++++----- js/json/src/stream/stream.test.ts | 4 ++-- js/json/src/window/window.test.ts | 4 ++-- js/p2p/src/transport.test.ts | 4 ++-- 13 files changed, 38 insertions(+), 38 deletions(-) diff --git a/js/auth/src/cli.test.ts b/js/auth/src/cli.test.ts index 4247c676dd3..60f74718be9 100644 --- a/js/auth/src/cli.test.ts +++ b/js/auth/src/cli.test.ts @@ -3,7 +3,7 @@ import { chmodSync, mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs import { tmpdir } from "node:os"; import { extname, join } from "node:path"; import { fileURLToPath } from "node:url"; -import { wall } from "@moq/clock"; +import { Wall, wall } from "@moq/clock"; const CLI = join(import.meta.dir, `cli${extname(fileURLToPath(import.meta.url))}`); @@ -81,9 +81,9 @@ describe("sign", () => { /** The `exp` `args` write, with the wall seconds bracketing the subprocess that wrote it. */ function bracketed(...args: string[]) { - const before = Math.floor(wall() / 1000); + const before = Math.floor(wall().since(Wall.UNIX_EPOCH).asSecs()); const value = exp(...args) ?? 0; - const after = Math.floor(wall() / 1000); + const after = Math.floor(wall().since(Wall.UNIX_EPOCH).asSecs()); return { before, value, after }; } diff --git a/js/auth/src/cli.ts b/js/auth/src/cli.ts index 469c38078ec..073d2bb15a6 100755 --- a/js/auth/src/cli.ts +++ b/js/auth/src/cli.ts @@ -1,7 +1,7 @@ #!/usr/bin/env node import { closeSync, fchmodSync, openSync, readFileSync, writeFileSync } from "node:fs"; -import { wall } from "@moq/clock"; +import { Wall, wall } from "@moq/clock"; import { Command, Option } from "commander"; import { base64url } from "jose"; import type { Algorithm } from "./algorithm.ts"; @@ -90,7 +90,7 @@ program const exp = options.unbounded ? undefined - : (options.expires ?? Math.floor(wall() / 1000) + (options.ttl ?? 3600)); + : (options.expires ?? Math.floor(wall().since(Wall.UNIX_EPOCH).asSecs()) + (options.ttl ?? 3600)); const claims = ClaimsSchema.parse({ root: options.root, ...(options.publish && { publish: options.publish }), diff --git a/js/auth/src/key.test.ts b/js/auth/src/key.test.ts index 1ae15cd4389..4889d899bfe 100644 --- a/js/auth/src/key.test.ts +++ b/js/auth/src/key.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Manual, Wall, wall } from "@moq/clock"; +import { Duration, Manual, Wall, wall } from "@moq/clock"; import { base64url, exportJWK, generateKeyPair, SignJWT } from "jose"; import type { Algorithm } from "./algorithm.ts"; import { authorize, type Claims } from "./claims.ts"; @@ -25,8 +25,8 @@ const testClaims = { root: "test-path", publish: ["test-pub/**"], subscribe: ["test-sub/**"], - exp: Math.floor((wall() + 60 * 1000) / 1000), // 1 minute from now in seconds - iat: Math.floor(wall() / 1000), // now in seconds + exp: Math.floor(wall().since(Wall.UNIX_EPOCH).asSecs() + 60), // 1 minute from now in seconds + iat: Math.floor(wall().since(Wall.UNIX_EPOCH).asSecs()), // now in seconds }; type AsymmetricAlgorithm = Exclude; @@ -56,7 +56,7 @@ async function generateAsymmetricKeyPair( test("verify refuses unsafe signed payloads without dropping their restrictions", async () => { const clock = new Manual(); - clock.stepWall(Wall(1_000_000)); + clock.stepWall(Wall.UNIX_EPOCH.add(Duration.millis(1_000_000))); const installed = clock.install(); try { const key = Key.parse(encodeJwk(testKey)); @@ -283,7 +283,7 @@ test("verify - invalid token format", async () => { test("verify - expired token", async () => { const expiredClaims = { ...testClaims, - exp: Math.floor((wall() - 60 * 1000) / 1000), // 1 minute ago in seconds + exp: Math.floor(wall().since(Wall.UNIX_EPOCH).asSecs() - 60), // 1 minute ago in seconds }; const key = Key.parse(encodeJwk(testKey)); @@ -332,8 +332,8 @@ test("round-trip - sign and verify", async () => { root: "test-path", publish: ["test-pub/**"], subscribe: ["test-sub/**"], - exp: Math.floor((wall() + 60 * 1000) / 1000), - iat: Math.floor(wall() / 1000), + exp: Math.floor(wall().since(Wall.UNIX_EPOCH).asSecs() + 60), + iat: Math.floor(wall().since(Wall.UNIX_EPOCH).asSecs()), }; const token = await Key.sign(key, originalClaims); @@ -876,7 +876,7 @@ async function signRaw(payload: Record): Promise { // might narrow the grant, and a misspelled `root` would widen it to everything. test("verify - only registered claims", async () => { const key = Key.parse(encodeJwk(testKey)); - const now = Math.floor(wall() / 1000); + const now = Math.floor(wall().since(Wall.UNIX_EPOCH).asSecs()); const token = await signRaw({ root: "room", publish: ["**"], iss: "api", sub: "alice", jti: "1", iat: now }); const claims = await Key.verify(key, token); @@ -895,7 +895,7 @@ test("verify - only registered claims", async () => { test("verify - enforces not before", async () => { const key = Key.parse(encodeJwk(testKey)); - const now = Math.floor(wall() / 1000); + const now = Math.floor(wall().since(Wall.UNIX_EPOCH).asSecs()); expect((await Key.verify(key, await signRaw({ publish: ["**"], nbf: now - 60 }))).nbf).toBe(now - 60); await expect(Key.verify(key, await signRaw({ publish: ["**"], nbf: now + 3600 }))).rejects.toThrow(); }); diff --git a/js/auth/src/key.ts b/js/auth/src/key.ts index 9771824133d..cf98a7363c7 100644 --- a/js/auth/src/key.ts +++ b/js/auth/src/key.ts @@ -1,4 +1,4 @@ -import { wall } from "@moq/clock"; +import { Wall, wall } from "@moq/clock"; import * as jose from "jose"; import * as z from "zod/mini"; import { type Algorithm, AlgorithmSchema } from "./algorithm.ts"; @@ -247,7 +247,7 @@ async function verify(key: PublicKey | SymmetricKey, token: string): Promise now) throw new Error("Token is not yet valid"); ensureClaimsWithinScope(key, claims); diff --git a/js/crypto/bench/pump.ts b/js/crypto/bench/pump.ts index 63f65ebef74..9d04ecf1921 100644 --- a/js/crypto/bench/pump.ts +++ b/js/crypto/bench/pump.ts @@ -1,6 +1,6 @@ // Sweep protected frame size x writes in flight through the serial pump, then open every frame. // Bun's WebCrypto stands in for the browser's, so compare runs on the same runtime. -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { Broadcast, Time } from "@moq/net"; import { Credential } from "../src/e2ee/index.ts"; @@ -29,7 +29,7 @@ for (const bytes of [160, 1_160, 16_384, 262_144]) { }); const consumer = credential .consume(generation.epoch) - .consume(net.subscribe({ delay: { max: Milli(60_000) } }), "video"); + .consume(net.subscribe({ delay: { max: Duration.millis(60_000) } }), "video"); const producer = await generation.produce(net, "video"); const sealStart = performance.now(); diff --git a/js/crypto/src/e2ee/e2ee.test.ts b/js/crypto/src/e2ee/e2ee.test.ts index 24e601f0147..2198307956e 100644 --- a/js/crypto/src/e2ee/e2ee.test.ts +++ b/js/crypto/src/e2ee/e2ee.test.ts @@ -1,5 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { Broadcast, Datagram as NetDatagram, @@ -50,7 +50,7 @@ function netTrack(name: string, timed = true): NetTrack.Producer { } function subscribe(net: NetTrack.Producer): NetTrack.Subscriber { - return net.subscribe({ delay: { max: Milli(60_000) } }); + return net.subscribe({ delay: { max: Duration.millis(60_000) } }); } interface Pair { @@ -253,7 +253,7 @@ test("a broadcast speaks semantic names and puts physical names on the wire", as const consumer = await new Protected.Consumer( net.consume(), generation.credential.consume(generation.epoch), - ).subscribe("video", { delay: { max: Milli(60_000) } }); + ).subscribe("video", { delay: { max: Duration.millis(60_000) } }); const group = video.appendGroup(); await group.writeFrame(ms(1), text("frame")); group.finish(); diff --git a/js/crypto/src/e2ee/transport.test.ts b/js/crypto/src/e2ee/transport.test.ts index 712f105a042..6470a5ed0f0 100644 --- a/js/crypto/src/e2ee/transport.test.ts +++ b/js/crypto/src/e2ee/transport.test.ts @@ -1,6 +1,6 @@ // Protected tracks over real moq-lite and MoQ Transport sessions: relays forward ciphertext. import { expect, test } from "bun:test"; -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { type Broadcast, Connection, Origin, type Path, Time } from "@moq/net"; // The in-memory WebTransport pair @moq/net tests with; not part of its published surface. import { createMockTransportPair } from "../../../net/src/mock.ts"; @@ -78,7 +78,7 @@ for (const [name, protocol, routed, timed] of transports) { expect(Epoch.of(remote)).toBe(routed ? generation.epoch : undefined); const epoch = Epoch.of(remote) ?? generation.epoch; const consumer = await new Protected.Consumer(remote, cred.consume(epoch)).subscribe("video", { - delay: { max: Milli(60_000) }, + delay: { max: Duration.millis(60_000) }, }); const received = await consumer.recvGroup(); diff --git a/js/crypto/src/sign/sign.test.ts b/js/crypto/src/sign/sign.test.ts index 342bb759c24..d7bcee46fb5 100644 --- a/js/crypto/src/sign/sign.test.ts +++ b/js/crypto/src/sign/sign.test.ts @@ -1,6 +1,6 @@ // Signed tracks over a real moq-lite session: the subscriber delivers only what verifies. import { expect, test } from "bun:test"; -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { type Broadcast, Connection, Error as NetError, Origin, Path, Time } from "@moq/net"; // The in-memory WebTransport pair @moq/net tests with; not part of its published surface. import { createMockTransportPair } from "../../../net/src/mock.ts"; @@ -14,7 +14,7 @@ import * as Track from "./track.ts"; const encoder = new TextEncoder(); const decoder = new TextDecoder(); const url = new URL("https://localhost:4443/test"); -const subscription = { delay: { max: Milli(60_000) } }; +const subscription = { delay: { max: Duration.millis(60_000) } }; async function session() { const pair = createMockTransportPair("moq-lite-07-wip"); diff --git a/js/json/src/snapshot/consumer.ts b/js/json/src/snapshot/consumer.ts index 492c2f5339a..957192bda69 100644 --- a/js/json/src/snapshot/consumer.ts +++ b/js/json/src/snapshot/consumer.ts @@ -1,4 +1,4 @@ -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import type { Timed } from "@moq/net"; import * as Moq from "@moq/net"; @@ -43,7 +43,7 @@ export class Consumer { .subscribe({ ...Moq.Track.Subscription.default(), priority: config.priority ?? 0, - delay: { max: Milli.zero }, + delay: { max: Duration.ZERO }, }) .ordered(); this.#decoder = new Decoder(config); diff --git a/js/json/src/snapshot/snapshot.test.ts b/js/json/src/snapshot/snapshot.test.ts index 3b4b571d35c..d063bac455d 100644 --- a/js/json/src/snapshot/snapshot.test.ts +++ b/js/json/src/snapshot/snapshot.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Manual, Milli, Nano } from "@moq/clock"; +import { Duration, Manual } from "@moq/clock"; import { Error as NetError, StreamCode, Time, Track } from "@moq/net"; import { hooks } from "../../../net/src/internal.ts"; import { Consumer } from "./consumer.ts"; @@ -10,7 +10,7 @@ type Value = Record; // These tests inspect complete finished timelines through raw ordered reads, so request a // replay window instead of the transport's live-edge default. A snapshot consumer ignores it. -const REPLAY_LATENCY = Milli(30_000); +const REPLAY_LATENCY = Duration.millis(30_000); // Reconstruct every state a consumer reading `track` yields from `next()`, in order. async function drain(track: Track.Producer | Consumer): Promise { @@ -195,7 +195,7 @@ test("next skips every superseded group, whatever budget another reader asks for for (let n = 1; n <= 3; n++) producer.update({ value: { n }, at: Time.Timestamp.fromMillis(n * 1_000) }); producer.finish(); - for (const max of [Milli.zero, Milli(500), REPLAY_LATENCY, null]) { + for (const max of [Duration.ZERO, Duration.millis(500), REPLAY_LATENCY, null]) { const other = track.subscribe({ delay: { max } }); expect(await drain(track)).toEqual([{ n: 3 }]); other.close(); @@ -210,7 +210,7 @@ test("reads skip a group the subscription still owes", async () => { const clock = new Manual(); const installed = clock.install(); try { - for (const max of [Milli.zero, Milli(1_000), null]) { + for (const max of [Duration.ZERO, Duration.millis(1_000), null]) { const track = new Track.Producer("test").accept({}); hooks.receiveTrack(track); const other = track.subscribe({ delay: { max } }); @@ -226,7 +226,7 @@ test("reads skip a group the subscription still owes", async () => { expect((await latest.latest())?.value).toEqual({ n: 0 }); expect((await next.next())?.value).toEqual({ n: 0 }); const reads = [latest.latest(), next.next()]; - await clock.advance(Nano.zero); + await clock.advance(Duration.ZERO); put(2n); expect((await Promise.all(reads)).map((state) => state?.value)).toEqual([{ n: 2 }, { n: 2 }]); diff --git a/js/json/src/stream/stream.test.ts b/js/json/src/stream/stream.test.ts index 7e2b6c860bb..322450062d3 100644 --- a/js/json/src/stream/stream.test.ts +++ b/js/json/src/stream/stream.test.ts @@ -1,5 +1,5 @@ import { expect, spyOn, test } from "bun:test"; -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { StreamCode, Time, Track } from "@moq/net"; import * as z from "zod/mini"; import { Consumer, Producer, Rolled } from "./index.ts"; @@ -99,7 +99,7 @@ test("a second group is reported while the first is still open", async () => { // Ask for a replay window, so the first group is delivered rather than skipped by the // subscriber's default max delay budget once a newer group exists. - const consumer = new Consumer({ track: track.subscribe({ delay: { max: Milli(30_000) } }) }); + const consumer = new Consumer({ track: track.subscribe({ delay: { max: Duration.millis(30_000) } }) }); expect((await consumer.next())?.value).toEqual({ n: 0 }); await expect(consumer.next()).rejects.toBeInstanceOf(Rolled); diff --git a/js/json/src/window/window.test.ts b/js/json/src/window/window.test.ts index 39e7c5f5c11..aed32de6e14 100644 --- a/js/json/src/window/window.test.ts +++ b/js/json/src/window/window.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Milli, yieldNow } from "@moq/clock"; +import { Duration, yieldNow } from "@moq/clock"; import { Error as NetError, StreamCode, Time, type Timed, Track } from "@moq/net"; import { Consumer } from "./consumer.ts"; import { Decoder, Encoder, type Event, Producer, type Span } from "./index.ts"; @@ -212,7 +212,7 @@ test("compressed round-trip across rolls", async () => { // The frame count and first-frame timestamp of each group in a finished track. async function groups(track: Track.Producer): Promise<[number, number | undefined][]> { - const ordered = track.subscribe({ delay: { max: Milli(30_000) } }).ordered(); + const ordered = track.subscribe({ delay: { max: Duration.millis(30_000) } }).ordered(); const out: [number, number | undefined][] = []; for (let group = await ordered.nextGroup(); group; group = await ordered.nextGroup()) { const first = await group.readFrame(); diff --git a/js/p2p/src/transport.test.ts b/js/p2p/src/transport.test.ts index fea9e5da024..1024733a003 100644 --- a/js/p2p/src/transport.test.ts +++ b/js/p2p/src/transport.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Manual, Milli, Nano, yieldNow } from "@moq/clock"; +import { Duration, Manual, yieldNow } from "@moq/clock"; import { Channel } from "./channel.ts"; import { peers } from "./mock.ts"; import { Transport } from "./transport.ts"; @@ -104,7 +104,7 @@ test("an accepted channel whose dialer stays silent closes at the handshake dead right.incoming.open(); // The session starts on open, so its 10 s handshake deadline runs while its first write // waits on the silent dialer's parameters. - await clock.advance(Nano.fromMilli(Milli(11_000))); + await clock.advance(Duration.millis(11_000)); await expect(server.closed).rejects.toThrow("handshake timeout"); expect(right.incoming.records).toEqual([]); expect(right.incoming.listeners.size).toBe(0); From d4b60baa4ad44a4b0b4ad6e37463a827ee829544 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 09:58:47 -0800 Subject: [PATCH 06/17] docs: Clock types in the JS guides; retire the js-time-types quest Co-Authored-By: Claude Opus 5.5 --- doc/lib/js/clock.md | 2 +- doc/lib/js/hang.md | 6 ++-- doc/lib/js/net.md | 3 +- quest/m2/README.md | 1 - quest/m2/api-shape/js.md | 4 +-- quest/m2/js-time-types.md | 53 ---------------------------------- quest/m2/time-addressing/js.md | 3 ++ 7 files changed, 11 insertions(+), 61 deletions(-) delete mode 100644 quest/m2/js-time-types.md diff --git a/doc/lib/js/clock.md b/doc/lib/js/clock.md index 77d434c1dbd..e106a11b899 100644 --- a/doc/lib/js/clock.md +++ b/doc/lib/js/clock.md @@ -89,7 +89,7 @@ workspace dependencies reach `@moq/clock` loads a preload fails a workspace that doesn't. The preload fails a test when a timer it armed through `@moq/clock` fires on the host clock, so a test can't prove that nothing happened by waiting in real time; lint bans the native timers in test files. A -timer already due when armed, such as `sleep(0)`, or a `timeout()` whose +timer already due when armed, such as `sleep(Duration.ZERO)`, or a `timeout()` whose operation settles first never waits, and a timer firing after its test ended fails nothing. A test on real sockets, devices, or processes calls `hostTime()` from `@moq/clock/test` first; without the preload it does nothing. diff --git a/doc/lib/js/hang.md b/doc/lib/js/hang.md index 12c96199ed9..ab9f35a116b 100644 --- a/doc/lib/js/hang.md +++ b/doc/lib/js/hang.md @@ -28,15 +28,15 @@ or building a custom player. A catalog's `media` section may carry a `clock` that maps PTS zero to wall time. `Catalog.wallClockTime(clock, pts, ptsTimescale)` turns a frame's timestamp -into a `Date`. A `Container.Legacy` timestamp is microseconds, so pass -`1_000_000`. +into a `Date`. It takes integer ticks at a timescale, so pass a frame's +`Duration` timestamp as whole microseconds with `1_000_000`. ```ts for await (const root of Catalog.watch(broadcast)) { const clock = root.media?.clock; if (!clock) continue; // the publisher exposes no clock // `frame` comes from your own `Container.Legacy` consumer. - const captured = Catalog.wallClockTime(clock, frame.timestamp, 1_000_000); + const captured = Catalog.wallClockTime(clock, Math.floor(frame.timestamp.asMicros()), 1_000_000); } ``` diff --git a/doc/lib/js/net.md b/doc/lib/js/net.md index faf1519921b..34ae7fd9524 100644 --- a/doc/lib/js/net.md +++ b/doc/lib/js/net.md @@ -52,8 +52,9 @@ route.announce(); - **One track per name.** Concurrent subscriptions share one request and producer. `createTrack` on a name with a request still queued answers it. The application owns sequence numbers: the broadcast keeps nothing of an ended track, so a track that replaces it, created or requested, starts at 0. A name always means the same content, so the replacement continues past its predecessor's groups by writing its first group with an explicit sequence. Sequences are `bigint`, so every ID the wire carries fits, past 2^53 included: `track.createGroup(5n)`, `{ absolute: 10n }`. Frame indices and relative anchors stay `number`. - **Serve history on request.** `track.requests()` opens a handle that serves the groups readers miss: ones their ranges name below the newest group written that the cache no longer holds, or never did. Each run of misses arrives as a `Track.Fill` from `await requests.requestedFill()`, shared by every reader missing it. `accept(sequence)` it into the cache and write the group's frames as first published, `dropGroups(start, end)` what the source lacks (sequences are `bigint`), and serve `wanted()` until it is `undefined`: a reader that leaves or narrows stops wanting its groups. `close()` the fill when done; whatever is still wanted is named dropped. A `fetchGroup` of an uncached group asks the handle at once, even for a group not written yet, which a live write then answers; with no handle open it fails with `NotFound`, as in Rust, and a reader's miss is given up. A reader only asks for what its `delay.max` still wants, so a reader at the live edge never asks. This serves lite FETCH, single-group IETF FETCH, and lite-07 ranged subscriptions from the same track, as Rust's `requests()` does. - **Timing is per track, with no default.** A track that declares a `timescale` carries a `timestamp` on every frame; one without is [untimed](/concept/moq-lite#subscriptions) and its frames carry none. Omitting it means untimed, as in Rust. Nothing stamps a frame for you: the publisher passes the timestamp, and the `Timed` type (`{ value, at }`) carries one into the `@moq/json` producers. +- **Durations and instants are `Clock` types.** Every duration (`maxAge`, `delay`, timeouts, RTT) is a `Clock.Duration` and every monotonic time a `Clock.Instant`, from [`@moq/clock`](./clock), which `@moq/net` re-exports as `Clock`: `maxAge: Moq.Clock.Duration.secs(30)`. Neither converts to a number implicitly; read one with an explicit unit, such as `asMillis()`. The wire still carries whole milliseconds, rounded up. Frame timestamps stay `Time.Timestamp`, a tick count at the track's timescale. - **A subscription's `delay` is a `Track.Delay { min, max }`, as in Rust.** Staleness is `delay.max`: it counts from a group's successor, by media time and by wall clock, whichever reaches it first. `delay.min` is the target latency, carried on moq-lite 07; a peer that cannot carry it leaves it `null` (not stated). Passing the old `maxAge` or `maxDelay` key throws a `TypeError` naming `delay.max`. The publisher's own staleness bound is the separate `Track.Info.maxAge`, which caps `delay.max` and fetches. -- **Authored tracks default to a zero `maxAge`.** `createTrack` and `accept` take a `Track.InfoInit`: an omitted `maxAge` is zero, so readers get only the live edge; `null` sets no publisher limit, and a number is that bound, as `Info::default()` and `with_max_age(None)` do in Rust. A track whose readers reach back for superseded groups (history, a fetch, a range from an absolute start) sets one explicitly; media takes `@moq/hang`'s 30-second `Container.MAX_AGE`. `maxAge` is how long a superseded group stays fresh, never the newest group, so a track that writes one snapshot stays readable to a late joiner. Received metadata keeps absence as no limit; serve a received `Track.Info` onward with `maxAge: info.maxAge ?? null`. +- **Authored tracks default to a zero `maxAge`.** `createTrack` and `accept` take a `Track.InfoInit`: an omitted `maxAge` is zero, so readers get only the live edge; `null` sets no publisher limit, and a `Clock.Duration` is that bound, as `Info::default()` and `with_max_age(None)` do in Rust. A track whose readers reach back for superseded groups (history, a fetch, a range from an absolute start) sets one explicitly; media takes `@moq/hang`'s 30-second `Container.MAX_AGE`. `maxAge` is how long a superseded group stays fresh, never the newest group, so a track that writes one snapshot stays readable to a late joiner. Received metadata keeps absence as no limit; serve a received `Track.Info` onward with `maxAge: info.maxAge ?? null`. - **The cache keeps an idle group for 30 seconds.** A track evicts a group nothing has written for 30 seconds, matching the Rust cache's default expiry; a live track's newest group is exempt until a newer one arrives, unless it failed. Neither `Track.Info.maxAge` nor `delay.max` changes that window: they only decide which cached groups a reader still receives. - **Subscription defaults.** `Track.Subscription.default()` returns the default subscription, whose zero `delay.max` skips a superseded group at once; calling `subscribe()` with no options means the same. An omitted `delay` field means the same zero; `max: null` sets no subscriber limit. - **A subscription asks for `ranges`.** Each [range](/concept/moq-lite#subscriptions) starts and ends at an `absolute` group, one `relative` to the latest, or the group containing a `time` (a `Timestamp`), and a reader reads only its own ranges. A read whose ranges all end finishes once every group in them is handed out, dropped, or skipped, as in Rust. A time anchor needs a timed track and `moq-lite-07-wip` over a session. Passing the old `groups` key throws a `TypeError` naming `ranges`; `withRange` only narrows reads locally. diff --git a/quest/m2/README.md b/quest/m2/README.md index 1ae9ab6e886..4314ba1e093 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -200,7 +200,6 @@ quests that require them. - [moq-video takes devices, not environment variables](/quest/m2/video-devices.md) - VA-API and V4L2 device paths are config fields, and `moq_video::ENV` never ships - [Gateways share one ingest config and one rate cap](/quest/m2/gateway-ingest.md) - `moq_mux::Ingest` replaces 18 per-gateway setters, and the live rate cap moves to `moq_net::bandwidth` - [Native playout sync keeps tracks decoupled](/quest/m2/mux-sync.md) - `moq_mux::timeline` becomes `moq_mux::sync`, and one slow track no longer stalls or moves another -- [JS time values are types, not numbers](/quest/m2/js-time-types.md) - every public JS duration and instant is a `Clock.Duration` or `Clock.Instant` object, so a unit mistake fails to compile - [Small API fixes before the cut](/quest/m2/api-shape/README.md) - one path and one spelling per item, names by role, and no dead or wrong-role public surface across net, transport, media, native, apps, JS, and bindings - [Public constructors spawn nothing, or say why](/quest/m2/spawn-constructors.md) - each public library entry point that spawns returns a driver its caller polls, or is listed as kept - [moq-audio codecs return zero or more outputs](/quest/m2/audio-codec-seam.md) - `encode` and `decode` return any number of outputs and gain `flush`, as moq-video's do diff --git a/quest/m2/api-shape/js.md b/quest/m2/api-shape/js.md index b4f94747d5f..179f46a312a 100644 --- a/quest/m2/api-shape/js.md +++ b/quest/m2/api-shape/js.md @@ -35,8 +35,8 @@ Added 2026-11-07 (maintainer, /quest-plan from the 2026-11-07 API sweep of open PRs and remaining quests): the worker-safe renderer output and room's narrower surface. Found by the 2026-11-07 API shape audit (JS core and browser media); see -the [epic](/quest/m2/api-shape/README.md). Durations are -[js-time-types](/quest/m2/js-time-types.md); hosted assets and the +the [epic](/quest/m2/api-shape/README.md). Durations are already +`Clock.Duration` objects; hosted assets and the `supported` default are m1 quests. Each change updates its package's `api/*.api.md`, and moq.dev's npm consumer is checked for each removed export. diff --git a/quest/m2/js-time-types.md b/quest/m2/js-time-types.md deleted file mode 100644 index b6ccdf94bd0..00000000000 --- a/quest/m2/js-time-types.md +++ /dev/null @@ -1,53 +0,0 @@ -# [L] JS time values are types, not numbers - -## Goal - -Every public duration and instant in the published JS packages is a -`Clock.Duration` or `Clock.Instant` object, so a unit mistake fails to -compile and cannot be stripped by `as number` or arithmetic. Today -`@moq/clock` and `@moq/signals` take `Nano`, `@moq/net` takes `Milli` -(`ConnectProps.timeout`, `Backoff`, `Delay`, `Info.maxAge`, fetch `maxDelay`, -`Goaway.handover`, `Drain.timeout`, `Probe.rtt`), and `@moq/qmux` takes raw -unbranded milliseconds (`Config.idleTimeout`, `handshakeTimeout`). That -costs 54 non-test unit conversions in `js/` alone. Covers -`@moq/clock`, `@moq/signals`, `@moq/net`, `@moq/qmux`, `@moq/hang`, -`@moq/json`, `@moq/room`, `@moq/watch`, and `@moq/publish`. `@moq/net` -re-exports `Clock` as it re-exports `Signals`. - -## Plan - -Decided 2026-11-07 (maintainer, /quest-plan from the API shape audit): -"Can we make a proper new type instead of an alias? Converting to number is -easy but dangerous." ✅ `Duration` and `Instant` classes, mirroring -`kio::clock` (rejected: a `Duration` class with `Instant` kept a branded -number; branded `Nano` everywhere, which keeps the `as number` escape; -moving everything to `Milli`, which reverses #5706 and loses timer -precision). - -- `Clock.Duration` is immutable, with unit constructors (`Duration.millis`, - `secs`, `micros`, `nanos`), unit accessors, `add`/`sub`/`mul`, comparison, - and no implicit number conversion (`valueOf` refuses). `Clock.Instant` - supports `add(Duration)`, `since(Instant) -> Duration`, and comparison; - `Wall` follows the same rule. -- `Clock.Instant`'s arithmetic mirrors `kio::clock::Instant`'s. If - [moq-dev/moq#8151](https://github.com/moq-dev/moq/pull/8151)'s - peer-arithmetic drops kio's `Duration` operators for checked and saturating - forms, JS gets `checkedAdd` and `saturatingAdd` too (added 2026-11-07 (maintainer, /quest-plan from the API sweep of open PRs and remaining quests)). -- The wire still carries whole milliseconds; rounding stays inside the - encoders, as it does today. -- `Manual`, `sleep`, `timeout`, `interval`, and the signals timers take the - new types. -- Per-frame paths now allocate (watch `Sync`, the audio jitter ring, hang's - container reader, publish encoders). Run their benches (`js/*/bench`) - against main and report the deltas in the PR; avoid allocations where a - hot loop can keep an internal number without exposing it. -- Decide here whether `Time.Timestamp.value` becomes a `bigint` or keeps a - `number`, together with [time addressing's JS half](/quest/m2/time-addressing/js.md), - which makes group starts `bigint` timestamps. - -Breaking in every listed package; the Impact section gives the migration -(`x as Milli` becomes `Clock.Duration.millis(x)`). - -## Related - -- [Time addressing in JS](/quest/m2/time-addressing/js.md) - rekeys groups by timestamp in the same packages diff --git a/quest/m2/time-addressing/js.md b/quest/m2/time-addressing/js.md index 3dd4d1a2875..03945ec437f 100644 --- a/quest/m2/time-addressing/js.md +++ b/quest/m2/time-addressing/js.md @@ -14,6 +14,9 @@ increasing starts, the three group ends, reach from a group's own end, and (`delivered.ts`, `ledger.ts`, `track.ts`, `resume.ts`) follows previous-start links instead. Starts are `bigint`, as group IDs already are, so they are carried past 2^53 (decided 2026-11-03, maintainer). +`Time.Timestamp.value` stays a `number` for now (2026-11-08, the JS time +types PR, to keep frames allocation-free); revisit it here if a start must +compare exactly with a timestamp past 2^53 ticks. The spike found no sparse-ID breakage in direct `@moq/net` sessions over lite-06 and lite-07; its relay fills follow Rust's once JavaScript received From 03831ac7bf444e93b82b08e1c58c7eeb3fd4ac7f Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 11:40:59 -0800 Subject: [PATCH 07/17] feat(watch,publish,room,boy)!: adopt Clock Duration, Instant, and Wall Also add Wall.unixMillis and asUnixMillis, which convert Unix milliseconds exactly, where a Duration since the epoch rounds past 2^53 ns. Co-Authored-By: Claude Opus 5.5 --- demo/carla/web/src/player.ts | 6 +- demo/carla/web/src/truck.ts | 12 +- demo/web/src/index.ts | 101 ++--- demo/web/src/publish.ts | 49 +- demo/web/src/stats.ts | 6 +- demo/web/src/viz.ts | 17 +- doc/lib/js/clock.md | 4 +- js/auth/src/cli.test.ts | 6 +- js/auth/src/cli.ts | 4 +- js/auth/src/key.test.ts | 18 +- js/auth/src/key.ts | 4 +- js/clock/api/index.api.md | 159 ++++--- js/clock/src/index.test.ts | 13 +- js/clock/src/types.ts | 16 +- js/hang/api/container.api.md | 38 +- js/hang/bench/buffered.ts | 10 +- .../container/consumer.backpressure.test.ts | 51 ++- js/hang/src/container/consumer.holes.test.ts | 21 +- .../src/container/consumer.outoforder.test.ts | 30 +- js/hang/src/container/consumer.test.ts | 229 ++++++++-- js/hang/src/container/consumer.ts | 3 +- js/hang/src/container/consumer.warmup.test.ts | 17 +- js/hang/src/container/jitter.test.ts | 15 +- js/hang/src/container/jitter.ts | 1 - js/hang/src/container/legacy.ts | 15 +- js/loc/api/index.api.md | 6 +- js/moq-boy/src/game.ts | 12 +- js/moq-boy/src/ui/components/StatsPanel.tsx | 8 +- js/net/api/index.api.md | 53 ++- js/net/bench/broadcasts.ts | 4 +- js/net/src/cache.ts | 2 +- js/net/src/connection/accept.ts | 2 +- js/net/src/connection/connect.ts | 2 +- js/net/src/connection/reload.ts | 2 +- js/net/src/internal.ts | 2 +- js/net/src/ledger.ts | 2 +- js/net/src/lite/publisher.ts | 2 +- js/net/src/lite/subscriber.ts | 7 +- js/net/src/tail.ts | 2 +- js/net/src/track.test.ts | 2 +- js/net/src/util/deadline.ts | 4 +- js/net/src/util/timeout.ts | 2 +- js/net/src/util/timer.ts | 2 +- js/publish/api/index.api.md | 16 +- js/publish/bench/audio-page.ts | 10 +- js/publish/bench/catalog.ts | 8 +- js/publish/src/audio/backlog.test.ts | 39 +- js/publish/src/audio/backlog.ts | 24 +- js/publish/src/audio/capture-worklet.ts | 12 +- js/publish/src/audio/capture.test.ts | 4 +- js/publish/src/audio/capture.ts | 25 +- js/publish/src/audio/encoder.test.ts | 231 ++++++---- js/publish/src/audio/encoder.ts | 109 ++--- js/publish/src/audio/framer.test.ts | 63 +-- js/publish/src/audio/framer.ts | 41 +- js/publish/src/audio/gain.test.ts | 12 +- js/publish/src/audio/gain.ts | 8 +- js/publish/src/audio/resampler.test.ts | 4 +- js/publish/src/audio/resampler.ts | 6 +- js/publish/src/broadcast.test.ts | 40 +- js/publish/src/broadcast.ts | 16 +- js/publish/src/catalog.test.ts | 14 +- js/publish/src/catalog.ts | 12 +- js/publish/src/preview.ts | 12 +- js/publish/src/rendition-internal.ts | 4 +- js/publish/src/source/file.test.ts | 12 +- js/publish/src/source/file.ts | 15 +- js/publish/src/source/pace.test.ts | 17 +- js/publish/src/source/pace.ts | 21 +- js/publish/src/source/retry.test.ts | 18 +- js/publish/src/source/retry.ts | 13 +- js/publish/src/source/timeline.test.ts | 31 +- js/publish/src/source/timeline.ts | 33 +- js/publish/src/ui/components/stats-tab.ts | 6 +- js/publish/src/ui/element.ts | 4 +- js/publish/src/video/capture.test.ts | 6 +- js/publish/src/video/capture.ts | 10 +- js/publish/src/video/encoder-stall.test.ts | 14 +- js/publish/src/video/encoder.test.ts | 30 +- js/publish/src/video/encoder.ts | 35 +- js/publish/src/video/processor.test.ts | 10 +- js/publish/src/video/processor.ts | 8 +- js/qmux/api/index.api.md | 6 +- js/room/api/index.api.md | 2 +- js/room/src/chat.test.ts | 6 +- js/room/src/chat.ts | 10 +- js/room/src/metadata.ts | 4 +- js/signals/api/index.api.md | 8 +- js/watch/api/element.api.md | 6 +- js/watch/api/index.api.md | 40 +- js/watch/bench/arrivals.ts | 4 +- js/watch/bench/ring-page.ts | 6 +- js/watch/bench/warmup.ts | 12 +- js/watch/src/arrivals.test.ts | 6 +- js/watch/src/arrivals.ts | 22 +- js/watch/src/audio/buffer.test.ts | 154 ++++--- js/watch/src/audio/buffer.ts | 76 ++-- js/watch/src/audio/config.test.ts | 16 +- js/watch/src/audio/config.ts | 12 +- js/watch/src/audio/decoder.test.ts | 223 ++++----- js/watch/src/audio/decoder.ts | 125 ++--- js/watch/src/audio/emitter.ts | 6 +- js/watch/src/audio/latency.test.ts | 20 +- js/watch/src/audio/latency.ts | 32 +- js/watch/src/audio/order.test.ts | 23 +- js/watch/src/audio/order.ts | 22 +- js/watch/src/audio/playout.test.ts | 32 +- js/watch/src/audio/render-worklet.test.ts | 63 ++- js/watch/src/audio/render.ts | 19 +- js/watch/src/audio/replay.test.ts | 24 +- js/watch/src/audio/replay.ts | 42 +- js/watch/src/audio/ring-buffer.test.ts | 303 ++++++------- js/watch/src/audio/ring-buffer.ts | 26 +- js/watch/src/audio/source.ts | 10 +- js/watch/src/audio/terminal.test.ts | 22 +- js/watch/src/audio/terminal.ts | 39 +- js/watch/src/duration.test.ts | 28 +- js/watch/src/duration.ts | 12 +- js/watch/src/echo.test.ts | 6 +- js/watch/src/echo.ts | 6 +- js/watch/src/element.ts | 26 +- js/watch/src/feedback.test.ts | 18 +- js/watch/src/feedback.ts | 27 +- js/watch/src/media.test.ts | 10 +- js/watch/src/player.ts | 6 +- js/watch/src/retention.test.ts | 24 +- js/watch/src/sync.test.ts | 427 +++++++++--------- js/watch/src/sync.ts | 91 ++-- js/watch/src/text/renderer.test.ts | 12 +- js/watch/src/text/renderer.ts | 22 +- js/watch/src/ui/components/buffer-control.ts | 33 +- js/watch/src/ui/components/latency.ts | 11 +- js/watch/src/ui/components/live-badge.ts | 2 +- js/watch/src/ui/element.ts | 4 +- js/watch/src/ui/stats.ts | 11 +- js/watch/src/video/decoder.test.ts | 187 ++++---- js/watch/src/video/decoder.ts | 132 +++--- js/watch/src/video/playhead.test.ts | 24 +- js/watch/src/video/playhead.ts | 28 +- js/watch/src/video/recovery.ts | 6 +- js/watch/src/video/renderer.ts | 6 +- 141 files changed, 2439 insertions(+), 2095 deletions(-) diff --git a/demo/carla/web/src/player.ts b/demo/carla/web/src/player.ts index 0b890b141b7..a44b67ef775 100644 --- a/demo/carla/web/src/player.ts +++ b/demo/carla/web/src/player.ts @@ -10,7 +10,7 @@ * @module */ -import { Milli, Nano } from "@moq/clock"; +import { Duration } from "@moq/clock"; import * as Moq from "@moq/net"; import { COLLISION_ALERT_MS, collisionAge, collisionLabel, diverged, divergence } from "./feedback.ts"; import { drawDivergence, drawDriveHud, drawGuide } from "./guides.ts"; @@ -720,7 +720,7 @@ export function mount(root: ShadowRoot, connection: Moq.Connection, origin: Moq. frame = requestAnimationFrame(tick); } signals.cleanup(() => cancelAnimationFrame(frame)); - signals.interval(step, Nano.fromMilli(Milli(250))); + signals.interval(step, Duration.millis(250)); // --- Wheel status chip + calibration dialog. --- let calibration: Calibration | undefined; @@ -1118,7 +1118,7 @@ export function mount(root: ShadowRoot, connection: Moq.Connection, origin: Moq. // A collision's age is wall clock, not a status field, so it needs its own // tick: without one the callout would freeze on a truck that stops moving // and therefore stops changing its snapshot. - this.#signals.interval(() => this.#renderCollision(this.truck.status.peek()), Nano.fromMilli(Milli(1000))); + this.#signals.interval(() => this.#renderCollision(this.truck.status.peek()), Duration.millis(1000)); // Repaint on layout/resize (the initial effect run happens before layout, // so the overlay has zero size until the first observation fires). diff --git a/demo/carla/web/src/truck.ts b/demo/carla/web/src/truck.ts index f88f9c26ad4..aecdbfbc5d1 100644 --- a/demo/carla/web/src/truck.ts +++ b/demo/carla/web/src/truck.ts @@ -9,7 +9,7 @@ * * @module */ -import { Milli, Nano } from "@moq/clock"; +import { Duration } from "@moq/clock"; import * as Json from "@moq/json"; import * as Moq from "@moq/net"; import * as Watch from "@moq/watch"; @@ -44,7 +44,7 @@ interface Command { /** A driver session: pending until the truck accepts, `null` once the dial or the session failed. */ type Session = Moq.Signals.Signal; -const CONTROL_HEARTBEAT = Milli(250); +const CONTROL_HEARTBEAT = Duration.millis(250); const MAX_PENDING_ACKS = 64; const encoder = new TextEncoder(); const decoder = new TextDecoder(); @@ -120,7 +120,7 @@ export class Truck { this.#signals.run(this.#runActive.bind(this)); this.#signals.run(this.#runControlLease.bind(this)); this.#signals.run(this.#runRespawn.bind(this)); - this.#signals.interval(() => this.#heartbeat(), Nano.fromMilli(CONTROL_HEARTBEAT)); + this.#signals.interval(() => this.#heartbeat(), CONTROL_HEARTBEAT); // Video pipeline. this.broadcast = new Watch.Broadcast({ @@ -313,11 +313,11 @@ export class Truck { #timestamps(): { label: string; ts: number }[] { const entries: { label: string; ts: number }[] = []; const received = this.sync.out.timestamp.peek(); - if (received != null) entries.push({ label: "received", ts: received }); + if (received != null) entries.push({ label: "received", ts: received.asMillis() }); const decoded = this.videoDecoder.out.timestamp.peek(); - if (decoded != null) entries.push({ label: "decoded", ts: decoded }); + if (decoded != null) entries.push({ label: "decoded", ts: decoded.asMillis() }); const rendered = this.videoRenderer.out.timestamp.peek(); - if (rendered != null) entries.push({ label: "rendered", ts: rendered }); + if (rendered != null) entries.push({ label: "rendered", ts: rendered.asMillis() }); return entries; } diff --git a/demo/web/src/index.ts b/demo/web/src/index.ts index c5128d3a9e9..812d9fdd959 100644 --- a/demo/web/src/index.ts +++ b/demo/web/src/index.ts @@ -17,7 +17,7 @@ */ import "./highlight"; -import { Milli, Nano, now } from "@moq/clock"; +import { Duration, now } from "@moq/clock"; import * as Json from "@moq/json"; import "@moq/watch/element"; // defines import "@moq/watch/ui"; // defines @@ -509,58 +509,55 @@ viz.run((effect) => { // Sample the active tile's byte/frame counters and push per-second rates. let prevWatch: MoqWatch | undefined; -let prev = { frames: 0, videoBytes: 0, audioBytes: 0, when: Nano.toMilli(Nano(now())) }; -viz.interval( - () => { - const watch = activeWatch.peek(); - const at = Nano.toMilli(Nano(now())); - - // Reset baselines when switching tiles (or when idle) so the first sample - // isn't a huge spike from the counter difference. - if (watch !== prevWatch || !watch) { - prevWatch = watch; - const video = watch?.video.out.stats.peek(); - const audio = watch?.audio.out.stats.peek(); - prev = { - frames: video?.frameCount ?? 0, - videoBytes: video?.bytesReceived ?? 0, - audioBytes: audio?.bytesReceived ?? 0, - when: at, - }; - for (const g of allGraphs) g.push(undefined); - return; - } +let prev = { frames: 0, videoBytes: 0, audioBytes: 0, when: now() }; +viz.interval(() => { + const watch = activeWatch.peek(); + const at = now(); + + // Reset baselines when switching tiles (or when idle) so the first sample + // isn't a huge spike from the counter difference. + if (watch !== prevWatch || !watch) { + prevWatch = watch; + const video = watch?.video.out.stats.peek(); + const audio = watch?.audio.out.stats.peek(); + prev = { + frames: video?.frameCount ?? 0, + videoBytes: video?.bytesReceived ?? 0, + audioBytes: audio?.bytesReceived ?? 0, + when: at, + }; + for (const g of allGraphs) g.push(undefined); + return; + } - const v = watch.video.out.stats.peek(); - const a = watch.audio.out.stats.peek(); - const videoBytes = v?.bytesReceived ?? 0; - const audioBytes = a?.bytesReceived ?? 0; - const frames = v?.frameCount ?? 0; - const elapsed = at - prev.when; - - const perSec = (delta: number) => (delta >= 0 ? (delta * 1000) / elapsed : undefined); - let videoBitrate: number | undefined; - let audioBitrate: number | undefined; - let throughput: number | undefined; - let fps: number | undefined; - if (elapsed > 0) { - videoBitrate = perSec((videoBytes - prev.videoBytes) * 8); - audioBitrate = perSec((audioBytes - prev.audioBytes) * 8); - throughput = perSec((videoBytes - prev.videoBytes + audioBytes - prev.audioBytes) * 8); - fps = perSec(frames - prev.frames); - } - videoBitrateGraph.push(videoBitrate); - audioBitrateGraph.push(audioBitrate); - fpsGraph.push(fps); - throughputGraph.push(throughput); - - const rtt = watch.connection.probe.peek()?.rtt as unknown as number | undefined; - rttGraph.push(rtt && rtt > 0 ? rtt : undefined); - - prev = { frames, videoBytes, audioBytes, when: at }; - }, - Nano.fromMilli(Milli(250)), -); + const v = watch.video.out.stats.peek(); + const a = watch.audio.out.stats.peek(); + const videoBytes = v?.bytesReceived ?? 0; + const audioBytes = a?.bytesReceived ?? 0; + const frames = v?.frameCount ?? 0; + const elapsed = at.since(prev.when).asMillis(); + + const perSec = (delta: number) => (delta >= 0 ? (delta * 1000) / elapsed : undefined); + let videoBitrate: number | undefined; + let audioBitrate: number | undefined; + let throughput: number | undefined; + let fps: number | undefined; + if (elapsed > 0) { + videoBitrate = perSec((videoBytes - prev.videoBytes) * 8); + audioBitrate = perSec((audioBytes - prev.audioBytes) * 8); + throughput = perSec((videoBytes - prev.videoBytes + audioBytes - prev.audioBytes) * 8); + fps = perSec(frames - prev.frames); + } + videoBitrateGraph.push(videoBitrate); + audioBitrateGraph.push(audioBitrate); + fpsGraph.push(fps); + throughputGraph.push(throughput); + + const rtt = watch.connection.probe.peek()?.rtt?.asMillis(); + rttGraph.push(rtt && rtt > 0 ? rtt : undefined); + + prev = { frames, videoBytes, audioBytes, when: at }; +}, Duration.millis(250)); // Rebuild the buffer visualization whenever the active tile changes; it binds to // one element and runs its own animation loop until its child effect closes. diff --git a/demo/web/src/publish.ts b/demo/web/src/publish.ts index 75ac86ded9b..632a080b007 100644 --- a/demo/web/src/publish.ts +++ b/demo/web/src/publish.ts @@ -19,7 +19,7 @@ import "./highlight"; import * as Json from "@moq/json"; import "@moq/publish/element"; // defines import "@moq/publish/ui"; // defines -import { Milli, Nano, now } from "@moq/clock"; +import { Duration, now } from "@moq/clock"; import { type Audio, Net, Signals, Source, type Video } from "@moq/publish"; import type MoqPublish from "@moq/publish/element"; import MoqPublishSupport from "@moq/publish/support/element"; @@ -142,7 +142,7 @@ function encoderConfig(effect: Signals.Effect, target: VideoTarget): Video.Confi codec: effect.get(codec), maxPixels: target.width && target.height ? target.width * target.height : undefined, maxBitrate: br != null ? br * 1000 : undefined, - join: kf != null ? Milli(kf) : undefined, + join: kf != null ? Duration.millis(kf) : undefined, frameRate: target.frameRate, }; } @@ -200,7 +200,7 @@ ui.run((effect) => { const config: Audio.OpusConfig = { mime: "opus", ...(bitrate != null ? { bitrate: bitrate * 1000 } : {}), - ...(frameDuration != null ? { frameDuration: Milli(frameDuration) } : {}), + ...(frameDuration != null ? { frameDuration: Duration.millis(frameDuration) } : {}), ...(complexity != null ? { complexity } : {}), ...(packetLoss != null ? { packetlossperc: packetLoss } : {}), useinbandfec: effect.get(opusFec), @@ -408,7 +408,7 @@ meta.run((effect) => { // A day-long cache so a viewer joining long after the last edit still replays the value. const track = net.createTrack(META_TRACK, { timescale: Net.Time.Timescale.MILLI, - maxAge: Milli(86_400_000), + maxAge: Duration.millis(86_400_000), }); effect.cleanup(() => { track.finish(); @@ -488,28 +488,25 @@ viz.run((effect) => { }); let prevFrames = 0; -let prevWhen = Nano.toMilli(Nano(now())); -viz.interval( - () => { - const at = Nano.toMilli(Nano(now())); - const elapsed = at - prevWhen; - captureGraph.push(elapsed > 0 ? ((frames - prevFrames) * 1000) / elapsed : undefined); - prevFrames = frames; - prevWhen = at; - - const rtt = publish.connection.probe.peek()?.rtt as unknown as number | undefined; - rttGraph.push(rtt && rtt > 0 ? rtt : undefined); - - void publish.connection.stats().then( - (stats) => { - const up = stats?.estimatedSendRate; - uploadGraph.push(up && up > 0 ? up : undefined); - }, - () => uploadGraph.push(undefined), - ); - }, - Nano.fromMilli(Milli(250)), -); +let prevWhen = now(); +viz.interval(() => { + const at = now(); + const elapsed = at.since(prevWhen).asMillis(); + captureGraph.push(elapsed > 0 ? ((frames - prevFrames) * 1000) / elapsed : undefined); + prevFrames = frames; + prevWhen = at; + + const rtt = publish.connection.probe.peek()?.rtt?.asMillis(); + rttGraph.push(rtt && rtt > 0 ? rtt : undefined); + + void publish.connection.stats().then( + (stats) => { + const up = stats?.estimatedSendRate; + uploadGraph.push(up && up > 0 ? up : undefined); + }, + () => uploadGraph.push(undefined), + ); +}, Duration.millis(250)); // Vite re-evaluates this module on hot reload, dropping the references to the // module-scoped effects above. Close them on dispose so they don't get garbage diff --git a/demo/web/src/stats.ts b/demo/web/src/stats.ts index 17c9ad5eb7e..333d23221ad 100644 --- a/demo/web/src/stats.ts +++ b/demo/web/src/stats.ts @@ -23,7 +23,7 @@ */ import "./highlight"; -import { Milli, Nano, wall } from "@moq/clock"; +import { Duration, wall } from "@moq/clock"; import { Net, Signals } from "@moq/hang"; import * as Json from "@moq/json"; @@ -33,7 +33,7 @@ const RELAY_URL = import.meta.env.VITE_RELAY_URL ?? "http://localhost:4443"; const STATS_PREFIX = ".stats/node"; // Rolling history window for the charts. -const SAMPLE = Nano.fromMilli(Milli(1000)); +const SAMPLE = Duration.millis(1000); const MAX_SAMPLES = 90; const $ = (id: string): T => { @@ -318,7 +318,7 @@ sampler.run((effect) => { effect.interval(() => { const all = nodeStats.peek(); const nodes = Object.keys(all).sort(); - const t = wall(); + const t = wall().asUnixMillis(); const agg: Sample = { t, diff --git a/demo/web/src/viz.ts b/demo/web/src/viz.ts index f43f613534e..ef8fb136c94 100644 --- a/demo/web/src/viz.ts +++ b/demo/web/src/viz.ts @@ -9,6 +9,7 @@ * to change the delay. */ +import { Duration } from "@moq/clock"; import type { BufferedRanges, Signals } from "@moq/watch"; import type MoqWatch from "@moq/watch/element"; @@ -153,7 +154,7 @@ const BUFFER_MAX = 4000; // window shown, in milliseconds function drawRanges( canvas: HTMLCanvasElement, ranges: BufferedRanges, - timestamp: number | undefined, + timestamp: Duration | undefined, stalled: boolean, ) { const ctx = canvas.getContext("2d"); @@ -173,11 +174,12 @@ function drawRanges( ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, width, height); if (timestamp === undefined) return; + const playhead = timestamp.asMillis(); for (let i = 0; i < ranges.length; i++) { const range = ranges[i]; - const startMs = range.start - timestamp; - const endMs = range.end - timestamp; + const startMs = range.start.asMillis() - playhead; + const endMs = range.end.asMillis() - playhead; const visibleStart = Math.max(0, startMs); const visibleEnd = Math.min(endMs, BUFFER_MAX); if (visibleEnd <= visibleStart) continue; @@ -256,10 +258,9 @@ export function bufferBars(parent: Signals.Effect, watch: MoqWatch): HTMLElement root.append(viz, legend); - // Set the playback delay. Cast bypasses the branded ms type. + // Set the playback delay, in milliseconds. const setDelay = (ms: number) => { - const clamped = Math.max(0, Math.min(BUFFER_MAX, ms)); - watch.delay = clamped as unknown as typeof watch.delay; + watch.delay = Duration.millis(Math.max(0, Math.min(BUFFER_MAX, ms))); }; const setFromX = (clientX: number) => { @@ -290,12 +291,12 @@ export function bufferBars(parent: Signals.Effect, watch: MoqWatch): HTMLElement : 0; if (delta === 0) return; e.preventDefault(); - setDelay(watch.sync.out.delay.peek() + delta); + setDelay(watch.sync.out.delay.peek().asMillis() + delta); }); // Position the target line from the resolved delay (the live buffer in ms). parent.run((effect) => { - const delay = effect.get(watch.sync.out.delay); + const delay = effect.get(watch.sync.out.delay).asMillis(); const pct = Math.max(0, Math.min(1, delay / BUFFER_MAX)) * 100; target.style.left = `${pct}%`; targetLabel.textContent = `${Math.round(delay)}ms`; diff --git a/doc/lib/js/clock.md b/doc/lib/js/clock.md index e106a11b899..bdd71e56350 100644 --- a/doc/lib/js/clock.md +++ b/doc/lib/js/clock.md @@ -46,8 +46,8 @@ days, then gradually lose sub-microsecond precision. Compare instants only from the same clock. Rust and JS each own their origin: no instant may cross that boundary until the backend explicitly shares one. -`Wall` is wall-clock time, separate from monotonic time: Unix milliseconds `ms` -are `Wall.UNIX_EPOCH.add(Duration.millis(ms))`. Use it for dates, rather than +`Wall` is wall-clock time, separate from monotonic time: `Wall.unixMillis(ms)` +builds one from Unix milliseconds and `asUnixMillis()` reads them back exactly. Use it for dates, rather than measuring elapsed time. A new `Manual` starts at instant zero and 2025-01-01 UTC. `await advance()` moves both readings through each due timer deadline, draining tasks between deadlines, including timers those tasks diff --git a/js/auth/src/cli.test.ts b/js/auth/src/cli.test.ts index 60f74718be9..05170250fdb 100644 --- a/js/auth/src/cli.test.ts +++ b/js/auth/src/cli.test.ts @@ -3,7 +3,7 @@ import { chmodSync, mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs import { tmpdir } from "node:os"; import { extname, join } from "node:path"; import { fileURLToPath } from "node:url"; -import { Wall, wall } from "@moq/clock"; +import { wall } from "@moq/clock"; const CLI = join(import.meta.dir, `cli${extname(fileURLToPath(import.meta.url))}`); @@ -81,9 +81,9 @@ describe("sign", () => { /** The `exp` `args` write, with the wall seconds bracketing the subprocess that wrote it. */ function bracketed(...args: string[]) { - const before = Math.floor(wall().since(Wall.UNIX_EPOCH).asSecs()); + const before = Math.floor(wall().asUnixMillis() / 1000); const value = exp(...args) ?? 0; - const after = Math.floor(wall().since(Wall.UNIX_EPOCH).asSecs()); + const after = Math.floor(wall().asUnixMillis() / 1000); return { before, value, after }; } diff --git a/js/auth/src/cli.ts b/js/auth/src/cli.ts index 073d2bb15a6..58d2c4e6bef 100755 --- a/js/auth/src/cli.ts +++ b/js/auth/src/cli.ts @@ -1,7 +1,7 @@ #!/usr/bin/env node import { closeSync, fchmodSync, openSync, readFileSync, writeFileSync } from "node:fs"; -import { Wall, wall } from "@moq/clock"; +import { wall } from "@moq/clock"; import { Command, Option } from "commander"; import { base64url } from "jose"; import type { Algorithm } from "./algorithm.ts"; @@ -90,7 +90,7 @@ program const exp = options.unbounded ? undefined - : (options.expires ?? Math.floor(wall().since(Wall.UNIX_EPOCH).asSecs()) + (options.ttl ?? 3600)); + : (options.expires ?? Math.floor(wall().asUnixMillis() / 1000) + (options.ttl ?? 3600)); const claims = ClaimsSchema.parse({ root: options.root, ...(options.publish && { publish: options.publish }), diff --git a/js/auth/src/key.test.ts b/js/auth/src/key.test.ts index 4889d899bfe..a0534cf591e 100644 --- a/js/auth/src/key.test.ts +++ b/js/auth/src/key.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { Duration, Manual, Wall, wall } from "@moq/clock"; +import { Manual, Wall, wall } from "@moq/clock"; import { base64url, exportJWK, generateKeyPair, SignJWT } from "jose"; import type { Algorithm } from "./algorithm.ts"; import { authorize, type Claims } from "./claims.ts"; @@ -25,8 +25,8 @@ const testClaims = { root: "test-path", publish: ["test-pub/**"], subscribe: ["test-sub/**"], - exp: Math.floor(wall().since(Wall.UNIX_EPOCH).asSecs() + 60), // 1 minute from now in seconds - iat: Math.floor(wall().since(Wall.UNIX_EPOCH).asSecs()), // now in seconds + exp: Math.floor(wall().asUnixMillis() / 1000 + 60), // 1 minute from now in seconds + iat: Math.floor(wall().asUnixMillis() / 1000), // now in seconds }; type AsymmetricAlgorithm = Exclude; @@ -56,7 +56,7 @@ async function generateAsymmetricKeyPair( test("verify refuses unsafe signed payloads without dropping their restrictions", async () => { const clock = new Manual(); - clock.stepWall(Wall.UNIX_EPOCH.add(Duration.millis(1_000_000))); + clock.stepWall(Wall.unixMillis(1_000_000)); const installed = clock.install(); try { const key = Key.parse(encodeJwk(testKey)); @@ -283,7 +283,7 @@ test("verify - invalid token format", async () => { test("verify - expired token", async () => { const expiredClaims = { ...testClaims, - exp: Math.floor(wall().since(Wall.UNIX_EPOCH).asSecs() - 60), // 1 minute ago in seconds + exp: Math.floor(wall().asUnixMillis() / 1000 - 60), // 1 minute ago in seconds }; const key = Key.parse(encodeJwk(testKey)); @@ -332,8 +332,8 @@ test("round-trip - sign and verify", async () => { root: "test-path", publish: ["test-pub/**"], subscribe: ["test-sub/**"], - exp: Math.floor(wall().since(Wall.UNIX_EPOCH).asSecs() + 60), - iat: Math.floor(wall().since(Wall.UNIX_EPOCH).asSecs()), + exp: Math.floor(wall().asUnixMillis() / 1000 + 60), + iat: Math.floor(wall().asUnixMillis() / 1000), }; const token = await Key.sign(key, originalClaims); @@ -876,7 +876,7 @@ async function signRaw(payload: Record): Promise { // might narrow the grant, and a misspelled `root` would widen it to everything. test("verify - only registered claims", async () => { const key = Key.parse(encodeJwk(testKey)); - const now = Math.floor(wall().since(Wall.UNIX_EPOCH).asSecs()); + const now = Math.floor(wall().asUnixMillis() / 1000); const token = await signRaw({ root: "room", publish: ["**"], iss: "api", sub: "alice", jti: "1", iat: now }); const claims = await Key.verify(key, token); @@ -895,7 +895,7 @@ test("verify - only registered claims", async () => { test("verify - enforces not before", async () => { const key = Key.parse(encodeJwk(testKey)); - const now = Math.floor(wall().since(Wall.UNIX_EPOCH).asSecs()); + const now = Math.floor(wall().asUnixMillis() / 1000); expect((await Key.verify(key, await signRaw({ publish: ["**"], nbf: now - 60 }))).nbf).toBe(now - 60); await expect(Key.verify(key, await signRaw({ publish: ["**"], nbf: now + 3600 }))).rejects.toThrow(); }); diff --git a/js/auth/src/key.ts b/js/auth/src/key.ts index cf98a7363c7..986e2faa875 100644 --- a/js/auth/src/key.ts +++ b/js/auth/src/key.ts @@ -1,4 +1,4 @@ -import { Wall, wall } from "@moq/clock"; +import { wall } from "@moq/clock"; import * as jose from "jose"; import * as z from "zod/mini"; import { type Algorithm, AlgorithmSchema } from "./algorithm.ts"; @@ -247,7 +247,7 @@ async function verify(key: PublicKey | SymmetricKey, token: string): Promise now) throw new Error("Token is not yet valid"); ensureClaimsWithinScope(key, claims); diff --git a/js/clock/api/index.api.md b/js/clock/api/index.api.md index a235e7946b6..cd050364a54 100644 --- a/js/clock/api/index.api.md +++ b/js/clock/api/index.api.md @@ -1,6 +1,39 @@ # `@moq/clock` ```ts +export class Duration { + static readonly ZERO: Duration; + [Symbol.toPrimitive](hint: string): string; + absDiff(other: Duration): Duration; + add(other: Duration): Duration; + asMicros(): number; + asMillis(): number; + asNanos(): number; + asSecs(): number; + clamp(lo: Duration, hi: Duration): Duration; + cmp(other: Duration): -1 | 0 | 1; + div(divisor: number): Duration; + divDuration(other: Duration): number; + eq(other: Duration): boolean; + ge(other: Duration): boolean; + gt(other: Duration): boolean; + isZero(): boolean; + le(other: Duration): boolean; + lt(other: Duration): boolean; + max(other: Duration): Duration; + static micros(value: number): Duration; + static millis(value: number): Duration; + min(other: Duration): Duration; + mul(factor: number): Duration; + static nanos(value: number): Duration; + saturatingSub(other: Duration): Duration; + static secs(value: number): Duration; + sub(other: Duration): Duration; + toJSON(): never; + toString(): string; + valueOf(): never; +} + export class Elapsed extends Error { constructor(); } @@ -9,21 +42,29 @@ export interface Installed { close(): void; } -export const Instant: ((value: number) => Instant) & { - add: (at: Instant, duration: Nano) => Instant; - durationSince: (at: Instant, earlier: Instant) => Nano; - sub: (at: Instant, duration: Nano) => Instant; - zero: Instant; -}; - -export type Instant = number & { - readonly _brand: "clock-instant"; -}; +export class Instant { + static readonly ZERO: Instant; + [Symbol.toPrimitive](hint: string): string; + add(duration: Duration): Instant; + cmp(other: Instant): -1 | 0 | 1; + eq(other: Instant): boolean; + ge(other: Instant): boolean; + gt(other: Instant): boolean; + le(other: Instant): boolean; + lt(other: Instant): boolean; + max(other: Instant): Instant; + min(other: Instant): Instant; + since(earlier: Instant): Duration; + sub(duration: Duration): Instant; + toJSON(): never; + toString(): string; + valueOf(): never; +} export class Interval { - constructor(period: Nano); + constructor(period: Duration); close(): void; - period(): Nano; + period(): Duration; setMissedTickBehavior(behavior: MissedTickBehavior): void; tick(): Promise; } @@ -31,44 +72,16 @@ export class Interval { export class Manual { constructor(); static readonly WALL_START: Wall; - advance(duration: Nano): Promise; + advance(duration: Duration): Promise; drive(work: PromiseLike): Promise; fire(): Promise; install(): Installed; - jump(duration: Nano): void; + jump(duration: Duration): void; now(): Instant; stepWall(wall: Wall): void; wall(): Wall; } -export const Micro: ((value: number) => Micro) & { - fromMilli: (value: Milli) => Micro; - fromNano: (value: Nano) => Micro; - fromSecond: (value: Second) => Micro; - toMilli: (value: Micro) => Milli; - toNano: (value: Micro) => Nano; - toSecond: (value: Micro) => Second; - zero: Micro; -}; - -export type Micro = number & { - readonly _brand: "clock-micro"; -}; - -export const Milli: ((value: number) => Milli) & { - fromMicro: (value: Micro) => Milli; - fromNano: (value: Nano) => Milli; - fromSecond: (value: Second) => Milli; - toMicro: (value: Milli) => Micro; - toNano: (value: Milli) => Nano; - toSecond: (value: Milli) => Second; - zero: Milli; -}; - -export type Milli = number & { - readonly _brand: "clock-milli"; -}; - export const MissedTickBehavior: { readonly Burst: "burst"; readonly Delay: "delay"; @@ -77,52 +90,32 @@ export const MissedTickBehavior: { export type MissedTickBehavior = typeof MissedTickBehavior[keyof typeof MissedTickBehavior]; -export const Nano: ((value: number) => Nano) & { - fromMicro: (value: Micro) => Nano; - fromMilli: (value: Milli) => Nano; - fromSecond: (value: Second) => Nano; - toMicro: (value: Nano) => Micro; - toMilli: (value: Nano) => Milli; - toSecond: (value: Nano) => Second; - zero: Nano; -}; - -export type Nano = number & { - readonly _brand: "clock-nano"; -}; - -export const Second: ((value: number) => Second) & { - fromMicro: (value: Micro) => Second; - fromMilli: (value: Milli) => Second; - fromNano: (value: Nano) => Second; - toMicro: (value: Second) => Micro; - toMilli: (value: Second) => Milli; - toNano: (value: Second) => Nano; - zero: Second; -}; - -export type Second = number & { - readonly _brand: "clock-second"; -}; - -export const Wall: ((unixMillis: number) => Wall) & { - UNIX_EPOCH: Wall; - add: (at: Wall, duration: Nano) => Wall; - durationSince: (at: Wall, earlier: Wall) => Nano; - sub: (at: Wall, duration: Nano) => Wall; -}; - -export type Wall = number & { - readonly _brand: "clock-wall"; -}; +export class Wall { + static readonly UNIX_EPOCH: Wall; + [Symbol.toPrimitive](hint: string): string; + add(duration: Duration): Wall; + asUnixMillis(): number; + cmp(other: Wall): -1 | 0 | 1; + eq(other: Wall): boolean; + ge(other: Wall): boolean; + gt(other: Wall): boolean; + le(other: Wall): boolean; + lt(other: Wall): boolean; + since(earlier: Wall): Duration; + sub(duration: Duration): Wall; + toJSON(): never; + toString(): string; + static unixMillis(millis: number): Wall; + valueOf(): never; +} -export function interval(period: Nano): Interval; +export function interval(period: Duration): Interval; export function now(): Instant; export function origin(): Wall; -export function sleep(duration: Nano, options?: { +export function sleep(duration: Duration, options?: { ref?: boolean; signal?: AbortSignal; }): Promise; @@ -132,7 +125,7 @@ export function sleepUntil(at: Instant, options?: { signal?: AbortSignal; }): Promise; -export function timeout(duration: Nano, operation: PromiseLike): Promise; +export function timeout(duration: Duration, operation: PromiseLike): Promise; export function wall(): Wall; diff --git a/js/clock/src/index.test.ts b/js/clock/src/index.test.ts index 63fafad956f..48b1ae64a0d 100644 --- a/js/clock/src/index.test.ts +++ b/js/clock/src/index.test.ts @@ -31,9 +31,9 @@ function manual(): Manual { } // Read an instant or wall time as a plain number for assertions. const ns = (at: Instant): number => at.since(Instant.ZERO).asNanos(); -const ms = (at: Wall): number => at.since(Wall.UNIX_EPOCH).asMillis(); +const ms = (at: Wall): number => at.asUnixMillis(); const instant = (nanos: number): Instant => Instant.ZERO.add(Duration.nanos(nanos)); -const unix = (millis: number): Wall => Wall.UNIX_EPOCH.add(Duration.millis(millis)); +const unix = (millis: number): Wall => Wall.unixMillis(millis); const START = ms(Manual.WALL_START); test("durations convert units and refuse to become numbers", () => { @@ -67,6 +67,15 @@ test("durations convert units and refuse to become numbers", () => { } }); +test("wall time round-trips Unix milliseconds exactly", () => { + // Past 2^53 ns, a detour through a Duration since the epoch would round. + for (const millis of [0, 1_735_689_600_001, 4_102_444_800_123, Number.MAX_SAFE_INTEGER]) { + expect(Wall.unixMillis(millis).asUnixMillis()).toBe(millis); + } + expect(() => Wall.unixMillis(-1)).toThrow(RangeError); + expect(() => Wall.unixMillis(Number.NaN)).toThrow(RangeError); +}); + test("manual reads and wall corrections share a clock without inventing elapsed time", () => { const clock = manual(); expect(ns(now())).toBe(0); diff --git a/js/clock/src/types.ts b/js/clock/src/types.ts index 3666df5fa08..ada5f247ba7 100644 --- a/js/clock/src/types.ts +++ b/js/clock/src/types.ts @@ -290,8 +290,7 @@ export class Instant { /** * A point in wall-clock time, separate from monotonic time, mirroring `kio::clock::Wall`. * - * Convert Unix milliseconds with `Wall.UNIX_EPOCH.add(Duration.millis(ms))` and back with - * `wall.since(Wall.UNIX_EPOCH).asMillis()`. + * Convert Unix milliseconds exactly with `Wall.unixMillis(ms)` and back with `asUnixMillis()`. */ export class Wall { /** 1970-01-01T00:00:00Z. */ @@ -310,6 +309,16 @@ export class Wall { wallMillis = (at) => at[VALUE]; } + /** The time `millis` Unix milliseconds after the epoch; throws a `RangeError` before it or past the safe range. */ + static unixMillis(millis: number): Wall { + return new Wall(checked(millis, "wall time")); + } + + /** Unix milliseconds, exact: `since(Wall.UNIX_EPOCH)` goes through nanoseconds, which pass 2^53. */ + asUnixMillis(): number { + return this[VALUE]; + } + /** This time moved forward by `duration`. */ add(duration: Duration): Wall { return new Wall(checked(this[VALUE] + duration.asMillis(), "wall time")); @@ -357,6 +366,7 @@ export class Wall { /** The time as an ISO 8601 string, or Unix milliseconds past `Date`'s range. */ toString(): string { + // biome-ignore lint/style/noRestrictedGlobals: formats a time, never reads the host clock. return this[VALUE] <= 8.64e15 ? new Date(this[VALUE]).toISOString() : `Wall(${this[VALUE]}ms)`; } @@ -365,7 +375,7 @@ export class Wall { return refuse("Wall"); } - /** Refuses: serialize `since(Wall.UNIX_EPOCH)` with an explicit unit instead. */ + /** Refuses: serialize `asUnixMillis()` instead. */ toJSON(): never { return refuse("Wall"); } diff --git a/js/hang/api/container.api.md b/js/hang/api/container.api.md index f2e81f7f2cb..0e16dbd15d8 100644 --- a/js/hang/api/container.api.md +++ b/js/hang/api/container.api.md @@ -3,15 +3,13 @@ ```ts import { AudioConfig } from "@moq/hang/catalog"; import { Format as Format_1 } from "@moq/hang/container"; -import { Micro } from "@moq/clock"; -import { Milli } from "@moq/clock"; import { Net } from "@moq/hang"; import { Signals } from "@moq/hang"; import { VideoConfig } from "@moq/hang/catalog"; export interface BufferedRange { - end: Milli; - start: Milli; + end: Net.Clock.Duration; + start: Net.Clock.Duration; } export type BufferedRanges = BufferedRange[]; @@ -21,27 +19,27 @@ export class Consumer { readonly buffered: Signals.Getter; close(): void; next(): Promise; - readonly spread: Signals.Getter; + readonly spread: Signals.Getter; } export interface ConsumerProps { delay?: Signals.GetterInit; format: Format; predecessor?: Consumer; - warmup?: Milli; + warmup?: Net.Clock.Duration; } export interface Format { decode(payload: Uint8Array, timestamp: Net.Time.Timestamp | undefined): Frame[]; - end?(frame: Frame): Micro | undefined; + end?(frame: Frame): Net.Clock.Duration | undefined; readonly kind?: "audio" | "video" | "data"; } export interface Frame { - duration?: Micro; + duration?: Net.Clock.Duration; keyframe: boolean; payload: Uint8Array; - timestamp: Micro; + timestamp: Net.Clock.Duration; } export namespace Legacy { @@ -50,48 +48,48 @@ export namespace Legacy { export class Format implements Format_1 { constructor(config: AudioConfig | VideoConfig | "audio" | "video" | "data"); decode(frame: Uint8Array): Frame[]; - end(frame: Frame): Micro | undefined; - finishGroup(group: Net.Group.Producer, end?: Micro): void; + end(frame: Frame): Net.Clock.Duration | undefined; + finishGroup(group: Net.Group.Producer, end?: Net.Clock.Duration): void; readonly kind: "audio" | "video" | "data"; } export { Frame }; export class Producer { constructor(track: Net.Track.Producer, format: Legacy.Format); close(err?: Error): void; - discontinuity(end?: Micro): void; - encode(data: Uint8Array | Legacy.Source, timestamp: Micro, keyframe: boolean): void; + discontinuity(endpoint?: Net.Clock.Duration): void; + encode(data: Uint8Array | Legacy.Source, pts: Net.Clock.Duration, keyframe: boolean): void; } export interface Source { byteLength: number; copyTo(buffer: Uint8Array): void; } - export function encodeFrame(source: Uint8Array | Legacy.Source, timestamp: Micro): Uint8Array; + export function encodeFrame(source: Uint8Array | Legacy.Source, timestamp: Net.Clock.Duration): Uint8Array; } export * as Loc from "@moq/loc"; -export const MAX_AGE: Milli; +export const MAX_AGE: Net.Clock.Duration; export type Read = { frame: ReceivedFrame; group: bigint; kind: "frame"; } | { - duration: Micro; + duration: Net.Clock.Duration; kind: "gap"; - timestamp: Micro; + timestamp: Net.Clock.Duration; } | { - end: Micro; + end: Net.Clock.Duration; group: bigint; kind: "end"; }; export interface ReceivedFrame extends Frame { - arrival: Milli; + arrival: Net.Clock.Instant; } export type TrackInfoOptions = { - maxAge?: Milli | null; + maxAge?: Net.Clock.Duration | null; priority: number; }; diff --git a/js/hang/bench/buffered.ts b/js/hang/bench/buffered.ts index acce7700681..20aa8ce9431 100644 --- a/js/hang/bench/buffered.ts +++ b/js/hang/bench/buffered.ts @@ -82,7 +82,11 @@ async function drain(player: Player, expected: number[]): Promise { gaps++; continue; } - if (read.kind !== "frame" || read.frame.timestamp.asMicros() !== want || read.frame.payload[0] !== PAYLOAD[0]) + if ( + read.kind !== "frame" || + read.frame.timestamp.asMicros() !== want || + read.frame.payload[0] !== PAYLOAD[0] + ) throw new Error("frame missing or reordered"); break; } @@ -91,7 +95,9 @@ async function drain(player: Player, expected: number[]): Promise { } function ranges(player: Player): string { - return JSON.stringify(player.consumer.buffered.peek().map((r) => ({ start: r.start.asMillis(), end: r.end.asMillis() }))); + return JSON.stringify( + player.consumer.buffered.peek().map((r) => ({ start: r.start.asMillis(), end: r.end.asMillis() })), + ); } /** Return elapsed ns, the measured operations, gaps and warnings for one case. */ diff --git a/js/hang/src/container/consumer.backpressure.test.ts b/js/hang/src/container/consumer.backpressure.test.ts index c9c9a0ff33b..8c64f0bffd5 100644 --- a/js/hang/src/container/consumer.backpressure.test.ts +++ b/js/hang/src/container/consumer.backpressure.test.ts @@ -228,7 +228,7 @@ test("Consumer charges a small view of a large wire frame the wire frame", async const padding = new Uint8Array(60_000); for (let i = 0; i < 8; i++) { padded.writeFrame({ - payload: encodeFrame(padding, Duration.micros((10_000 + i))), + payload: encodeFrame(padding, Duration.micros(10_000 + i)), timestamp: Time.Timestamp.now(), }); } @@ -236,10 +236,16 @@ test("Consumer charges a small view of a large wire frame the wire frame", async // The padded frames fill the max buffer behind the stalled group, which moves the cursor on to them. // Charging only the one byte views, the buffer never fills and the reader waits on the stall. - expect(await within(consumer.next())).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(0) } }); + expect(await within(consumer.next())).toMatchObject({ + kind: "frame", + frame: { timestamp: Duration.micros(0) }, + }); expect(await within(consumer.next())).toMatchObject({ kind: "gap" }); for (let i = 0; i < 8; i++) { - expect(await within(consumer.next())).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(10_000 + i) } }); + expect(await within(consumer.next())).toMatchObject({ + kind: "frame", + frame: { timestamp: Duration.micros(10_000 + i) }, + }); } } finally { consumer.close(); @@ -268,8 +274,14 @@ test("Consumer stamps frames the max buffer held back with when they landed, not // The reader is slow: nothing is read until well after both frames landed. await clock.advance(Duration.millis(750)); - expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(0), arrival: Instant.ZERO } }); - expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(10_000), arrival: Instant.ZERO.add(Duration.millis(250)) } }); + expect(await consumer.next()).toMatchObject({ + kind: "frame", + frame: { timestamp: Duration.micros(0), arrival: Instant.ZERO }, + }); + expect(await consumer.next()).toMatchObject({ + kind: "frame", + frame: { timestamp: Duration.micros(10_000), arrival: Instant.ZERO.add(Duration.millis(250)) }, + }); } finally { consumer.close(); track.close(); @@ -329,7 +341,10 @@ for (const maxBuffer of [0, 256]) { expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(0) } }); expect(await consumer.next()).toMatchObject({ kind: "gap" }); - expect(await consumer.next()).toMatchObject({ kind: "frame", frame: { timestamp: Duration.micros(10_000) } }); + expect(await consumer.next()).toMatchObject({ + kind: "frame", + frame: { timestamp: Duration.micros(10_000) }, + }); } finally { consumer.close(); track.close(); @@ -358,7 +373,11 @@ test("Consumer moves past a stalled backlog group below the cursor once the max newer.finish(); expect(await consumer.next()).toMatchObject({ kind: "gap" }); - expect(await consumer.next()).toMatchObject({ kind: "frame", group: 4n, frame: { timestamp: Duration.micros(40_000) } }); + expect(await consumer.next()).toMatchObject({ + kind: "frame", + group: 4n, + frame: { timestamp: Duration.micros(40_000) }, + }); } finally { consumer.close(); track.close(); @@ -393,7 +412,11 @@ test("Consumer reads what a promoted head already holds before skipping it under // Group 0 is skipped, but group 1 is read once promoted rather than skipped before its task runs. expect(await consumer.next()).toMatchObject({ kind: "gap" }); - expect(await consumer.next()).toMatchObject({ kind: "frame", group: 1n, frame: { timestamp: Duration.micros(10_000) } }); + expect(await consumer.next()).toMatchObject({ + kind: "frame", + group: 1n, + frame: { timestamp: Duration.micros(10_000) }, + }); } finally { consumer.close(); track.close(); @@ -503,7 +526,11 @@ test("Consumer reads a finished marker group's end before skipping under pressur // Group 0 is skipped, and group 1 declares its end before group 2 is read. expect(await within(consumer.next())).toMatchObject({ kind: "gap" }); expect(await within(consumer.next())).toMatchObject({ kind: "end", group: 1n }); - expect(await within(consumer.next())).toMatchObject({ kind: "frame", group: 2n, frame: { timestamp: Duration.micros(20_000) } }); + expect(await within(consumer.next())).toMatchObject({ + kind: "frame", + group: 2n, + frame: { timestamp: Duration.micros(20_000) }, + }); } finally { consumer.close(); track.close(); @@ -542,7 +569,11 @@ test("Consumer reads a group whose frame fails to read as cut short while the re armed = true; expect(await pending).toMatchObject({ kind: "gap" }); - expect(await within(consumer.next())).toMatchObject({ kind: "frame", group: 1n, frame: { timestamp: Duration.micros(10_000) } }); + expect(await within(consumer.next())).toMatchObject({ + kind: "frame", + group: 1n, + frame: { timestamp: Duration.micros(10_000) }, + }); } finally { consumer.close(); track.close(); diff --git a/js/hang/src/container/consumer.holes.test.ts b/js/hang/src/container/consumer.holes.test.ts index 37b4a8184ae..b6d76bccba1 100644 --- a/js/hang/src/container/consumer.holes.test.ts +++ b/js/hang/src/container/consumer.holes.test.ts @@ -24,7 +24,10 @@ test.each([0, 100])("a sequence hole before a paused data marker expires at %sms })(); try { const first = track.createGroup(0n); - first.writeFrame({ payload: encodeFrame(new Uint8Array([1]), Duration.micros(10_000)), timestamp: Time.Timestamp.now() }); + first.writeFrame({ + payload: encodeFrame(new Uint8Array([1]), Duration.micros(10_000)), + timestamp: Time.Timestamp.now(), + }); first.finish(); await flush(); expect(results).toHaveLength(1); @@ -73,7 +76,10 @@ test("a filled hole cancels its timer and the next hole gets a fresh budget", as const write = (sequence: bigint, timestamp?: number) => { const group = track.createGroup(sequence); group.writeFrame({ - payload: timestamp === undefined ? new Uint8Array() : encodeFrame(new Uint8Array([1]), Duration.micros(timestamp)), + payload: + timestamp === undefined + ? new Uint8Array() + : encodeFrame(new Uint8Array([1]), Duration.micros(timestamp)), timestamp: Time.Timestamp.fromMicros(timestamp ?? 20_000), }); group.finish(); @@ -212,7 +218,10 @@ test("a hole in a drained backlog is late from the earliest arrival past it, not group.finish(); }; const first = track.createGroup(0n); - first.writeFrame({ payload: encodeFrame(new Uint8Array([1]), Duration.micros(0)), timestamp: Time.Timestamp.fromMicros(0) }); + first.writeFrame({ + payload: encodeFrame(new Uint8Array([1]), Duration.micros(0)), + timestamp: Time.Timestamp.fromMicros(0), + }); first.finish(); marker(5n); await clock.advance(Duration.millis(900)); @@ -292,7 +301,11 @@ test.each([true, false])("the head after a declared end is waited for (arrives: // The end, then the stopped encoder's final packet, as a native publisher writes them. write(1n, [60_000, new Uint8Array()], [40_000]); await flush(); - expect(results).toEqual([frame(0n, 0), { kind: "end", group: 1n, end: Duration.micros(60_000) }, frame(1n, 40_000)]); + expect(results).toEqual([ + frame(0n, 0), + { kind: "end", group: 1n, end: Duration.micros(60_000) }, + frame(1n, 40_000), + ]); write(3n, [60_060_000]); await flush(); await clock.advance(Duration.millis(299)); diff --git a/js/hang/src/container/consumer.outoforder.test.ts b/js/hang/src/container/consumer.outoforder.test.ts index f5acd8de43c..74330cec692 100644 --- a/js/hang/src/container/consumer.outoforder.test.ts +++ b/js/hang/src/container/consumer.outoforder.test.ts @@ -75,7 +75,10 @@ async function drain(consumer: Consumer): Promise<[bigint, number | undefined][] // the budget. A group below that floor is never delivered and adds no gap. Mirrors Rust's // `startup_at_the_publishers_start_over_a_newer_first_arrival`. test("the head of the window arriving after the live edge is delivered first", async () => { - const track = new Track.Producer("test").accept({ timescale: Time.Timescale.MILLI, maxAge: Duration.millis(30_000) }); + const track = new Track.Producer("test").accept({ + timescale: Time.Timescale.MILLI, + maxAge: Duration.millis(30_000), + }); const consumer = new Consumer( track.subscribe({ delay: { max: Duration.millis(5000) }, ranges: [{ start: { absolute: 1n } }] }), { format: new LegacyFormat("data"), delay: { max: Duration.millis(5000) } }, @@ -106,7 +109,10 @@ test("the head of the window arriving after the live edge is delivered first", a // loop consumes faster than the network delivers). Removing it at that instant silently truncates // its tail, so removal must wait for the group to finish. test("a head group still downloading is not truncated", async () => { - const track = new Track.Producer("test").accept({ timescale: Time.Timescale.MILLI, maxAge: Duration.millis(30_000) }); + const track = new Track.Producer("test").accept({ + timescale: Time.Timescale.MILLI, + maxAge: Duration.millis(30_000), + }); const consumer = new Consumer( track.subscribe({ delay: { max: Duration.millis(5000) }, ranges: [{ start: { absolute: 1n } }] }), { format: new LegacyFormat("data"), delay: { max: Duration.millis(5000) } }, @@ -141,7 +147,10 @@ test("a head group still downloading is not truncated", async () => { // budget, or forever on an open track, for groups it never gets. Mirrors Rust's // `an_excluded_gap_between_ranges_does_not_stall`. test("an excluded gap between ranges does not stall", async () => { - const track = new Track.Producer("test").accept({ timescale: Time.Timescale.MILLI, maxAge: Duration.millis(30_000) }); + const track = new Track.Producer("test").accept({ + timescale: Time.Timescale.MILLI, + maxAge: Duration.millis(30_000), + }); const consumer = new Consumer( track.subscribe({ delay: { max: Duration.millis(10_000) }, @@ -162,13 +171,22 @@ test("an excluded gap between ranges does not stall", async () => { // which counts a newest group that held no frame yet, rather than wait under the budget for a group // below it that never comes. Mirrors Rust's `a_resolved_relative_floor_rises_to_the_publishers_start`. test("a resolved relative floor rises to the publisher's start", async () => { - const track = new Track.Producer("test").accept({ timescale: Time.Timescale.MILLI, maxAge: Duration.millis(30_000) }); + const track = new Track.Producer("test").accept({ + timescale: Time.Timescale.MILLI, + maxAge: Duration.millis(30_000), + }); for (const sequence of [0n, 1n, 2n, 3n, 4n]) publish(track, sequence, Number(sequence) * 100); - const subscriber = track.subscribe({ delay: { max: Duration.millis(10_000) }, ranges: [{ start: { relative: 0n } }] }); + const subscriber = track.subscribe({ + delay: { max: Duration.millis(10_000) }, + ranges: [{ start: { relative: 0n } }], + }); expect(subscriber.floor()).toBe(4n); // A session declares the publisher's start; a local track has none, so stand in for it. subscriber.start = async () => 5n; - const consumer = new Consumer(subscriber, { format: new LegacyFormat("data"), delay: { max: Duration.millis(10_000) } }); + const consumer = new Consumer(subscriber, { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(10_000) }, + }); publish(track, 5n, 500); expect(await drain(consumer)).toEqual([[5n, 5]]); diff --git a/js/hang/src/container/consumer.test.ts b/js/hang/src/container/consumer.test.ts index 138ff0f60aa..e13fe20d41d 100644 --- a/js/hang/src/container/consumer.test.ts +++ b/js/hang/src/container/consumer.test.ts @@ -62,7 +62,9 @@ function at(ticks: number): Time.Timestamp { // Fixed cadence keeps timing-only tests independent of CMAF parsing. const timedLegacy: ContainerFormat = { decode(payload) { - return new LegacyFormat("video").decode(payload).map((frame) => ({ ...frame, duration: Duration.micros(33_333) })); + return new LegacyFormat("video") + .decode(payload) + .map((frame) => ({ ...frame, duration: Duration.micros(33_333) })); }, }; /** A one-byte legacy frame at the test track timestamp. */ @@ -157,7 +159,9 @@ test("Legacy Producer refuses a group below the previous group start", () => { const producer = new LegacyProducer(track, new LegacyFormat("video")); producer.encode(new Uint8Array([1]), Duration.micros(20_000), true); producer.encode(new Uint8Array([1]), Duration.micros(33_000), false); - expect(() => producer.encode(new Uint8Array([1]), Duration.micros(16_000), true)).toThrow("below the previous group start"); + expect(() => producer.encode(new Uint8Array([1]), Duration.micros(16_000), true)).toThrow( + "below the previous group start", + ); producer.close(); }); @@ -293,7 +297,9 @@ test("Legacy Producer refuses a keyframe that rewinds the timeline", () => { const producer = new LegacyProducer(track, new LegacyFormat("video")); producer.encode(new Uint8Array([1]), Duration.micros(20_000), true); producer.encode(new Uint8Array([2]), Duration.micros(30_000), false); - expect(() => producer.encode(new Uint8Array([3]), Duration.micros(0), true)).toThrow("below the previous group start"); + expect(() => producer.encode(new Uint8Array([3]), Duration.micros(0), true)).toThrow( + "below the previous group start", + ); producer.close(); }); @@ -398,7 +404,10 @@ test("Legacy Producer discontinuity on a data track reads as an end at the edge" producer.encode(new Uint8Array([1]), Duration.micros(5_000_000), true); producer.close(); - const consumer = new Consumer(subscriber, { format: new LegacyFormat("data"), delay: { max: Duration.millis(30_000) } }); + const consumer = new Consumer(subscriber, { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(30_000) }, + }); const items: string[] = []; for (let read = await consumer.next(); read; read = await consumer.next()) items.push(describe(read)); expect(items).toEqual(["0", "20000", "end 20000", "5000000"]); @@ -553,7 +562,11 @@ async function drainFrames(consumer: Consumer): Promise<{ timestamp: number; gro const result = await poll(consumer.next()); if (result === "pending" || result === undefined) break; if (result.kind === "frame") { - frames.push({ timestamp: result.frame.timestamp.asMicros(), group: result.group, keyframe: result.frame.keyframe }); + frames.push({ + timestamp: result.frame.timestamp.asMicros(), + group: result.group, + keyframe: result.frame.keyframe, + }); } } return frames; @@ -575,7 +588,10 @@ function frameOf(read: Read | string | undefined): Frame { test("Consumer delivers frames from a single group", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(500) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(500) }, + }); writeGroupWithLegacyFrames(track, 0n, [0, 33_000]); track.finish(); @@ -590,7 +606,10 @@ test("Consumer delivers frames from a single group", async () => { test("Consumer forces keyframe true at index 0", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(500) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(500) }, + }); writeGroupWithLegacyFrames(track, 0n, [0, 33_000]); track.finish(); @@ -679,7 +698,10 @@ for (const [where, payloads] of [ // Errors come in delivery order, so a decode error waits behind the items ahead of it, a gap included. test("Consumer delivers everything ahead of a decode error", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(10_000) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(10_000) }, + }); writeGroupWithLegacyFrames(track, 0n, [0]); writeGroupWithLegacyFrames(track, 2n, [100_000]); @@ -795,7 +817,10 @@ test("Consumer keeps frames decoded before a group reset (truncated GoP)", async test("Consumer close returns undefined from next()", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(500) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(500) }, + }); const promise = consumer.next(); consumer.close(); @@ -806,7 +831,10 @@ test("Consumer close returns undefined from next()", async () => { test("Consumer throws on concurrent next() calls", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(500) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(500) }, + }); // First call blocks waiting for data void consumer.next(); @@ -819,7 +847,10 @@ test("Consumer throws on concurrent next() calls", async () => { test("Consumer skips groups via PTS-span when over the max delay", async () => { const track = new Track.Producer("test"); // Zero max delay = skip everything that's not the latest - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(0) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(0) }, + }); // Write groups with increasing timestamps. With a 0 max delay, any PTS span > 0 triggers skip. writeGroupWithLegacyFrames(track, 0n, [0]); @@ -850,7 +881,7 @@ test("Consumer measures arrivals as they land", async () => { // Groups arriving exactly as fast as their media, across four resample intervals. Nothing is // late, so the evidence pulls the estimate down from the cold start. for (let i = 0; i < 5; i++) { - writeGroupWithLegacyFrames(track, BigInt(i), [(i * 520_000)]); + writeGroupWithLegacyFrames(track, BigInt(i), [i * 520_000]); await clock.advance(Duration.millis(520)); } expect(consumer.spread.peek().asMillis()).toBeLessThan(100); @@ -884,7 +915,7 @@ test("Consumer does not relax its measurement across a declared silence", async let media = 0; const send = async (count: number) => { for (let i = 0; i < count; i++) { - for (const producer of producers) producer.encode(payload, Duration.micros((media * 1000)), true); + for (const producer of producers) producer.encode(payload, Duration.micros(media * 1000), true); media += 520; await clock.advance(Duration.millis(520)); } @@ -918,7 +949,10 @@ test("Consumer does not relax its measurement across a declared silence", async test("Consumer delivers groups in sequence order regardless of arrival order", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(500) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(500) }, + }); writeGroupWithLegacyFrames(track, 2n, [60_000]); writeGroupWithLegacyFrames(track, 0n, [0]); @@ -940,7 +974,10 @@ test("Consumer delivers groups in sequence order regardless of arrival order", a // group arriving there is never delivered and adds no gap. Mirrors Rust's consumer. test("Consumer drops a group that arrives below the cursor", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(500) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(500) }, + }); // Group 5 arrives first, and delivery starts there: the track reports no start. writeGroupWithLegacyFrames(track, 5n, [100_000]); @@ -966,7 +1003,10 @@ test("Consumer drops a group that arrives below the cursor", async () => { test("Consumer next() yields no gap before the first frame", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(500) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(500) }, + }); writeGroupWithLegacyFrames(track, 0n, [0, 33_000]); writeGroupWithLegacyFrames(track, 1n, [66_000]); @@ -988,7 +1028,10 @@ test("Consumer next() yields no gap before the first frame", async () => { test("Consumer reads nothing after close, even the frame a gap was returned ahead of", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: Duration.millis(0) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("audio"), + delay: { max: Duration.millis(0) }, + }); writeGroupWithLegacyFrames(track, 0n, [0]); await flush(); @@ -997,7 +1040,11 @@ test("Consumer reads nothing after close, even the frame a gap was returned ahea // Group 1 never arrives, so group 2's frame is deferred behind a gap. writeGroupWithLegacyFrames(track, 2n, [100_000]); await flush(); - expect(await consumer.next()).toEqual({ kind: "gap", timestamp: Duration.micros(0), duration: Duration.micros(100_000) }); + expect(await consumer.next()).toEqual({ + kind: "gap", + timestamp: Duration.micros(0), + duration: Duration.micros(100_000), + }); consumer.close(); expect(await consumer.next()).toBeUndefined(); @@ -1073,7 +1120,10 @@ test("Consumer reads an empty LOC payload as the frame's duration", async () => ], ]); - const consumer = new Consumer(replay(track), { format: new LocFormat("video"), delay: { max: Duration.millis(500) } }); + const consumer = new Consumer(replay(track), { + format: new LocFormat("video"), + delay: { max: Duration.millis(500) }, + }); await flush(); const media = frameOf(await consumer.next()); expect(media.payload).toEqual(new Uint8Array([0xde, 0xad])); @@ -1096,7 +1146,10 @@ test("Consumer passes over LOC duration markers", async () => { ], ]); - const consumer = new Consumer(replay(track), { format: new LocFormat("video"), delay: { max: Duration.millis(500) } }); + const consumer = new Consumer(replay(track), { + format: new LocFormat("video"), + delay: { max: Duration.millis(500) }, + }); await flush(); const first = frameOf(await consumer.next()); expect(first.payload).toEqual(new Uint8Array([0xde, 0xad])); @@ -1144,7 +1197,10 @@ const wallClock = () => Time.Timestamp.now(); test("Consumer aborts a group below the previous group start", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(30_000) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(30_000) }, + }); writeGroupWithLegacyFrames(track, 0n, [10_000_000], wallClock); writeGroupWithLegacyFrames(track, 1n, [0, 100_000], wallClock); @@ -1159,7 +1215,10 @@ test("Consumer aborts a group below the previous group start", async () => { // A later group's rewind does not mask an earlier group's decode error. test("Consumer throws the first error in delivery order", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(30_000) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(30_000) }, + }); writeGroupWithLegacyFrames(track, 0n, [10_000_000], wallClock); const malformed = track.createGroup(1n); @@ -1187,7 +1246,11 @@ test("Consumer checks a whole decoded batch before a skip drops its group", asyn decode(frame: Uint8Array): Frame[] { const timestamps = JSON.parse(new TextDecoder().decode(frame)) as number[]; for (const timestamp of timestamps) decoded.get(timestamp)?.(); - return timestamps.map((timestamp) => ({ payload: frame, timestamp: Duration.micros(timestamp), keyframe: true })); + return timestamps.map((timestamp) => ({ + payload: frame, + timestamp: Duration.micros(timestamp), + keyframe: true, + })); }, }; const write = (sequence: bigint, timestamps: number[]) => { @@ -1226,7 +1289,10 @@ test("Consumer checks a whole decoded batch before a skip drops its group", asyn test("Consumer aborts a rewind carried by a later arrival", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(30_000) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(30_000) }, + }); writeGroupWithLegacyFrames(track, 0n, [10_000_000], wallClock); await flush(); @@ -1245,7 +1311,10 @@ test("Consumer aborts a rewind carried by a later arrival", async () => { // rewind, so the detector compares against the previous group's start. test("Consumer treats B-frame reordering within a group as continuous", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(30_000) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(30_000) }, + }); writeGroupWithLegacyFrames(track, 0n, [0, 66_000, 33_000]); await flush(); @@ -1266,7 +1335,10 @@ test("Consumer treats B-frame reordering within a group as continuous", async () test("Consumer accepts open-GOP leading pictures above the previous group", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(30_000) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(30_000) }, + }); writeGroupWithLegacyFrames(track, 0n, [0, 33_000]); writeGroupWithLegacyFrames(track, 1n, [66_000, 50_000]); @@ -1282,7 +1354,10 @@ test("Consumer accepts open-GOP leading pictures above the previous group", asyn // the max delay loses nothing. test("Consumer reads no gap when retiring a fully delivered group", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: Duration.millis(150) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("audio"), + delay: { max: Duration.millis(150) }, + }); writeGroupWithLegacyFrames(track, 0n, [0]); await flush(); @@ -1301,7 +1376,10 @@ test("Consumer reads no gap when retiring a fully delivered group", async () => // An unread trailing endpoint carries no media, so retiring its group loses nothing. test("Consumer reads no gap when retiring a group holding only its endpoint", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("video"), delay: { max: Duration.millis(150) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("video"), + delay: { max: Duration.millis(150) }, + }); const group = track.createGroup(0n); group.writeFrame({ payload: encodeLegacy(0), timestamp: Time.Timestamp.fromMicros(0) }); @@ -1326,7 +1404,10 @@ test("Consumer reads no gap when retiring a group holding only its endpoint", as // next group is adjacent. test("Consumer reads a gap when retiring a truncated group", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: Duration.millis(150) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("audio"), + delay: { max: Duration.millis(150) }, + }); const group = track.createGroup(0n); group.writeFrame({ payload: encodeLegacy(0), timestamp: Time.Timestamp.fromMicros(0) }); @@ -1339,7 +1420,11 @@ test("Consumer reads a gap when retiring a truncated group", async () => { await flush(); // Legacy carries no duration, so the gap starts at the last frame read. - expect(await consumer.next()).toEqual({ kind: "gap", timestamp: Duration.micros(0), duration: Duration.micros(100_000) }); + expect(await consumer.next()).toEqual({ + kind: "gap", + timestamp: Duration.micros(0), + duration: Duration.micros(100_000), + }); expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(100_000); consumer.close(); @@ -1348,7 +1433,10 @@ test("Consumer reads a gap when retiring a truncated group", async () => { // An open group may still have a tail in flight, so adjacency proves nothing when it is retired. test("Consumer reads a gap when retiring an open group", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: Duration.millis(150) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("audio"), + delay: { max: Duration.millis(150) }, + }); const group = track.createGroup(0n); group.writeFrame({ payload: encodeLegacy(0), timestamp: Time.Timestamp.fromMicros(0) }); @@ -1361,7 +1449,11 @@ test("Consumer reads a gap when retiring an open group", async () => { await flush(); // Legacy carries no duration, so the gap starts at the last frame read. - expect(await consumer.next()).toEqual({ kind: "gap", timestamp: Duration.micros(0), duration: Duration.micros(100_000) }); + expect(await consumer.next()).toEqual({ + kind: "gap", + timestamp: Duration.micros(0), + duration: Duration.micros(100_000), + }); expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(100_000); group.finish(); @@ -1372,7 +1464,10 @@ test("Consumer reads a gap when retiring an open group", async () => { test("Consumer buffered signal updates as frames arrive", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(500) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(500) }, + }); expect(consumer.buffered.peek()).toEqual([]); @@ -1395,7 +1490,10 @@ test("Consumer buffered signal updates as frames arrive", async () => { test("Consumer recovers from gap in group sequence numbers", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(100) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(100) }, + }); writeGroupWithLegacyFrames(track, 0n, [0, 20_000]); writeGroupWithLegacyFrames(track, 1n, [40_000, 60_000]); @@ -1530,7 +1628,7 @@ const durationFormat: ContainerFormat = { return [ { payload: frame, - timestamp: Duration.micros((frame[0] * 1000)), + timestamp: Duration.micros(frame[0] * 1000), duration: Duration.micros(33_000), keyframe: false, }, @@ -1568,7 +1666,7 @@ test("Consumer does not duration-skip when the gap is not covered", async () => return [ { payload: frame, - timestamp: Duration.micros((frame[0] * 1000)), + timestamp: Duration.micros(frame[0] * 1000), duration: Duration.micros(10_000), keyframe: false, }, @@ -1814,7 +1912,10 @@ test("Consumer waits on a gap within the budget, then plays the head once it exc // adjacency doesn't rule out a group the max delay check dropped on the way past. test("Consumer yields no gap while nothing is dropped", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(100) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(100) }, + }); writeGroupWithLegacyFrames(track, 0n, [0, 33_000]); await flush(); @@ -1831,7 +1932,10 @@ test("Consumer yields no gap while nothing is dropped", async () => { test("Consumer reads a marker group as an end, not a gap", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: Duration.millis(2_000) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("audio"), + delay: { max: Duration.millis(2_000) }, + }); writeGroupWithLegacyFrames(track, 0n, [0]); writeMarkerGroup(track, 1n, 0); @@ -1848,7 +1952,10 @@ test("Consumer reads a marker group as an end, not a gap", async () => { test("Consumer empty groups mean nothing", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: Duration.millis(2_000) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("audio"), + delay: { max: Duration.millis(2_000) }, + }); writeGroupWithLegacyFrames(track, 0n, [0]); const empty = track.createGroup(1n); @@ -1864,7 +1971,10 @@ test("Consumer empty groups mean nothing", async () => { test("Consumer reads a latency skip as one gap", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: Duration.millis(0) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("audio"), + delay: { max: Duration.millis(0) }, + }); writeGroupWithLegacyFrames(track, 0n, [0]); await flush(); @@ -1873,7 +1983,11 @@ test("Consumer reads a latency skip as one gap", async () => { writeGroupWithLegacyFrames(track, 2n, [100_000]); await flush(); - expect(await consumer.next()).toEqual({ kind: "gap", timestamp: Duration.micros(0), duration: Duration.micros(100_000) }); + expect(await consumer.next()).toEqual({ + kind: "gap", + timestamp: Duration.micros(0), + duration: Duration.micros(100_000), + }); expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(100_000); consumer.close(); @@ -1881,7 +1995,10 @@ test("Consumer reads a latency skip as one gap", async () => { test("Consumer reads a timestamp hole as a gap", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: Duration.millis(0) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("audio"), + delay: { max: Duration.millis(0) }, + }); writeGroupWithLegacyFrames(track, 0n, [0]); await flush(); @@ -1902,7 +2019,10 @@ test("Consumer reads a timestamp hole as a gap", async () => { test("Consumer reads a shed marker group as a gap", async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), delay: { max: Duration.millis(0) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("audio"), + delay: { max: Duration.millis(0) }, + }); const group0 = track.createGroup(0n); group0.writeFrame({ @@ -1917,7 +2037,11 @@ test("Consumer reads a shed marker group as a gap", async () => { await flush(); // The zero budget sheds the marker unread, and what it declared is lost with it. - expect(await consumer.next()).toEqual({ kind: "gap", timestamp: Duration.micros(0), duration: Duration.micros(500) }); + expect(await consumer.next()).toEqual({ + kind: "gap", + timestamp: Duration.micros(0), + duration: Duration.micros(500), + }); expect(frameOf(await consumer.next()).timestamp.asMicros()).toBe(500); group0.finish(); @@ -1995,7 +2119,10 @@ test("audio discontinuity writes no duration marker", async () => { for (const code of [StreamCode.Cancel, StreamCode.Internal, StreamCode.Old, StreamCode.Evicted, StreamCode(1234)]) { test(`Consumer preserves frames and continues after group reset ${code}`, async () => { const track = new Track.Producer("test"); - const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), delay: { max: Duration.millis(0) } }); + const consumer = new Consumer(replay(track), { + format: new LegacyFormat("data"), + delay: { max: Duration.millis(0) }, + }); const error = spyOn(console, "error").mockImplementation(() => {}); try { const group = track.appendGroup(); @@ -2103,8 +2230,16 @@ for (const end of [ const resumed = await poll(pending); expect(resumed).not.toBe("pending"); if (resumed === "pending") return; - expect(resumed).toEqual({ kind: "gap", timestamp: Duration.micros(0), duration: Duration.micros(1_000_000) }); - expect(await consumer.next()).toMatchObject({ kind: "frame", group: 2n, frame: { timestamp: Duration.micros(1_000_000) } }); + expect(resumed).toEqual({ + kind: "gap", + timestamp: Duration.micros(0), + duration: Duration.micros(1_000_000), + }); + expect(await consumer.next()).toMatchObject({ + kind: "frame", + group: 2n, + frame: { timestamp: Duration.micros(1_000_000) }, + }); if (end) await expect(consumer.next()).rejects.toBe(end); else expect(await consumer.next()).toBeUndefined(); } finally { diff --git a/js/hang/src/container/consumer.ts b/js/hang/src/container/consumer.ts index bee65b4e3c6..adf57b55a9a 100644 --- a/js/hang/src/container/consumer.ts +++ b/js/hang/src/container/consumer.ts @@ -153,7 +153,8 @@ function ptsContiguous(end: number | undefined, nextStart: number | undefined): function continues(prev: Group, next: Group | undefined): next is Group { if (next === undefined) return false; return ( - next.consumer.sequence === prev.consumer.sequence + 1n || ptsContiguous(prev.end, next.frames.at(0)?.timestamp.asMicros()) + next.consumer.sequence === prev.consumer.sequence + 1n || + ptsContiguous(prev.end, next.frames.at(0)?.timestamp.asMicros()) ); } diff --git a/js/hang/src/container/consumer.warmup.test.ts b/js/hang/src/container/consumer.warmup.test.ts index 9a133c3b77d..d35d7668473 100644 --- a/js/hang/src/container/consumer.warmup.test.ts +++ b/js/hang/src/container/consumer.warmup.test.ts @@ -14,11 +14,14 @@ function setup(delay = BUDGET, warmup = 0, min = delay, max: number | null = del const flush = () => clock.advance(Duration.ZERO); const track = new Track.Producer("video"); // A null max delay sets no subscriber limit; an omitted one is zero. - const consumer = new Consumer(track.subscribe({ delay: { max: max === null ? null : Duration.millis(max + warmup) } }), { - format: new Format("video"), - delay: { min: Duration.millis(min), max: max === null ? null : Duration.millis(max) }, - warmup: Duration.millis(warmup), - }); + const consumer = new Consumer( + track.subscribe({ delay: { max: max === null ? null : Duration.millis(max + warmup) } }), + { + format: new Format("video"), + delay: { min: Duration.millis(min), max: max === null ? null : Duration.millis(max) }, + warmup: Duration.millis(warmup), + }, + ); const results: Read[] = []; const warn = spyOn(console, "warn").mockImplementation(() => {}); const reading = (async () => { @@ -44,7 +47,9 @@ function setup(delay = BUDGET, warmup = 0, min = delay, max: number | null = del // Each frame as "@<µs>". function frames(results: Read[]): string[] { - return results.flatMap((read) => (read.kind === "frame" ? [`${read.group}@${read.frame.timestamp.asMicros()}`] : [])); + return results.flatMap((read) => + read.kind === "frame" ? [`${read.group}@${read.frame.timestamp.asMicros()}`] : [], + ); } function write(group: Group.Producer, timestamp: number) { diff --git a/js/hang/src/container/jitter.test.ts b/js/hang/src/container/jitter.test.ts index 534e329448e..4f7d32d2cf5 100644 --- a/js/hang/src/container/jitter.test.ts +++ b/js/hang/src/container/jitter.test.ts @@ -82,7 +82,7 @@ describe("Jitter", () => { const jitter = new Jitter(); jitter.observe(0, 0); for (let i = 0; i < 500; i++) { - jitter.observe((10 + i * 20), (14_500 + i * 20)); + jitter.observe(10 + i * 20, 14_500 + i * 20); } expect(jitter.measured).toBe(20); }); @@ -92,9 +92,9 @@ describe("Jitter", () => { // excuse the first unexplained gap. const jitter = new Jitter(); jitter.end(); - for (let i = 0; i < 500; i++) jitter.observe((50 + i * 20), (i * 20)); + for (let i = 0; i < 500; i++) jitter.observe(50 + i * 20, i * 20); const settled = jitter.measured; - jitter.observe((50 + 500 * 20 + 30_000), (500 * 20 + 30_000)); + jitter.observe(50 + 500 * 20 + 30_000, 500 * 20 + 30_000); expect(jitter.measured).toBeGreaterThan(settled); }); @@ -103,8 +103,8 @@ describe("Jitter", () => { const near = new Jitter(); const far = new Jitter(); for (let i = 0; i < 500; i++) { - near.observe((10 + i * 20), (i * 20)); - far.observe((2000 + i * 20), (i * 20)); + near.observe(10 + i * 20, i * 20); + far.observe(2000 + i * 20, i * 20); } expect(far.measured).toBe(near.measured); }); @@ -113,7 +113,7 @@ describe("Jitter", () => { // A path where every tenth frame lands 300ms late. const warm = new Jitter(); for (let i = 0; i < 500; i++) { - warm.observe((i * 20 + (i % 10 === 0 ? 300 : 0)), (i * 20)); + warm.observe(i * 20 + (i % 10 === 0 ? 300 : 0), i * 20); } const learned = warm.measured; expect(learned).toBeGreaterThan(100); @@ -123,8 +123,7 @@ describe("Jitter", () => { // The replacement opens with a backlog: older media arriving at once, long after the warm // track's frames. Measured against the warm track's arrivals it would read as seconds late. - for (let i = 0; i < 100; i++) - fork.observe((20_000 + Math.floor(i / 50) * 1000), (8000 + i * 20)); + for (let i = 0; i < 100; i++) fork.observe(20_000 + Math.floor(i / 50) * 1000, 8000 + i * 20); expect(fork.measured).toBeLessThanOrEqual(learned); expect(warm.measured).toBe(learned); }); diff --git a/js/hang/src/container/jitter.ts b/js/hang/src/container/jitter.ts index 5014b9db4a3..2074a4adfd5 100644 --- a/js/hang/src/container/jitter.ts +++ b/js/hang/src/container/jitter.ts @@ -1,4 +1,3 @@ - // Implements the estimator in doc/concept/audio-jitter.md, which is normative. The design and // every constant come from WebRTC NetEq's underrun optimizer; this is written from the document, // not from NetEq's source. diff --git a/js/hang/src/container/legacy.ts b/js/hang/src/container/legacy.ts index 667c1ec77ea..0853c53bc65 100644 --- a/js/hang/src/container/legacy.ts +++ b/js/hang/src/container/legacy.ts @@ -21,7 +21,10 @@ export class Format implements ContainerFormat { /** Write the final video frame's end timestamp before the group closes. */ finishGroup(group: Moq.Group.Producer, end?: Duration) { if (this.kind !== "video" || end === undefined) return; - group.writeFrame({ payload: encodeFrame(new Uint8Array(), end), timestamp: Time.Timestamp.fromMicros(micros(end)) }); + group.writeFrame({ + payload: encodeFrame(new Uint8Array(), end), + timestamp: Time.Timestamp.fromMicros(micros(end)), + }); } /** Return the video-frame or audio-source endpoint for an empty codec payload. */ @@ -151,7 +154,10 @@ export class Producer { const group = this.#track.appendGroup(); group.writeFrame({ - payload: this.#format.kind === "data" ? new Uint8Array() : encodeFrame(new Uint8Array(), Duration.micros(timestamp)), + payload: + this.#format.kind === "data" + ? new Uint8Array() + : encodeFrame(new Uint8Array(), Duration.micros(timestamp)), timestamp: Time.Timestamp.fromMicros(timestamp), }); group.finish(); @@ -171,10 +177,7 @@ export class Producer { ) { throw new Error("video group endpoint precedes its last frame"); } - end ??= - this.#end !== undefined && this.#interval !== undefined - ? this.#end + this.#interval - : undefined; + end ??= this.#end !== undefined && this.#interval !== undefined ? this.#end + this.#interval : undefined; // A presentation endpoint cannot bound the decode-order tail after reordering. this.#format.finishGroup(this.#group, this.#reordered || end === undefined ? undefined : Duration.micros(end)); this.#group.finish(); diff --git a/js/loc/api/index.api.md b/js/loc/api/index.api.md index 3d7e3df62a0..d360f331898 100644 --- a/js/loc/api/index.api.md +++ b/js/loc/api/index.api.md @@ -1,18 +1,18 @@ # `@moq/loc` ```ts -import { Micro } from "@moq/clock"; +import { Duration } from "@moq/clock"; export class Format { constructor(kind?: "audio" | "video" | "data"); decode(frame: Uint8Array): Frame[]; - end(frame: Frame): Micro | undefined; + end(frame: Frame): Duration | undefined; readonly kind: "audio" | "video" | "data"; } export interface Frame { keyframe: boolean; payload: Uint8Array; - timestamp: Micro; + timestamp: Duration; } ``` diff --git a/js/moq-boy/src/game.ts b/js/moq-boy/src/game.ts index 57bb4c5ae5b..631bc1df6be 100644 --- a/js/moq-boy/src/game.ts +++ b/js/moq-boy/src/game.ts @@ -6,7 +6,7 @@ * * @module */ -import { Nano, Second } from "@moq/clock"; +import { Duration } from "@moq/clock"; import * as Json from "@moq/json"; import * as Moq from "@moq/net"; import * as Watch from "@moq/watch"; @@ -37,7 +37,7 @@ interface Command { } // Close the session to the emulator after 60s of no input. -const FEEDBACK_IDLE = Nano.fromSecond(Second(60)); +const FEEDBACK_IDLE = Duration.secs(60); // Game Boy native resolution. const GB_WIDTH = 160; @@ -221,15 +221,15 @@ export class Game { this.#command.set({ cmd, timestamps: this.#timestamps() }, true); } - /** Collect media timestamps at each pipeline stage for latency measurement. */ + /** Collect media timestamps, in milliseconds, at each pipeline stage for latency measurement. */ #timestamps(): { label: string; ts: number }[] { const entries: { label: string; ts: number }[] = []; const received = this.sync.out.timestamp.peek(); - if (received != null) entries.push({ label: "received", ts: received }); + if (received != null) entries.push({ label: "received", ts: received.asMillis() }); const decoded = this.videoDecoder.out.timestamp.peek(); - if (decoded != null) entries.push({ label: "decoded", ts: decoded }); + if (decoded != null) entries.push({ label: "decoded", ts: decoded.asMillis() }); const rendered = this.videoRenderer.out.timestamp.peek(); - if (rendered != null) entries.push({ label: "rendered", ts: rendered }); + if (rendered != null) entries.push({ label: "rendered", ts: rendered.asMillis() }); return entries; } diff --git a/js/moq-boy/src/ui/components/StatsPanel.tsx b/js/moq-boy/src/ui/components/StatsPanel.tsx index 0c131798135..29ce4dda8a2 100644 --- a/js/moq-boy/src/ui/components/StatsPanel.tsx +++ b/js/moq-boy/src/ui/components/StatsPanel.tsx @@ -1,4 +1,4 @@ -import { Milli } from "@moq/clock"; +import { Duration } from "@moq/clock"; import { createAccessor } from "@moq/signals/solid"; import { For, Show } from "solid-js"; import { useGameUI } from "../hooks/use-boy-ui"; @@ -12,7 +12,7 @@ export default function StatsPanel() { const onDelayInput = (e: Event) => { const el = e.currentTarget as HTMLInputElement; - game.delay.set(Milli(Number.parseInt(el.value, 10))); + game.delay.set(Duration.millis(Number.parseInt(el.value, 10))); }; const location = () => ctx.status()?.location; @@ -47,13 +47,13 @@ export default function StatsPanel() {