diff --git a/doc/lib/js/clock.md b/doc/lib/js/clock.md index bdd71e56350..6b76531ddb3 100644 --- a/doc/lib/js/clock.md +++ b/doc/lib/js/clock.md @@ -40,11 +40,13 @@ 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))`, +on the host, so a DOM timestamp `t` is `Instant.ZERO.saturatingAdd(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. +days, then gradually lose sub-microsecond precision. Like kio, moving an instant +by a duration has no throwing form: `checkedAdd`/`checkedSub` return `undefined` +past the clock's range, and `saturatingAdd`/`saturatingSub` stop at its ends. +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: `Wall.unixMillis(ms)` builds one from Unix milliseconds and `asUnixMillis()` reads them back exactly. Use it for dates, rather than diff --git a/js/clock/api/index.api.md b/js/clock/api/index.api.md index 25e1144a7ab..85b3cbc07e6 100644 --- a/js/clock/api/index.api.md +++ b/js/clock/api/index.api.md @@ -10,6 +10,7 @@ export class Duration { asMillis(): number; asNanos(): number; asSecs(): number; + checkedAdd(other: Duration): Duration | undefined; clamp(lo: Duration, hi: Duration): Duration; cmp(other: Duration): -1 | 0 | 1; div(divisor: number): Duration; @@ -26,6 +27,7 @@ export class Duration { min(other: Duration): Duration; mul(factor: number): Duration; static nanos(value: number): Duration; + saturatingAdd(other: Duration): Duration; saturatingSub(other: Duration): Duration; static secs(value: number): Duration; sub(other: Duration): Duration; @@ -45,7 +47,8 @@ export interface Installed { export class Instant { static readonly ZERO: Instant; [Symbol.toPrimitive](hint: string): string; - add(duration: Duration): Instant; + checkedAdd(duration: Duration): Instant | undefined; + checkedSub(duration: Duration): Instant | undefined; cmp(other: Instant): -1 | 0 | 1; eq(other: Instant): boolean; ge(other: Instant): boolean; @@ -54,8 +57,9 @@ export class Instant { lt(other: Instant): boolean; max(other: Instant): Instant; min(other: Instant): Instant; + saturatingAdd(duration: Duration): Instant; + saturatingSub(duration: Duration): Instant; since(earlier: Instant): Duration; - sub(duration: Duration): Instant; toJSON(): never; toString(): string; valueOf(): never; diff --git a/js/clock/src/index.test.ts b/js/clock/src/index.test.ts index ef58eacf02c..164395eef19 100644 --- a/js/clock/src/index.test.ts +++ b/js/clock/src/index.test.ts @@ -33,7 +33,7 @@ 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.asUnixMillis(); -const instant = (nanos: number): Instant => Instant.ZERO.add(Duration.nanos(nanos)); +const instant = (nanos: number): Instant => Instant.ZERO.saturatingAdd(Duration.nanos(nanos)); const unix = (millis: number): Wall => Wall.unixMillis(millis); const START = ms(Manual.WALL_START); @@ -46,7 +46,6 @@ test("durations convert units and refuse to become numbers", () => { 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"); @@ -68,6 +67,26 @@ test("durations convert units and refuse to become numbers", () => { } }); +test("moving past either end of a range is checked or saturates", () => { + // Past the longest duration, a nanosecond count is no longer finite. + const longest = Duration.secs(Number.MAX_VALUE); + expect(Instant.ZERO.checkedSub(Duration.nanos(1))).toBeUndefined(); + expect(instant(5).saturatingSub(Duration.nanos(9))).toEqual(Instant.ZERO); + expect(instant(5).checkedSub(Duration.nanos(5))).toEqual(Instant.ZERO); + expect(instant(5).checkedAdd(Duration.nanos(4))).toEqual(instant(9)); + expect(Instant.ZERO.checkedAdd(longest)).toBeUndefined(); + const last = Instant.ZERO.saturatingAdd(longest); + expect(last.gt(instant(Number.MAX_SAFE_INTEGER))).toBe(true); + expect(last.saturatingAdd(Duration.nanos(1))).toEqual(last); + expect(longest.checkedAdd(longest)).toBeUndefined(); + expect(longest.saturatingAdd(longest).gt(longest)).toBe(true); + const max = longest.saturatingAdd(longest); + expect(max.checkedAdd(Duration.nanos(1))).toBeUndefined(); + expect(max.saturatingAdd(Duration.nanos(1))).toEqual(max); + expect(Duration.secs(1).checkedAdd(Duration.millis(1))).toEqual(Duration.millis(1001)); + expect(Duration.secs(1).saturatingAdd(Duration.millis(1))).toEqual(Duration.millis(1001)); +}); + test("durations keep a whole count of any unit exact past 2^53 ns", () => { // Microseconds since the Unix epoch, as a legacy container timestamp carries them. for (const micros of [1_735_689_600_000_016, 4_102_444_800_123_457, Number.MAX_SAFE_INTEGER]) { diff --git a/js/clock/src/types.ts b/js/clock/src/types.ts index 0a2df100315..d5acedaf2bd 100644 --- a/js/clock/src/types.ts +++ b/js/clock/src/types.ts @@ -39,6 +39,8 @@ const NANOS_PER_SEC = 1_000_000_000; export class Duration { /** No time at all. */ static readonly ZERO: Duration = new Duration(0, 0); + // The longest representable duration, which a saturating sum stops at. + static readonly #MAX: Duration = new Duration(Number.MAX_VALUE, NANOS_PER_SEC - 1); /** @internal Whole seconds. */ readonly [VALUE]: number; @@ -75,6 +77,13 @@ export class Duration { // Whole seconds plus any nanoseconds, possibly out of range or fractional seconds, rounded to // whole nanoseconds as Rust's are, so a value's conversions agree with its ordering. static #carry(secs: number, nanos: number): Duration { + const out = Duration.#tryCarry(secs, nanos); + if (out === undefined) throw new RangeError(`invalid duration: ${secs}s + ${nanos}ns`); + return out; + } + + // `#carry`, or `undefined` when the result is negative or past the longest duration. + static #tryCarry(secs: number, nanos: number): Duration | undefined { let whole = Math.floor(secs); let rest = Math.round((secs - whole) * NANOS_PER_SEC + nanos); const carry = Math.floor(rest / NANOS_PER_SEC); @@ -87,9 +96,7 @@ export class Duration { whole -= 1; rest += NANOS_PER_SEC; } - if (!Number.isFinite(whole) || !Number.isFinite(rest) || whole < 0) { - throw new RangeError(`invalid duration: ${secs}s + ${nanos}ns`); - } + if (!Number.isFinite(whole) || !Number.isFinite(rest) || whole < 0) return undefined; return new Duration(whole, rest); } @@ -140,7 +147,22 @@ export class Duration { /** The sum of both durations. */ add(other: Duration): Duration { - return Duration.#carry(this[VALUE] + other[VALUE], this[NANOS] + other[NANOS]); + const sum = this.checkedAdd(other); + if (sum === undefined) throw new RangeError("duration overflow"); + return sum; + } + + /** The sum of both durations, or `undefined` past the longest representable duration. */ + checkedAdd(other: Duration): Duration | undefined { + const sum = Duration.#tryCarry(this[VALUE] + other[VALUE], this[NANOS] + other[NANOS]); + // Near the ceiling a carried second rounds away, which would shrink the sum below an operand. + if (sum === undefined || sum.lt(this) || sum.lt(other)) return undefined; + return sum; + } + + /** The sum of both durations, stopping at the longest representable duration. */ + saturatingAdd(other: Duration): Duration { + return this.checkedAdd(other) ?? Duration.#MAX; } /** This duration minus `other`; throws a `RangeError` if `other` is longer. */ @@ -248,11 +270,16 @@ export class 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))`. + * performance time origin, so a DOM timestamp `t` is `Instant.ZERO.saturatingAdd(Duration.millis(t))`. + * + * Moving one by a `Duration` has no throwing form: each caller picks `checked` or `saturating`, + * so a duration past the clock's range is handled rather than thrown. */ export class Instant { /** The clock's origin. */ static readonly ZERO: Instant = new Instant(0); + // The last instant the clock can represent, which a deadline past its range saturates to. + static readonly #MAX: Instant = new Instant(Number.MAX_VALUE); /** @internal Nanoseconds since the origin. */ readonly [VALUE]: number; @@ -267,14 +294,26 @@ export class Instant { instantNanos = (at) => at[VALUE]; } - /** This instant moved forward by `duration`. */ - add(duration: Duration): Instant { - return new Instant(checked(this[VALUE] + duration.asNanos(), "instant")); + /** This instant moved forward by `duration`, or `undefined` past the clock's range. */ + checkedAdd(duration: Duration): Instant | undefined { + const nanos = this[VALUE] + duration.asNanos(); + return Number.isFinite(nanos) ? new Instant(nanos) : undefined; + } + + /** This instant moved back by `duration`, or `undefined` before the clock's origin. */ + checkedSub(duration: Duration): Instant | undefined { + const nanos = this[VALUE] - duration.asNanos(); + return nanos >= 0 ? new Instant(nanos) : undefined; + } + + /** This instant moved forward by `duration`, stopping at the clock's last instant. */ + saturatingAdd(duration: Duration): Instant { + return this.checkedAdd(duration) ?? Instant.#MAX; } - /** This instant moved back by `duration`; throws a `RangeError` before the clock's origin. */ - sub(duration: Duration): Instant { - return new Instant(checked(this[VALUE] - duration.asNanos(), "instant")); + /** This instant moved back by `duration`, stopping at the clock's origin. */ + saturatingSub(duration: Duration): Instant { + return this.checkedSub(duration) ?? Instant.ZERO; } /** The time from `earlier` to this instant, zero if `earlier` is later. */ diff --git a/js/hang/src/container/consumer.backpressure.test.ts b/js/hang/src/container/consumer.backpressure.test.ts index 8c64f0bffd5..7a39e2c4dc5 100644 --- a/js/hang/src/container/consumer.backpressure.test.ts +++ b/js/hang/src/container/consumer.backpressure.test.ts @@ -280,7 +280,7 @@ test("Consumer stamps frames the max buffer held back with when they landed, not }); expect(await consumer.next()).toMatchObject({ kind: "frame", - frame: { timestamp: Duration.micros(10_000), arrival: Instant.ZERO.add(Duration.millis(250)) }, + frame: { timestamp: Duration.micros(10_000), arrival: Instant.ZERO.saturatingAdd(Duration.millis(250)) }, }); } finally { consumer.close(); diff --git a/js/net/bench/ledger.ts b/js/net/bench/ledger.ts index 93041156533..abefbc34c56 100644 --- a/js/net/bench/ledger.ts +++ b/js/net/bench/ledger.ts @@ -27,14 +27,14 @@ export function run(): void { const start = performance.now(); for (let i = 0; i < count * (order === "rolling" ? 2 : 1); i++) { const sequence = keys[i]; - const at = order === "rolling" ? Instant.ZERO.add(Duration.millis(i)) : Instant.ZERO; + const at = order === "rolling" ? Instant.ZERO.saturatingAdd(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.ZERO.add(Duration.millis(count * 3)), grace); + ledger.expire(Instant.ZERO.saturatingAdd(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/src/cache.ts b/js/net/src/cache.ts index a36838f992d..861d132d98a 100644 --- a/js/net/src/cache.ts +++ b/js/net/src/cache.ts @@ -197,7 +197,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 = now().add(TICK.mul(this.#expiry / 2)); + const at = now().saturatingAdd(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/bandwidth.test.ts b/js/net/src/connection/bandwidth.test.ts index b01f0ee545e..91948b57ab6 100644 --- a/js/net/src/connection/bandwidth.test.ts +++ b/js/net/src/connection/bandwidth.test.ts @@ -17,7 +17,7 @@ async function settle() { } async function waitUntil(pred: () => boolean, ms = 1000): Promise { - const deadline = now().add(Duration.millis(ms)); + const deadline = now().saturatingAdd(Duration.millis(ms)); for (;;) { if (pred()) return; if (now().gt(deadline)) throw new Error("timed out waiting for condition"); diff --git a/js/net/src/connection/migrate.test.ts b/js/net/src/connection/migrate.test.ts index 8f3b238de2a..2fe56d7f352 100644 --- a/js/net/src/connection/migrate.test.ts +++ b/js/net/src/connection/migrate.test.ts @@ -23,7 +23,7 @@ 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 = now().add(Duration.millis(ms)); + const deadline = now().saturatingAdd(Duration.millis(ms)); for (;;) { if (pred()) return; if (now().gt(deadline)) throw new Error("timed out waiting for condition"); diff --git a/js/net/src/connection/reload.test.ts b/js/net/src/connection/reload.test.ts index 4b66c61c1f1..f5e188bbc28 100644 --- a/js/net/src/connection/reload.test.ts +++ b/js/net/src/connection/reload.test.ts @@ -231,7 +231,7 @@ 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 = now().add(Duration.millis(1000)); + const deadline = now().saturatingAdd(Duration.millis(1000)); while (now().le(deadline)) { if (pred()) return; await settle(); diff --git a/js/net/src/connection/reload.ts b/js/net/src/connection/reload.ts index a4625c7c37b..5ff58fd5a4e 100644 --- a/js/net/src/connection/reload.ts +++ b/js/net/src/connection/reload.ts @@ -842,7 +842,7 @@ export class Reload { // When a retry window starting `at` expires. #window(at: Instant): Instant | null { const { timeout } = this.#pacing(); - return timeout === null ? null : at.add(timeout); + return timeout === null ? null : at.saturatingAdd(timeout); } /** diff --git a/js/net/src/connection/ticker.ts b/js/net/src/connection/ticker.ts index b5452b86eeb..dcda0535505 100644 --- a/js/net/src/connection/ticker.ts +++ b/js/net/src/connection/ticker.ts @@ -33,7 +33,7 @@ class Ticker { const abort = new AbortController(); this.#abort = abort; void (async () => { - let next = now().add(this.#period); + let next = now().saturatingAdd(this.#period); for (;;) { await sleepUntil(next, { signal: abort.signal }).catch(() => {}); if (abort.signal.aborted) return; @@ -45,7 +45,7 @@ class Ticker { console.error("ticker callback error", err); } } - next = now().add(this.#period); + next = now().saturatingAdd(this.#period); } })(); } diff --git a/js/net/src/goaway-requests.test.ts b/js/net/src/goaway-requests.test.ts index 9844107e943..d27f5a184c3 100644 --- a/js/net/src/goaway-requests.test.ts +++ b/js/net/src/goaway-requests.test.ts @@ -26,7 +26,7 @@ async function settle() { } async function waitUntil(pred: () => boolean): Promise { - const deadline = now().add(Duration.millis(2000)); + const deadline = now().saturatingAdd(Duration.millis(2000)); for (;;) { if (pred()) return; if (now().gt(deadline)) throw new Error("timed out waiting for condition"); diff --git a/js/net/src/ietf/publisher.ts b/js/net/src/ietf/publisher.ts index 98b26232631..cf6fdd18afc 100644 --- a/js/net/src/ietf/publisher.ts +++ b/js/net/src/ietf/publisher.ts @@ -1868,7 +1868,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, now().add(Duration.millis(wait))); + ns.refused.set(key, now().saturatingAdd(Duration.millis(wait))); ns.offered.set(key, snap); } @@ -2040,10 +2040,11 @@ export class Publisher { /** * What a REQUEST_ERROR's retry interval, in milliseconds, says about re-offering the - * namespace: 0 means the peer does not want this again. + * namespace: 0, or an interval past the clock's range, means the peer does not want this again. */ #refusal(err: RequestError): Answer { - return err.retryInterval === 0n ? "never" : now().add(Duration.millis(toNumber(err.retryInterval))); + if (err.retryInterval === 0n) return "never"; + return now().checkedAdd(Duration.millis(toNumber(err.retryInterval))) ?? "never"; } /** diff --git a/js/net/src/integration.test.ts b/js/net/src/integration.test.ts index 5d91d2e0d9b..29c32a85502 100644 --- a/js/net/src/integration.test.ts +++ b/js/net/src/integration.test.ts @@ -2049,7 +2049,7 @@ 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 = now().add(Duration.millis(1000)); + const deadline = now().saturatingAdd(Duration.millis(1000)); while (!pred()) { if (now().gt(deadline)) throw new Error("timed out waiting for condition"); await yieldNow(); diff --git a/js/net/src/ledger.test.ts b/js/net/src/ledger.test.ts index b0639cd1aaf..cd790fa16dd 100644 --- a/js/net/src/ledger.test.ts +++ b/js/net/src/ledger.test.ts @@ -2,7 +2,7 @@ import { expect, test } from "bun:test"; import { Duration, Instant } from "@moq/clock"; import { Ledger } from "./ledger.ts"; -const at = (ms: number) => Instant.ZERO.add(Duration.millis(ms)); +const at = (ms: number) => Instant.ZERO.saturatingAdd(Duration.millis(ms)); test("overlapping and adjacent ranges merge without changing surviving gap ages", () => { const ledger = new Ledger(); diff --git a/js/net/src/mock.test.ts b/js/net/src/mock.test.ts index f414355d09b..49ef52b8e1b 100644 --- a/js/net/src/mock.test.ts +++ b/js/net/src/mock.test.ts @@ -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.ZERO.add(ms(10)) }); + expect(await clock.drive(work)).toEqual({ value: Uint8Array.of(7), at: Instant.ZERO.saturatingAdd(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()).toEqual(Instant.ZERO.add(ms(1000))); + expect(clock.now()).toEqual(Instant.ZERO.saturatingAdd(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()).toEqual(Instant.ZERO.add(ms(1000))); + expect(clock.now()).toEqual(Instant.ZERO.saturatingAdd(ms(1000))); expect(delivered).toBeGreaterThan(0); } finally { sending = false; diff --git a/js/net/src/resume.ts b/js/net/src/resume.ts index ad8b603701a..960c47ff77e 100644 --- a/js/net/src/resume.ts +++ b/js/net/src/resume.ts @@ -1214,7 +1214,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.ZERO.add(Duration.nanos(at)), { signal: timer.signal, ref: false }).then( + void sleepUntil(Instant.ZERO.saturatingAdd(Duration.nanos(at)), { signal: timer.signal, ref: false }).then( () => { if (timer.signal.aborted) return; this.#wall = undefined; diff --git a/js/net/src/tail.test.ts b/js/net/src/tail.test.ts index c730c3a011c..d9b8871f0fc 100644 --- a/js/net/src/tail.test.ts +++ b/js/net/src/tail.test.ts @@ -122,7 +122,7 @@ describe("Tail", () => { function tail(grace = GRACE) { const clock = new Manual(); installed = clock.install(); - const at = (to: Duration) => clock.jump(Instant.ZERO.add(to).since(clock.now())); + const at = (to: Duration) => clock.jump(Instant.ZERO.saturatingAdd(to).since(clock.now())); return { at, clock, tail: new Tail({ grace: () => grace }) }; } diff --git a/js/net/src/track.test.ts b/js/net/src/track.test.ts index ce9cd8723b8..c19fa9c5811 100644 --- a/js/net/src/track.test.ts +++ b/js/net/src/track.test.ts @@ -50,7 +50,7 @@ function settle(): Promise { function manualTime(initial: number) { const clock = new Manual(); const installed = clock.install(); - const to = (ms: number) => Instant.ZERO.add(Duration.millis(ms)).since(clock.now()); + const to = (ms: number) => Instant.ZERO.saturatingAdd(Duration.millis(ms)).since(clock.now()); clock.jump(to(initial)); return { set: (ms: number) => clock.jump(to(ms)), diff --git a/js/net/src/track.ts b/js/net/src/track.ts index c12f6c68b03..b117faa8f1d 100644 --- a/js/net/src/track.ts +++ b/js/net/src/track.ts @@ -1414,7 +1414,7 @@ export class Producer { const limit = land.grace; const drops = this.#state.drops; for (const gap of this.#arrivals.gaps(start, end)) { - const folds = gap.since?.add(limit); + const folds = gap.since?.saturatingAdd(limit); if (folds !== undefined && at.ge(folds)) continue; for (const open of runGaps(drops.overlapping(gap.start, gap.end), gap.start, gap.end)) { yield { ...open, folds }; @@ -2708,7 +2708,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.ZERO.add(Duration.nanos(at)), { signal: timer.signal, ref: false }).then( + void sleepUntil(Instant.ZERO.saturatingAdd(Duration.nanos(at)), { signal: timer.signal, ref: false }).then( () => { if (timer.signal.aborted) return; wall.timer = undefined; diff --git a/js/publish/src/catalog.ts b/js/publish/src/catalog.ts index eefd1a0ab00..578561f1ee4 100644 --- a/js/publish/src/catalog.ts +++ b/js/publish/src/catalog.ts @@ -52,7 +52,7 @@ export class CatalogProducer { if (!changed || this.#outputs.size === 0) return; const at = now(); - const next = this.#lastEstimate === undefined ? undefined : this.#lastEstimate.add(ESTIMATE_INTERVAL); + const next = this.#lastEstimate === undefined ? undefined : this.#lastEstimate.saturatingAdd(ESTIMATE_INTERVAL); if (!estimateOnly || next === undefined || at.ge(next)) { this.#publish(estimateOnly || this.#pending !== undefined); } else if (!this.#pending) { diff --git a/js/publish/src/source/file.ts b/js/publish/src/source/file.ts index 287db57eb6a..bda421b73c5 100644 --- a/js/publish/src/source/file.ts +++ b/js/publish/src/source/file.ts @@ -117,7 +117,7 @@ export class File { const due = Math.floor(now().since(zero).asSecs() * IMAGE_FRAME_RATE); index = Math.max(index, due); - const at = zero.add(Duration.secs(index / IMAGE_FRAME_RATE)); + const at = zero.saturatingAdd(Duration.secs(index / IMAGE_FRAME_RATE)); index++; await sleepUntil(at, signal); diff --git a/js/publish/src/source/pace.test.ts b/js/publish/src/source/pace.test.ts index e924add8cb0..4ee01188471 100644 --- a/js/publish/src/source/pace.test.ts +++ b/js/publish/src/source/pace.test.ts @@ -107,7 +107,7 @@ test("a reader returning after a long gap seeks to the present on the shared tim // Pacing continues from there at 1x. expect(await read()).toBe(zero + 61_600_000); - expect(clock.now()).toEqual(Instant.ZERO.add(Duration.micros(zero + 61_600_000))); + expect(clock.now()).toEqual(Instant.ZERO.saturatingAdd(Duration.micros(zero + 61_600_000))); } finally { await close(); } diff --git a/js/publish/src/source/timeline.test.ts b/js/publish/src/source/timeline.test.ts index 38ce238c7a4..009d8b8a429 100644 --- a/js/publish/src/source/timeline.test.ts +++ b/js/publish/src/source/timeline.test.ts @@ -4,7 +4,7 @@ import { Timeline } from "./timeline"; const micro = (value: number): Duration => Duration.micros(value); // A point on the clock, `value` microseconds past its origin. -const at = (value: number): Instant => Instant.ZERO.add(micro(value)); +const at = (value: number): Instant => Instant.ZERO.saturatingAdd(micro(value)); const ZERO = at(1_000_000); @@ -61,11 +61,11 @@ describe("Timeline", () => { test("maps a loop boundary of a duration with no exact binary form to the next pass", () => { const timeline = new Timeline(Instant.ZERO, 1.1); - expect(timeline.position(Instant.ZERO.add(Duration.millis(1100)))).toEqual({ + expect(timeline.position(Instant.ZERO.saturatingAdd(Duration.millis(1100)))).toEqual({ timestamp: Duration.ZERO, loop: 1, }); - expect(timeline.position(Instant.ZERO.add(Duration.millis(3300)))).toEqual({ + expect(timeline.position(Instant.ZERO.saturatingAdd(Duration.millis(3300)))).toEqual({ timestamp: Duration.ZERO, loop: 3, }); diff --git a/js/publish/src/source/timeline.ts b/js/publish/src/source/timeline.ts index 40cf1397feb..9f433580921 100644 --- a/js/publish/src/source/timeline.ts +++ b/js/publish/src/source/timeline.ts @@ -1,4 +1,4 @@ -import { Duration, Instant } from "@moq/clock"; +import { Duration, type Instant } from "@moq/clock"; /** * Maps a file's presentation timeline onto our clock, repeating it forever. @@ -33,9 +33,9 @@ export class Timeline { * zero, so it stays signed until it lands on the clock, which saturates at the clock's origin. */ at(micros: number, loop: number): Instant { - const start = this.#zero.add(this.#duration.mul(loop)); - if (micros >= 0) return start.add(Duration.micros(micros)); - return Instant.ZERO.add(start.since(Instant.ZERO).saturatingSub(Duration.micros(-micros))); + const start = this.#zero.saturatingAdd(this.#duration.mul(loop)); + if (micros >= 0) return start.saturatingAdd(Duration.micros(micros)); + return start.saturatingSub(Duration.micros(-micros)); } /** The file timestamp and pass due at the given clock time, the inverse of {@link at}. */ diff --git a/js/qmux/src/session.test.ts b/js/qmux/src/session.test.ts index bbfd52d7e57..03f013eb936 100644 --- a/js/qmux/src/session.test.ts +++ b/js/qmux/src/session.test.ts @@ -177,7 +177,7 @@ 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 = now().add(Duration.millis(timeoutMs)); + const deadline = now().saturatingAdd(Duration.millis(timeoutMs)); while (!check()) { if (now().gt(deadline)) throw new Error("timed out waiting for condition"); await yieldNow(); diff --git a/js/room/src/chat.ts b/js/room/src/chat.ts index c995d9a43d7..9fb572de707 100644 --- a/js/room/src/chat.ts +++ b/js/room/src/chat.ts @@ -50,7 +50,7 @@ export class Publisher { if (!text) return; this.expire(); this.#producer.push({ value: text, at: Time.Timestamp.now() }); - this.#expires.update((expires) => [...expires, now().add(HISTORY)]); + this.#expires.update((expires) => [...expires, now().saturatingAdd(HISTORY)]); } /** Retire elapsed messages now; the publisher also schedules this automatically. */ diff --git a/js/signals/src/index.ts b/js/signals/src/index.ts index 269c078348a..5d6d1869607 100644 --- a/js/signals/src/index.ts +++ b/js/signals/src/index.ts @@ -917,7 +917,7 @@ export class Effect { if (period.isZero()) throw new RangeError("interval period must be positive"); const abort = new AbortController(); - let next = now().add(period); + let next = now().saturatingAdd(period); void (async () => { for (;;) { await sleepUntil(next, { signal: abort.signal }); @@ -929,7 +929,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 = now().add(period); + next = now().saturatingAdd(period); } })().catch(noop); this.cleanup(() => abort.abort()); diff --git a/js/watch/src/arrivals.test.ts b/js/watch/src/arrivals.test.ts index 434c0845bf7..0cf4cfa326c 100644 --- a/js/watch/src/arrivals.test.ts +++ b/js/watch/src/arrivals.test.ts @@ -5,7 +5,7 @@ import { Producer } from "./arrivals"; const frame = (arrival: number) => ({ kind: "frame" as const, timestamp: Duration.millis(arrival), - arrival: Instant.ZERO.add(Duration.millis(arrival)), + arrival: Instant.ZERO.saturatingAdd(Duration.millis(arrival)), late: false, }); diff --git a/js/watch/src/audio/replay.test.ts b/js/watch/src/audio/replay.test.ts index 466a833484c..558a482e0ed 100644 --- a/js/watch/src/audio/replay.test.ts +++ b/js/watch/src/audio/replay.test.ts @@ -231,7 +231,7 @@ describe("ingress diagnostics", () => { trace.map((entry) => ({ kind: "frame" as const, timestamp: Duration.millis(entry.timestamp), - arrival: Instant.ZERO.add(Duration.millis(entry.at)), + arrival: Instant.ZERO.saturatingAdd(Duration.millis(entry.at)), late: false, })), ); diff --git a/js/watch/src/sync.test.ts b/js/watch/src/sync.test.ts index 200b76e7b19..dcfa6f8ac87 100644 --- a/js/watch/src/sync.test.ts +++ b/js/watch/src/sync.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from "bun:test"; import { Duration, type Installed, Instant, Manual, now, yieldNow } from "@moq/clock"; // A monotonic instant `ms` after the clock origin. -const at = (ms: number) => Instant.ZERO.add(Duration.millis(ms)); +const at = (ms: number) => Instant.ZERO.saturatingAdd(Duration.millis(ms)); import { Signal } from "@moq/signals"; import { type Delay, Sync } from "./sync"; diff --git a/js/watch/src/video/decoder.test.ts b/js/watch/src/video/decoder.test.ts index e0d02b5af3a..1109a586823 100644 --- a/js/watch/src/video/decoder.test.ts +++ b/js/watch/src/video/decoder.test.ts @@ -643,7 +643,7 @@ for (const kind of ["legacy", "cmaf"] as const) { expect(playback.outputs).toEqual(stage === "queued" ? [] : [picture]); const before = playback.decoder.out.frame.peek(); - playback.audio.received(Duration.millis(skipTo), Instant.ZERO.add(Duration.millis(5000))); + playback.audio.received(Duration.millis(skipTo), Instant.ZERO.saturatingAdd(Duration.millis(5000))); playback.release(); await microtasks(); const due = playback.decoder.out.frame.peek(); diff --git a/quest/m0/README.md b/quest/m0/README.md index 4a7f0aecf61..f5fb86dfd60 100644 --- a/quest/m0/README.md +++ b/quest/m0/README.md @@ -29,7 +29,6 @@ edge, which embeds moq-relay; it moved there on 2026-09-28. - [The C bindings accept MoqInstance again](/quest/m0/check-c-moqinstance.md) - `check c` passes on main once the C generator stops refusing `MoqInstance`'s exported `Debug` - [Nightly passes on main](/quest/m0/nightly/README.md) - the scheduled Nightly passes end to end, so red means a new break - [Interop and Video pass on main](/quest/m0/interop-green/README.md) - the scheduled Interop and Video workflows pass, so red means a new break -- [@moq/clock's Instant has no throwing Duration arithmetic, mirroring kio](/quest/m0/peer-arithmetic.md) - JS `Instant` drops `add`/`sub` for checked and saturating forms, so each call site states what overflow means, as kio's do - [Publish the release line's drain() wrappers](/quest/m0/ffi-shutdown-backport.md) - Dart `moq` 0.1.1 reaches pub.dev from `release` - [CI cost and latency](/quest/m0/ci/README.md) - cloud CI runs only in GitHub's merge queue, one tested entry at a time, expensive checks run nightly and gate `release`, caches move to R2, and runners are chosen last - [More tests under load](/quest/m0/test-flakes-2/README.md) - load-only and queue failures, one quest per flake, fixed at the cause, since each one drops a queued PR diff --git a/quest/m0/peer-arithmetic.md b/quest/m0/peer-arithmetic.md deleted file mode 100644 index 5fb22d2636e..00000000000 --- a/quest/m0/peer-arithmetic.md +++ /dev/null @@ -1,9 +0,0 @@ -# [M] @moq/clock's Instant has no throwing Duration arithmetic, mirroring kio - -## Goal - -`@moq/clock` mirrors `kio::clock::Instant`, which no longer has `+`/`-` with `Duration` ([moq-dev/moq#8220](https://github.com/moq-dev/moq/pull/8220)): JS `Instant` drops `add` and `sub` in favor of `checkedAdd`/`checkedSub` and `saturatingAdd`/`saturatingSub`, and `Duration` gains `checkedAdd` and `saturatingAdd` beside its existing `saturatingSub`. Each call site states what overflow means, as the Rust sites do. - -## Plan - -`@moq/clock` mirrors kio (decided 2026-11-07, maintainer, /quest-plan from the API sweep). The Rust half and the peer-reachable fixes landed in [moq-dev/moq#8220](https://github.com/moq-dev/moq/pull/8220); about 160 non-test JS call sites remain. Today `Instant.add` throws a `RangeError` past the clock's range instead of panicking, so this is API parity rather than a crash a peer can reach.