diff --git a/doc/lib/rs/kio.md b/doc/lib/rs/kio.md index 85d4cff05e6..644fa225b06 100644 --- a/doc/lib/rs/kio.md +++ b/doc/lib/rs/kio.md @@ -15,7 +15,10 @@ and in a simulator that tests drive. ## The clock `kio::clock::Instant` is a monotonic instant, counted in nanoseconds from the -clock's origin, with the methods of `std::time::Instant`. `Wall` is wall +clock's origin, with the methods of `std::time::Instant`. It has no `+` or `-` +with a `Duration`, which would panic past the clock's range: pick +`checked_add`/`checked_sub`, or `saturating_add`/`saturating_sub`, which stop +at the clock's last instant (centuries out) or its origin. `Wall` is wall time from the same clock. It is a separate type because wall time can step forward or back without any time passing, so it never measures elapsed time. @@ -76,7 +79,7 @@ async fn gives_up_after_five_seconds() { kio::clock::timeout(Duration::from_secs(5), std::future::pending::<()>()).await }); assert!(task.await.unwrap().is_err()); - assert_eq!(kio::clock::now(), kio::clock::Instant::ZERO + Duration::from_secs(5)); + assert_eq!(kio::clock::now(), kio::clock::Instant::ZERO.saturating_add(Duration::from_secs(5))); } ``` diff --git a/drafts/draft-lcurley-moq-lite.md b/drafts/draft-lcurley-moq-lite.md index 7234ec57f4f..9f7266cbf1f 100644 --- a/drafts/draft-lcurley-moq-lite.md +++ b/drafts/draft-lcurley-moq-lite.md @@ -178,6 +178,7 @@ Datagram Tracks have a namespace apart from other Tracks, so a datagram Track an A Group is an ordered stream of Frames within a Track. Each group consists of an append-only list of Frames. +A publisher never creates a Group with sequence 2^64-1, so every range of Groups ends within 64 bits; a receiver treats a Group Stream naming it as a malformed Track. A Group is normally served by a dedicated QUIC stream which is closed on completion, reset by the publisher, or cancelled by the subscriber. This ensures that all Frames within a Group arrive reliably and in order. @@ -1823,14 +1824,14 @@ SUBSCRIBE_DROP Message { Type (i) = 0x2 Message Length (i) Group Start (i) - Group End (i) + Group Count (i) Error Code (i) Update (i) } ~~~ -**Group Start** and **Group End** are the inclusive range of group sequences the publisher gave up. -`Group Start = Group End + 1` is an empty range; a larger Group Start is a PROTOCOL_VIOLATION. +**Group Start** and **Group Count** name the group sequences the publisher gave up: `Group Count` of them from `Group Start`. +A `Group Count` of 0 is an empty range, and a `Group Start + Group Count` above 2^64-1 is a PROTOCOL_VIOLATION. **Error Code** is a [stream error code](#error-codes) saying why the groups were given up, as a reset retaining the Group Stream header would: for example OLD for one past the subscriber's budget, EVICTED for one the publisher no longer holds, or NOT_FOUND for one a relay never received. A subscriber MUST end the readers of a dropped group it holds with that error, including a group whose stream is still arriving, rather than end it cleanly. @@ -1861,7 +1862,8 @@ This includes streams reset before their headers were delivered. A reliably delivered reset retaining the Group Stream header accounts for that group instead. The publisher SHOULD name a sequence as soon as it gives it up, without waiting for SUBSCRIBE_FINISH. -Before moq-lite-07, SUBSCRIBE_DROP carries no `Update`, its Error Code is application-specific, and it also names the sequences moq-lite-07 names in SUBSCRIBE_SKIP; every such drop is final. +Before moq-lite-07, SUBSCRIBE_DROP carries an inclusive `Group End` in place of `Group Count`, where `Group Start = Group End + 1` is an empty range and a larger Group Start is a PROTOCOL_VIOLATION. +It carries no `Update`, its Error Code is application-specific, and it also names the sequences moq-lite-07 names in SUBSCRIBE_SKIP; every such drop is final. ## SUBSCRIBE_SKIP {#subscribe-skip} @@ -1872,12 +1874,11 @@ SUBSCRIBE_SKIP Message { Type (i) = 0x3 Message Length (i) Group Start (i) - Group End (i) + Group Count (i) } ~~~ -**Group Start** and **Group End** are the inclusive range of sequences that will never hold a group. -`Group Start = Group End + 1` is an empty range; a larger Group Start is a PROTOCOL_VIOLATION. +**Group Start** and **Group Count** name the sequences that will never hold a group, as in [SUBSCRIBE_DROP](#subscribe-drop). A skip names only sequences the original publisher declared it will never produce, and it is final: no Group will ever exist at those sequences, whatever the terms. A publisher MUST NOT later create a Group at a sequence it skipped, and a subscriber MUST NOT deliver a Group Stream for one. @@ -2212,6 +2213,7 @@ The `Message Length` describes the payload size on the wire. - An untimed Track declares a `Timescale` of 0 in TRACK_INFO, and its FRAME messages omit the timestamp. - A publisher must not start a timed Group's frame 0 earlier than a lower-sequence Group's, and a receiver may refuse a Group that does. A relay serves every Track's timestamps on as received. - Bounded every timestamp below 2^61. A larger one is a malformed Track. +- Reserved Group sequence 2^64-1: a publisher never creates it, and a Group Stream naming it is a malformed Track. ### Subscriptions {#changelog-07-subscribe} @@ -2229,7 +2231,8 @@ The `Message Length` describes the payload size on the wire. - Added `Error Code` to SUBSCRIBE_FINISH: a track can end with an error while keeping the groups below its end. - Restored SUBSCRIBE_DROP (type 0x2), replacing Stream Count on SUBSCRIBE_FINISH. Every sequence is accounted for by a Group Stream or a drop; a publisher SHOULD send a drop as soon as it gives a sequence up. - SUBSCRIBE_DROP's Error Code is a stream error code, which ends the dropped groups' readers, including one still arriving. -- Refuse a SUBSCRIBE_DROP whose Group Start is greater than Group End plus one on every version that carries it. +- Refuse a SUBSCRIBE_DROP whose Group Start is greater than Group End plus one on every earlier version that carries it. +- SUBSCRIBE_DROP and SUBSCRIBE_SKIP carry `Group Start` and `Group Count` in place of an inclusive `Group End`. A range past 2^64-1 is a PROTOCOL_VIOLATION. - Added SUBSCRIBE_SKIP (type 0x3) for sequences the publisher declared it will never produce, which ends no reader and is final: a Group is never created at a skipped sequence. A skip overrides an earlier drop of the same sequences, whatever its Error Code, without re-delivering to readers the drop already ended, and never overrides a Group that arrived. A gap in the sequence numbers is not a skip, since Groups may be created out of order; a sequence never had and never declared skipped is named in SUBSCRIBE_DROP. SUBSCRIBE_DROP no longer names declared skips. - Added `Update` to SUBSCRIBE, SUBSCRIBE_UPDATE, and SUBSCRIBE_DROP: the number of the terms in effect. A stale (OLD) drop holds only under the update it names, judged against the budget the subscriber sent with it; every later SUBSCRIBE_UPDATE reopens it, and the publisher re-offers the group or drops it again under the new `Update`. Any other drop is final. A Group Stream wins over its earlier drop, and over a stale drop that arrives after it; no update reopens a sequence its Group Stream accounted for. A re-offered Group Stream that overtakes the reset of the stream it replaces waits, unread, until that stream ends, and is read only if it was reset. - SUBSCRIBE_FINISH declares the final boundary while lower groups can still be in flight, and no longer closes the Subscribe Stream: the publisher keeps reading SUBSCRIBE_UPDATE, so an update can reach an ended Track's history. diff --git a/js/net/src/group.ts b/js/net/src/group.ts index 85bacec82b5..dc71f859bba 100644 --- a/js/net/src/group.ts +++ b/js/net/src/group.ts @@ -29,7 +29,7 @@ import { rescale } from "./rescale.ts"; import type { Timestamp } from "./time.ts"; import type { Info as TrackInfo } from "./track.ts"; import { MAX_FRAME_BYTES } from "./util/limits.ts"; -import { checkSequence } from "./util/sequence.ts"; +import { checkSequence, RESERVED } from "./util/sequence.ts"; // A live tail budget, including a conservative charge for each frame's object and queue slot. const TAIL_BYTES = 32 * 1024 * 1024; @@ -259,7 +259,7 @@ export class Producer { #admits?: ((start: Timestamp) => () => void)[]; constructor(sequence: bigint) { - checkSequence(sequence); + if (checkSequence(sequence) >= RESERVED) throw new RangeError(`group sequence out of range: ${sequence}`); this.#state = new GroupState(sequence); this.sequence = sequence; this.#demand = makeDemand(sequence, this.#wanted, this.#state); diff --git a/js/net/src/lite/publisher.test.ts b/js/net/src/lite/publisher.test.ts index fea005feab4..423ab41f438 100644 --- a/js/net/src/lite/publisher.test.ts +++ b/js/net/src/lite/publisher.test.ts @@ -1114,7 +1114,7 @@ test("lite draft-05: a late-arriving older group is still served", async () => { } }); -// The SUBSCRIBE_DROP ranges, inclusive, a subscribe stream carried up to its FIN. +// The SUBSCRIBE_DROP ranges a subscribe stream carried up to its FIN. async function drops(reader: Reader, version: Version): Promise<[bigint, bigint][]> { const ranges: [bigint, bigint][] = []; for (;;) { @@ -1137,7 +1137,7 @@ test("lite draft-06: a cut group is dropped early, once", async () => { cut.abort(new Error("cut")); const resp = await decodeSubscribeResponse(sub.client.reader, Version.DRAFT_06); if (!("drop" in resp)) throw new Error("expected SUBSCRIBE_DROP"); - expect([resp.drop.start, resp.drop.end]).toEqual([1n, 1n]); + expect([resp.drop.start, resp.drop.end]).toEqual([1n, 2n]); sub.serve(2n); expect(await sub.servedSequence()).toBe(2n); @@ -1165,7 +1165,7 @@ for (const version of [Version.DRAFT_06, Version.DRAFT_07]) { if (!("drop" in resp)) throw new Error("expected SUBSCRIBE_DROP"); expect([resp.drop.start, resp.drop.end, resp.drop.error]).toEqual([ 1n, - 1n, + 2n, version === Version.DRAFT_07 ? 70 : 0, ]); } finally { @@ -1185,7 +1185,7 @@ for (const version of [Version.DRAFT_06, Version.DRAFT_07]) { if (!("drop" in resp)) throw new Error("expected SUBSCRIBE_DROP"); expect([resp.drop.start, resp.drop.end, resp.drop.error]).toEqual([ 1n, - 2n, + 3n, version === Version.DRAFT_07 ? 70 : 0, ]); } finally { @@ -1205,12 +1205,12 @@ for (const version of [Version.DRAFT_06, Version.DRAFT_07]) { hooks.dropTrackGroups(sub.track, 1n, 3n, { error: new StreamError(StreamCode(70), { message: "cut" }) }); const resp = await decodeSubscribeResponse(sub.client.reader, version); if (!("drop" in resp)) throw new Error("expected SUBSCRIBE_DROP"); - expect([resp.drop.start, resp.drop.end]).toEqual([1n, 2n]); + expect([resp.drop.start, resp.drop.end]).toEqual([1n, 3n]); sub.track.skipGroups(1n, 3n); if (version === Version.DRAFT_07) { const skip = await decodeSubscribeResponse(sub.client.reader, version); - expect(skip).toMatchObject({ skip: { start: 1n, end: 2n } }); + expect(skip).toMatchObject({ skip: { start: 1n, end: 3n } }); } sub.track.finish(); sub.track.close(); @@ -1241,7 +1241,7 @@ for (const version of [Version.DRAFT_06, Version.DRAFT_07]) { hooks.dropTrackGroups(sub.track, 1n, 2n, staleHole(60_000)); const resp = await decodeSubscribeResponse(sub.client.reader, version); if (!("drop" in resp)) throw new Error("expected SUBSCRIBE_DROP"); - expect([resp.drop.start, resp.drop.end]).toEqual([1n, 1n]); + expect([resp.drop.start, resp.drop.end]).toEqual([1n, 2n]); sub.serve(1n); sub.serve(2n); @@ -1282,7 +1282,7 @@ for (const version of [Version.DRAFT_06, Version.DRAFT_07]) { if (version !== Version.DRAFT_07) { expect([codes, skips]).toEqual([[0], []]); } else if (declared) { - expect([codes, skips]).toEqual([[], [[2n, 4n]]]); + expect([codes, skips]).toEqual([[], [[2n, 5n]]]); } else { expect([codes, skips]).toEqual([[StreamCode.NotFound], []]); } @@ -1313,7 +1313,7 @@ test("lite-07 skips a huge run at once", async () => { if ("skip" in resp) skips.push([resp.skip.start, resp.skip.end]); if ("finish" in resp) break; } - expect([codes, skips]).toEqual([[], [[1n, FAR - 1n]]]); + expect([codes, skips]).toEqual([[], [[1n, FAR]]]); } finally { await sub.close(); } @@ -1332,7 +1332,7 @@ test("lite draft-06: a reported cut stays dropped when re-created", async () => cut.abort(new Error("cut")); const resp = await decodeSubscribeResponse(sub.client.reader, Version.DRAFT_06); if (!("drop" in resp)) throw new Error("expected SUBSCRIBE_DROP"); - expect([resp.drop.start, resp.drop.end]).toEqual([1n, 1n]); + expect([resp.drop.start, resp.drop.end]).toEqual([1n, 2n]); sub.serve(1n); sub.serve(2n); @@ -1383,7 +1383,7 @@ test("lite draft-06: a group stream that never completes is reset once the group expect(toStreamCode(fromTransport(reason))).toBe(StreamCode.Old); const resp = await decodeSubscribeResponse(sub.client.reader, Version.DRAFT_06); if (!("drop" in resp)) throw new Error("expected SUBSCRIBE_DROP"); - expect([resp.drop.start, resp.drop.end]).toEqual([1n, 1n]); + expect([resp.drop.start, resp.drop.end]).toEqual([1n, 2n]); } finally { await sub.close(); installed.close(); @@ -1419,7 +1419,7 @@ test("lite draft-07: an update drops an expired stream again while it is still s 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"); - expect([first.drop.start, first.drop.end, first.drop.update]).toEqual([1n, 1n, 0n]); + expect([first.drop.start, first.drop.end, first.drop.update]).toEqual([1n, 2n, 0n]); // The track's max age still caps the budget, so group 1 is still stale. await replayUpdate({ priority: 1, startGroup: 0n, update: 1n, ...restate(Version.DRAFT_07) }).encode( @@ -1428,7 +1428,7 @@ test("lite draft-07: an update drops an expired stream again while it is still s ); const again = await decodeSubscribeResponse(sub.client.reader, Version.DRAFT_07); if (!("drop" in again)) throw new Error("expected SUBSCRIBE_DROP"); - expect([again.drop.start, again.drop.end, again.drop.update]).toEqual([1n, 1n, 1n]); + expect([again.drop.start, again.drop.end, again.drop.update]).toEqual([1n, 2n, 1n]); } finally { await sub.close(); installed.close(); @@ -1462,7 +1462,7 @@ test("lite draft-07: a group served over a stale drop retires it", async () => { hooks.dropTrackGroups(sub.track, 1n, 2n, staleHole(60_000)); const resp = await decodeSubscribeResponse(sub.client.reader, Version.DRAFT_07); if (!("drop" in resp)) throw new Error("expected SUBSCRIBE_DROP"); - expect([resp.drop.start, resp.drop.end]).toEqual([1n, 1n]); + expect([resp.drop.start, resp.drop.end]).toEqual([1n, 2n]); sub.serve(1n); expect(await sub.servedSequence()).toBe(1n); @@ -1510,12 +1510,12 @@ test("lite draft-07: a final drop replaces an expired stream", async () => { 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"); - expect([first.drop.start, first.drop.end, first.drop.update]).toEqual([1n, 1n, 0n]); + expect([first.drop.start, first.drop.end, first.drop.update]).toEqual([1n, 2n, 0n]); hooks.dropTrackGroups(sub.track, 1n, 2n, { error: new StreamError(StreamCode(70), { message: "cut" }) }); const final = await decodeSubscribeResponse(sub.client.reader, Version.DRAFT_07); if (!("drop" in final)) throw new Error("expected SUBSCRIBE_DROP"); - expect([final.drop.start, final.drop.end, final.drop.error]).toEqual([1n, 1n, 70]); + expect([final.drop.start, final.drop.end, final.drop.error]).toEqual([1n, 2n, 70]); await replayUpdate({ priority: 1, startGroup: 0n, update: 1n, ...restate(Version.DRAFT_07) }).encode( sub.client.writer, @@ -1567,7 +1567,7 @@ test("lite draft-07: a re-offer dropped again before it opens stays stale at the 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"); - expect([first.drop.start, first.drop.end, first.drop.update]).toEqual([1n, 1n, 1n]); + expect([first.drop.start, first.drop.end, first.drop.update]).toEqual([1n, 2n, 1n]); // Update 2 widens the budget, so group 1 is re-offered; update 3 restores it. Both arrive in // one chunk, which the decoder reads without leaving the task, so update 3 is decoded @@ -1580,7 +1580,7 @@ test("lite draft-07: a re-offer dropped again before it opens stays stale at the await flush(); sub.track.finish(); sub.track.close(); - expect(await holesToEnd(sub.client.reader)).toEqual([["drop", 1n, 1n, 3n]]); + expect(await holesToEnd(sub.client.reader)).toEqual([["drop", 1n, 2n, 3n]]); } finally { await sub.close(); installed.close(); @@ -1601,7 +1601,7 @@ test("lite draft-07: a final OLD drop is dropped again by each update", async () hooks.dropTrackGroups(sub.track, 1n, 2n, { error: new StreamError(StreamCode.Old) }); const first = await decodeSubscribeResponse(sub.client.reader, Version.DRAFT_07); if (!("drop" in first)) throw new Error("expected SUBSCRIBE_DROP"); - expect([first.drop.start, first.drop.end, first.drop.update]).toEqual([1n, 1n, 0n]); + expect([first.drop.start, first.drop.end, first.drop.update]).toEqual([1n, 2n, 0n]); for (const update of [1n, 2n]) { await replayUpdate({ @@ -1615,8 +1615,8 @@ test("lite draft-07: a final OLD drop is dropped again by each update", async () sub.track.finish(); sub.track.close(); expect(await holesToEnd(sub.client.reader)).toEqual([ - ["drop", 1n, 1n, 1n], - ["drop", 1n, 1n, 2n], + ["drop", 1n, 2n, 1n], + ["drop", 1n, 2n, 2n], ]); } finally { await sub.close(); @@ -1634,7 +1634,7 @@ test("lite draft-06: an update lowering the start is swept at the end", async () await flush(); sub.track.finish(); sub.track.close(); - expect(await drops(sub.client.reader, Version.DRAFT_06)).toEqual([[2n, 4n]]); + expect(await drops(sub.client.reader, Version.DRAFT_06)).toEqual([[2n, 5n]]); } finally { await sub.close(); } @@ -1796,7 +1796,7 @@ for (const skipped of ["failed", "stale"] as const) { if (skipped === "failed") { const dropped = await decodeSubscribeResponse(sub.client.reader, Version.DRAFT_06); if (!("drop" in dropped)) throw new Error("expected SUBSCRIBE_DROP"); - expect([dropped.drop.start, dropped.drop.end]).toEqual([7n, 7n]); + expect([dropped.drop.start, dropped.drop.end]).toEqual([7n, 8n]); } expect(await sub.servedSequence()).toBe(6n); } finally { @@ -2483,7 +2483,7 @@ test("lite draft-07: subscribe end precedes a failed stream open", async () => { expect(resp.finish.group).toBe(1n); const dropped = await held.next(); if (!("drop" in dropped)) throw new Error("expected SUBSCRIBE_DROP"); - expect([dropped.drop.start, dropped.drop.end, dropped.drop.error]).toEqual([0n, 0n, 0]); + expect([dropped.drop.start, dropped.drop.end, dropped.drop.error]).toEqual([0n, 1n, 0]); } finally { held.close(); } @@ -2530,7 +2530,7 @@ test("lite draft-07: a group whose close fails is dropped", async () => { if (!("finish" in end)) throw new Error("expected SUBSCRIBE_FINISH"); const dropped = await decodeSubscribeResponse(client.reader, Version.DRAFT_07); if (!("drop" in dropped)) throw new Error("expected SUBSCRIBE_DROP"); - expect([dropped.drop.start, dropped.drop.end, dropped.drop.error]).toEqual([0n, 0n, 0]); + expect([dropped.drop.start, dropped.drop.end, dropped.drop.error]).toEqual([0n, 1n, 0]); } finally { publisher.close(); client.close(); @@ -2593,7 +2593,7 @@ test("blocked DROP responses stop opening later groups", async () => { while (dropped < 72) { const response = await decodeSubscribeResponseMaybe(client.reader, Version.DRAFT_07); if (!response) break; - if ("drop" in response) dropped += Number(response.drop.end - response.drop.start) + 1; + if ("drop" in response) dropped += Number(response.drop.end - response.drop.start); } expect(dropped).toBe(72); expect(opens).toHaveBeenCalledTimes(72); diff --git a/js/net/src/lite/publisher.ts b/js/net/src/lite/publisher.ts index 4988a8537b1..fb18179d911 100644 --- a/js/net/src/lite/publisher.ts +++ b/js/net/src/lite/publisher.ts @@ -1420,7 +1420,7 @@ export class Publisher { return true; }; - // The message naming `[start, end]` given up as `hole` says: lite-07 skips what was never + // The message naming `[start, end)` given up as `hole` says: lite-07 skips what was never // produced, and earlier versions drop it as not found. const holeMessage = (start: bigint, end: bigint, hole: Hole): SubscribeResponse => hole.skip && hasSkip(this.version) @@ -1466,7 +1466,7 @@ export class Publisher { } for (const gap of gaps) { insertRun(served, gap.start, gap.end); - const msg = holeMessage(gap.start, gap.end - 1n, hole); + const msg = holeMessage(gap.start, gap.end, hole); if (!(await controls.response(encodeSubscribeResponse(stream, msg, this.version)))) return false; } return true; @@ -1580,7 +1580,7 @@ export class Publisher { } // A re-offer an update owed again is given up now, so the end sweep never names it. if (served) insertRun(served, start, end); - const msg = SubscribeDrop.given(start, end - 1n, error, this.version, updateNumber); + const msg = SubscribeDrop.given(start, end, error, this.version, updateNumber); if (!(await controls.response(encodeSubscribeResponse(stream, { drop: msg }, this.version)))) return false; } diff --git a/js/net/src/lite/subscribe.test.ts b/js/net/src/lite/subscribe.test.ts index 7b5e9b01bce..57cb6e1a841 100644 --- a/js/net/src/lite/subscribe.test.ts +++ b/js/net/src/lite/subscribe.test.ts @@ -334,22 +334,22 @@ test("SubscribeFinish carries its error on draft-07", async () => { }); test("SubscribeDrop is restored on draft-07", async () => { - const drop: SubscribeResponse = { drop: new SubscribeDrop({ start: 1n, end: 3n, error: 7 }) }; + const drop: SubscribeResponse = { drop: new SubscribeDrop({ start: 1n, end: 4n, error: 7 }) }; const wire = await encode(Version.DRAFT_07, drop); - // The drop names the SUBSCRIBE's update, 0. + // Groups 1 to 3 as a start and count; the drop names the SUBSCRIBE's update, 0. expect(wire).toEqual(new Uint8Array([2, 4, 1, 3, 7, 0])); const got = await responseRoundtrip(Version.DRAFT_07, drop); if (!("drop" in got)) throw new Error("expected drop"); - expect([got.drop.start, got.drop.end, got.drop.error]).toEqual([1n, 3n, 7]); + expect([got.drop.start, got.drop.end, got.drop.error]).toEqual([1n, 4n, 7]); }); test("a drop names its update on draft-07 alone", async () => { - const drop = new SubscribeDrop({ start: 4n, end: 4n, error: 0x34, update: 2n }); - expect(await encode(Version.DRAFT_07, { drop })).toEqual(new Uint8Array([2, 4, 4, 4, 0x34, 2])); + const drop = new SubscribeDrop({ start: 4n, end: 5n, error: 0x34, update: 2n }); + expect(await encode(Version.DRAFT_07, { drop })).toEqual(new Uint8Array([2, 4, 4, 1, 0x34, 2])); const got = await responseRoundtrip(Version.DRAFT_07, { drop }); if (!("drop" in got)) throw new Error("expected drop"); expect(got.drop.update).toBe(2n); - const old = new SubscribeDrop({ start: 4n, end: 4n, error: 0, update: 2n }); + const old = new SubscribeDrop({ start: 4n, end: 5n, error: 0, update: 2n }); expect(await encode(Version.DRAFT_06, { drop: old })).toEqual(new Uint8Array([2, 3, 4, 4, 0])); const back = await responseRoundtrip(Version.DRAFT_06, { drop: old }); if (!("drop" in back)) throw new Error("expected drop"); @@ -357,18 +357,41 @@ test("a drop names its update on draft-07 alone", async () => { }); test("SubscribeSkip is type 3 on draft-07 alone", async () => { - const skip: SubscribeResponse = { skip: new SubscribeSkip({ start: 1n, end: 3n }) }; + const skip: SubscribeResponse = { skip: new SubscribeSkip({ start: 1n, end: 4n }) }; expect(await encode(Version.DRAFT_07, skip)).toEqual(new Uint8Array([3, 2, 1, 3])); const got = await responseRoundtrip(Version.DRAFT_07, skip); if (!("skip" in got)) throw new Error("expected skip"); - expect([got.skip.start, got.skip.end]).toEqual([1n, 3n]); + expect([got.skip.start, got.skip.end]).toEqual([1n, 4n]); await expect(encode(Version.DRAFT_06, skip)).rejects.toThrow(); - const malformed = new Reader(undefined, new Uint8Array([2, 3, 1]), Version.DRAFT_07); - await expect(SubscribeSkip.decode(malformed)).rejects.toThrow("invalid skipped range"); +}); + +// Lite-07 carries Group Start and Group Count, which reach but never pass the reserved group 2^64-1. +// Mirrors the Rust `skip_ranges_on_lite07_count_up_to_the_reserved_group`. +test("lite-07 skip ranges count up to the reserved group", async () => { + const top = (1n << 64n) - 1n; + for (const [start, end] of [ + [0n, 0n], + [3n, 4n], + [0n, top], + [top, top], + ]) { + const got = await responseRoundtrip(Version.DRAFT_07, { skip: new SubscribeSkip({ start, end }) }); + if (!("skip" in got)) throw new Error("expected skip"); + expect([got.skip.start, got.skip.end]).toEqual([start, end]); + } + // Group Start 2^64-1, Group Count 1. + const wire = await encodeMessage(Version.DRAFT_07, new SubscribeSkip({ start: top, end: top })); + wire[wire.length - 1] = 1; + await expect(SubscribeSkip.decode(new Reader(undefined, wire, Version.DRAFT_07), Version.DRAFT_07)).rejects.toThrow( + "invalid group range", + ); + for (const version of [Version.DRAFT_06, Version.DRAFT_07]) { + await expect(encode(version, { drop: new SubscribeDrop({ start: 3n, end: 1n, error: 0 }) })).rejects.toThrow(); + } }); test("SubscribeDrop is type 0x2 on draft-05 and 0x1 on draft-04", async () => { - const drop: SubscribeResponse = { drop: new SubscribeDrop({ start: 1n, end: 3n, error: 0 }) }; + const drop: SubscribeResponse = { drop: new SubscribeDrop({ start: 1n, end: 4n, error: 0 }) }; const wire05 = await encode(Version.DRAFT_05, drop); expect(wire05[0]).toBe(2); @@ -379,7 +402,7 @@ test("SubscribeDrop is type 0x2 on draft-05 and 0x1 on draft-04", async () => { const got = await responseRoundtrip(Version.DRAFT_05, drop); expect("drop" in got).toBe(true); if (!("drop" in got)) throw new Error("expected drop"); - expect([got.drop.start, got.drop.end]).toEqual([1n, 3n]); + expect([got.drop.start, got.drop.end]).toEqual([1n, 4n]); }); test("SUBSCRIBE_OK is rejected on draft-05", async () => { @@ -502,14 +525,18 @@ test("wanted groups refuse malformed input before writing bytes", async () => { } }); -for (const version of [Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07]) { - test(`SUBSCRIBE_DROP refuses reversed ranges while retaining empty ranges on ${version}`, async () => { +// Before lite-07 a range is an inclusive Group Start and Group End, refused reversed. Mirrors the +// Rust `drop_ranges_before_lite07_are_inclusive`. +for (const version of [Version.DRAFT_05, Version.DRAFT_06]) { + test(`SUBSCRIBE_DROP ranges are inclusive on ${version}`, async () => { + // Group Start 3, Group End 1. const malformed = new Reader(undefined, new Uint8Array([3, 3, 1, 0]), version); - await expect(SubscribeDrop.decode(malformed, version)).rejects.toThrow("invalid dropped range"); - await expect(encode(version, { drop: new SubscribeDrop({ start: 3n, end: 1n, error: 0 }) })).rejects.toThrow(); + await expect(SubscribeDrop.decode(malformed, version)).rejects.toThrow("invalid group range"); + const max = (1n << 62n) - 1n; for (const [start, end] of [ - [2n, 1n], - [BigInt(Number.MAX_SAFE_INTEGER), BigInt(Number.MAX_SAFE_INTEGER)], + [2n, 2n], + [1n, 4n], + [max, max + 1n], ]) { const got = await responseRoundtrip(version, { drop: new SubscribeDrop({ start, end, error: 0 }) }); if (!("drop" in got)) throw new Error("missing drop"); diff --git a/js/net/src/lite/subscribe.ts b/js/net/src/lite/subscribe.ts index 22a6e59bcf6..acc41d97b5b 100644 --- a/js/net/src/lite/subscribe.ts +++ b/js/net/src/lite/subscribe.ts @@ -11,6 +11,7 @@ import * as Path from "../path.ts"; import type { Reader, Writer } from "../stream.ts"; import { floorAt, type Timescale, Timestamp } from "../time.ts"; import type { Anchor, Order, Position, Range } from "../track.ts"; +import { UNBOUNDED } from "../util/sequence.ts"; import { lengthLeadingOnes, parts, split } from "../util/varint.ts"; import * as Duration from "./duration.ts"; import { decodePin, encodePin } from "./instance.ts"; @@ -20,6 +21,7 @@ import { hasDropCode, hasEndError, hasFrameBounds, + hasGroupCount, hasGroupOrder, hasMinDelay, hasOrder, @@ -1154,6 +1156,26 @@ export class SubscribeStarted { } } +/** + * A SUBSCRIBE_DROP or SUBSCRIBE_SKIP range: `Group Start` and `Group Count` on lite-07, an inclusive + * `Group Start` and `Group End` before. Either way it ends by the reserved sequence 2^64-1, so it + * never names that group. + */ +async function decodeGroups(r: Reader, version: Version): Promise<{ start: bigint; end: bigint }> { + const start = await r.u62(); + const end = hasGroupCount(version) ? start + (await r.u62()) : (await r.u62()) + 1n; + if (end < start || end >= UNBOUNDED) throw new ProtocolViolation(`invalid group range: [${start}, ${end})`); + return { start, end }; +} + +async function encodeGroups(w: Writer, start: bigint, end: bigint, version: Version) { + // An empty range at 0 has no inclusive end to spell before lite-07. + if (end < start || end >= UNBOUNDED || (end === 0n && !hasGroupCount(version))) + throw new RangeError(`invalid group range: [${start}, ${end})`); + await w.u62(start); + await w.u62(hasGroupCount(version) ? end - start : end - 1n); +} + /** * Names groups that existed but will not be delivered: aborted or reset, evicted or expired with * no copy left, or stale. @@ -1162,7 +1184,9 @@ export class SubscribeStarted { * declared skipped, which lite-07 names in {@link SubscribeSkip}. */ export class SubscribeDrop { + /** The first dropped group sequence. */ start: bigint; + /** One past the last dropped group sequence. */ end: bigint; error: number; /** @@ -1179,7 +1203,7 @@ export class SubscribeDrop { this.update = props.update ?? 0n; } - /** Name `[start, end]` given up with `err` under the terms numbered `update`, as `version` carries it. */ + /** Name `[start, end)` given up with `err` under the terms numbered `update`, as `version` carries it. */ static given(start: bigint, end: bigint, err: unknown, version: Version, update = 0n): SubscribeDrop { return new SubscribeDrop({ start, @@ -1204,17 +1228,13 @@ export class SubscribeDrop { } async #encode(w: Writer, version: Version) { - if (this.start - this.end > 1n) throw new RangeError("invalid dropped range"); - await w.u62(this.start); - await w.u62(this.end); + await encodeGroups(w, this.start, this.end, version); await w.u53(this.error); await encodeUpdate(w, version, this.update); } static async #decode(r: Reader, version: Version): Promise { - const start = await r.u62(); - const end = await r.u62(); - if (start - end > 1n) throw new ProtocolViolation("invalid dropped range"); + const { start, end } = await decodeGroups(r, version); const error = await r.u53(); const update = await decodeUpdate(r, version); return new SubscribeDrop({ start, end, error, update }); @@ -1235,7 +1255,9 @@ export class SubscribeDrop { * {@link SubscribeDrop}. */ export class SubscribeSkip { + /** The first skipped group sequence. */ start: bigint; + /** One past the last skipped group sequence. */ end: bigint; constructor(props: { start: bigint; end: bigint }) { @@ -1243,24 +1265,12 @@ export class SubscribeSkip { this.end = props.end; } - async #encode(w: Writer) { - if (this.start - this.end > 1n) throw new RangeError("invalid skipped range"); - await w.u62(this.start); - await w.u62(this.end); - } - - static async #decode(r: Reader): Promise { - const skip = new SubscribeSkip({ start: await r.u62(), end: await r.u62() }); - if (skip.start - skip.end > 1n) throw new ProtocolViolation("invalid skipped range"); - return skip; - } - - async encode(w: Writer): Promise { - return Message.encode(w, this.#encode.bind(this)); + async encode(w: Writer, version: Version): Promise { + return Message.encode(w, (w) => encodeGroups(w, this.start, this.end, version)); } - static async decode(r: Reader): Promise { - return Message.decode(r, SubscribeSkip.#decode); + static async decode(r: Reader, version: Version): Promise { + return Message.decode(r, async (r) => new SubscribeSkip(await decodeGroups(r, version))); } } @@ -1318,7 +1328,7 @@ export async function encodeSubscribeResponse(w: Writer, resp: SubscribeResponse await resp.drop.encode(w, version); } else if ("skip" in resp && hasSkip(version)) { await w.u53(0x3); - await resp.skip.encode(w); + await resp.skip.encode(w, version); } else if ("started" in resp && hasRanges(version)) { await w.u53(0x4); await resp.started.encode(w); @@ -1357,7 +1367,7 @@ export async function decodeSubscribeResponse(r: Reader, version: Version): Prom return { drop: await SubscribeDrop.decode(r, version) }; case 0x3: if (!hasSkip(version)) throw new ProtocolViolation(`unknown subscribe response type: ${typ}`); - return { skip: await SubscribeSkip.decode(r) }; + return { skip: await SubscribeSkip.decode(r, version) }; case 0x4: if (!hasRanges(version)) throw new ProtocolViolation(`unknown subscribe response type: ${typ}`); return { started: await SubscribeStarted.decode(r) }; diff --git a/js/net/src/lite/subscriber.test.ts b/js/net/src/lite/subscriber.test.ts index a938276babb..f5acf8b215d 100644 --- a/js/net/src/lite/subscriber.test.ts +++ b/js/net/src/lite/subscriber.test.ts @@ -2649,7 +2649,7 @@ test("a group wins over its stale drop on lite-07", async () => { await drainReactions(); }; const old = (sequence: bigint): SubscribeResponse => ({ - drop: new SubscribeDrop({ start: sequence, end: sequence, error: StreamCode.Old }), + drop: new SubscribeDrop({ start: sequence, end: sequence + 1n, error: StreamCode.Old }), }); // A group stream's header: the tail accounts for it, and the track holds the group. const arrive = (sequence: bigint) => { @@ -2735,7 +2735,7 @@ test("a finished group wins over a late stale drop once evicted on lite-07", asy await drainReactions(); }; const old = (sequence: bigint, update: bigint): SubscribeResponse => ({ - drop: new SubscribeDrop({ start: sequence, end: sequence, error: StreamCode.Old, update }), + drop: new SubscribeDrop({ start: sequence, end: sequence + 1n, error: StreamCode.Old, update }), }); // A group stream that arrives whole, through the path that records it. const arrive = (sequence: bigint) => @@ -2810,13 +2810,13 @@ test("a skip or final drop replaces an earlier stale one on lite-07", async () = }); for (const resp of [ { start: new SubscribeStart([0n]) }, - old(1n, 2n), - old(4n, 4n), - { skip: new SubscribeSkip({ start: 1n, end: 2n }) }, - { drop: new SubscribeDrop({ start: 4n, end: 4n, error: StreamCode.NotFound }) }, + old(1n, 3n), + old(4n, 5n), + { skip: new SubscribeSkip({ start: 1n, end: 3n }) }, + { drop: new SubscribeDrop({ start: 4n, end: 5n, error: StreamCode.NotFound }) }, // Empty ranges. - old(6n, 5n), - { skip: new SubscribeSkip({ start: 6n, end: 5n }) }, + old(6n, 6n), + { skip: new SubscribeSkip({ start: 6n, end: 6n }) }, ] satisfies SubscribeResponse[]) { await encodeSubscribeResponse(writer, resp, version); } @@ -2875,17 +2875,17 @@ test("a skip replaces a final drop but not a cached group on lite-07", async () }; await send([ { start: new SubscribeStart([0n]) }, - { drop: new SubscribeDrop({ start: 1n, end: 2n, error: StreamCode.NotFound }) }, + { drop: new SubscribeDrop({ start: 1n, end: 3n, error: StreamCode.NotFound }) }, ]); if (!entry) throw new Error("no subscription"); entry.track.createGroup(5n).finish(); await send([ - { skip: new SubscribeSkip({ start: 1n, end: 2n }) }, + { skip: new SubscribeSkip({ start: 1n, end: 3n }) }, // A later drop leaves the skip in place. - { drop: new SubscribeDrop({ start: 2n, end: 2n, error: StreamCode.NotFound }) }, + { drop: new SubscribeDrop({ start: 2n, end: 3n, error: StreamCode.NotFound }) }, // Group 5 arrived, so the skip names only 4 and 6. - { skip: new SubscribeSkip({ start: 4n, end: 6n }) }, + { skip: new SubscribeSkip({ start: 4n, end: 7n }) }, ]); expect(() => entry?.track.createGroup(1n)).toThrow(Skipped); expect(() => entry?.track.createGroup(2n)).toThrow(Skipped); @@ -3099,7 +3099,7 @@ test("a lite-07 drop naming an unsent update closes the session", async () => { await encodeSubscribeResponse(writer, { start: new SubscribeStart([0n]) }, version); await encodeSubscribeResponse( writer, - { drop: new SubscribeDrop({ start: 1n, end: 1n, error: StreamCode.Old, update: 1n }) }, + { drop: new SubscribeDrop({ start: 1n, end: 2n, error: StreamCode.Old, update: 1n }) }, version, ); for (const chunk of chunks) stream.inbound.enqueue(chunk); diff --git a/js/net/src/lite/subscriber.ts b/js/net/src/lite/subscriber.ts index 411cb59d4c1..03614f8c99d 100644 --- a/js/net/src/lite/subscriber.ts +++ b/js/net/src/lite/subscriber.ts @@ -2190,32 +2190,32 @@ export class Subscriber { // publisher re-offers it or drops it again under the new number, so it is still owed, // and a reader that wants it fills it meanwhile. if (stale && update < (entry.update ?? 0n)) continue; - entry.tail.account(start, end + 1n); + entry.tail.account(start, end); // Judged under the budget this subscriber sent with that update. const hole = stale ? staleHole(entry.maxDelay ?? 0) : { error }; // A group whose stream finished under this update was served over a stale drop, so it // won, even once the cache evicted it. - const named = stale ? entry.tail.unfinished(start, end + 1n) : [{ start, end: end + 1n }]; + const named = stale ? entry.tail.unfinished(start, end) : [{ start, end }]; const recorded = named.flatMap((run) => hooks.dropTrackGroups(entry.track, run.start, run.end, hole)); // A final drop is never reopened, even where it replaces a stale one. A sequence // already skipped stays skipped, and one whose group arrived keeps it, so no update // reopens either. entry.stale = stale ? recorded.reduce((runs, run) => insertDrop(runs, run.start, run.end, hole), entry.stale ?? []) - : removeRun(entry.stale ?? [], start, end + 1n); + : removeRun(entry.stale ?? [], start, end); } else if ("skip" in resp) { // Never produced, so nothing is waited for and no reader ends. A skip is final and // replaces any drop of the same groups, stale or final, so no update reopens them; a // reader a drop already ended stays ended. const { start, end } = resp.skip; - entry.tail.account(start, end + 1n); - entry.stale = removeRun(entry.stale ?? [], start, end + 1n); + entry.tail.account(start, end); + entry.stale = removeRun(entry.stale ?? [], start, end); // A group that arrived was produced after all, so the skip contradicts it: it keeps // the group, and the session goes on, since the draft requires no more. - const [cached] = hooks.skipTrackGroups(entry.track, start, end + 1n); + const [cached] = hooks.skipTrackGroups(entry.track, start, end); if (cached) { console.warn( - `protocol error: SUBSCRIBE_SKIP [${start}, ${end}] names group ${cached.start}, which arrived; keeping it`, + `protocol error: SUBSCRIBE_SKIP [${start}, ${end}) names group ${cached.start}, which arrived; keeping it`, ); } } diff --git a/js/net/src/lite/tail.test.ts b/js/net/src/lite/tail.test.ts index 4b3f6b81059..5d516ad96a2 100644 --- a/js/net/src/lite/tail.test.ts +++ b/js/net/src/lite/tail.test.ts @@ -256,7 +256,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver // A max delay far past the test's patience: only the accounting may end it. 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 }) }); + await respond({ drop: new SubscribeDrop({ start: 0n, end: 1n, error: 0 }) }); const group = groupStream(subscriber, 1n); group.write("1.0"); group.finish(); @@ -278,7 +278,7 @@ describe.each([Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07])("%s", (ver const group = await reader.recvGroup(); expect(await group?.readString()).toBe("0.0"); - await respond({ drop: new SubscribeDrop({ start: 0n, end: 0n, error: 70 }) }); + await respond({ drop: new SubscribeDrop({ start: 0n, end: 1n, error: 70 }) }); const err = await group?.readString().then( () => undefined, (err: unknown) => err, @@ -427,7 +427,7 @@ test("lite-07 settles a skipped group with SUBSCRIBE_DROP", async () => { await group.handled; } await respond({ finish: new SubscribeFinish(3n) }); - await respond({ drop: new SubscribeDrop({ start: 1n, end: 1n, error: 0 }) }); + await respond({ drop: new SubscribeDrop({ start: 1n, end: 2n, error: 0 }) }); await fin(); expect((await reader.recvGroup())?.sequence).toBe(0n); @@ -441,7 +441,7 @@ test("lite-07 settles a dropped range without grace", async () => { 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 respond({ drop: new SubscribeDrop({ start: 0n, end: 3n, error: 0 }) }); await fin(); expect(await settlesWithin(reader.recvGroup(), clock, Duration.millis(1000))).toBe(true); @@ -480,7 +480,7 @@ test("lite-07 FIN waits for the skipped and reset final range to settle", async const last = groupStream(subscriber, 2n); last.write("tail"); await respond({ finish: new SubscribeFinish(3n) }); - await respond({ drop: new SubscribeDrop({ start: 1n, end: 1n, error: 0 }) }); + await respond({ drop: new SubscribeDrop({ start: 1n, end: 2n, error: 0 }) }); await fin(); let finished = false; const ack = subscriberFin().then(() => { diff --git a/js/net/src/lite/version.ts b/js/net/src/lite/version.ts index f8f03106635..6fa34454729 100644 --- a/js/net/src/lite/version.ts +++ b/js/net/src/lite/version.ts @@ -597,6 +597,25 @@ export function hasDropCode(version: Version): boolean { } } +/** + * Whether SUBSCRIBE_DROP and SUBSCRIBE_SKIP carry `Group Start` and `Group Count`. Added in lite-07; + * earlier versions carry an inclusive `Group Start` and `Group End`. + */ +export function hasGroupCount(version: Version): boolean { + // Explicitly list older versions so future versions keep the lite-07+ behavior. + switch (version) { + case Version.DRAFT_01: + case Version.DRAFT_02: + case Version.DRAFT_03: + case Version.DRAFT_04: + case Version.DRAFT_05: + case Version.DRAFT_06: + return false; + default: + return true; + } +} + /** * Whether holes split into SUBSCRIBE_SKIP, for sequences declared never produced, and * SUBSCRIBE_DROP, which names the `Update` in effect when it was given up; SUBSCRIBE and diff --git a/js/net/src/track.test.ts b/js/net/src/track.test.ts index 9d1de543938..ce9cd8723b8 100644 --- a/js/net/src/track.test.ts +++ b/js/net/src/track.test.ts @@ -4760,14 +4760,18 @@ test("reopening stale drops reports again what is stale at the max age bound", ( expect(drain()).toEqual([[1n, 3n, 1500]]); }); -test("group sequences stop at 2^64-1, as a u64 does", () => { +// Mirrors moq-net's `the_reserved_sequence_is_refused` and `a_group_at_the_reserved_sequence_is_refused`. +test("the reserved sequence is refused", () => { + const reserved = (1n << 64n) - 1n; const producer = new TrackProducer("test").accept({}); expect(() => producer.createGroup(1n << 64n)).toThrow(RangeError); - producer.createGroup((1n << 64n) - 1n).finish(); + expect(() => producer.createGroup(reserved)).toThrow(RangeError); + expect(() => hooks.receiveGroup(producer, { sequence: reserved, start: 0 })).toThrow(RangeError); + producer.createGroup(reserved - 1n).finish(); expect(() => producer.appendGroup()).toThrow(RangeError); - // A run's exclusive end may sit just past the last group. - producer.skipGroups(1n << 63n, 1n << 64n); - expect(() => producer.skipGroups(0n, (1n << 64n) + 1n)).toThrow(RangeError); + // A run's exclusive end may sit at the reserved sequence, never past it. + producer.skipGroups(1n << 63n, reserved); + expect(() => producer.skipGroups(0n, 1n << 64n)).toThrow(RangeError); }); // Mirrors the Rust `track::Finished` doctests: the handle `finish` returns takes no new diff --git a/js/net/src/track.ts b/js/net/src/track.ts index 04ca97d81a2..aa02dc73b9c 100644 --- a/js/net/src/track.ts +++ b/js/net/src/track.ts @@ -1907,7 +1907,8 @@ export class Producer { * It says nothing about the sequences around it: groups may be created out of order, and an * aborted or evicted sequence created again. A gap it leaves is skipped only once the * producer says it will not fill it, with {@link skipGroups} or {@link appendGroup}. A - * sequence already skipped throws {@link Skipped}. + * sequence already skipped throws {@link Skipped}, and the reserved sequence 2^64-1 a + * `RangeError`. * * Throws on a sequence that is still cached: a live duplicate would fan out to every * subscriber twice. An aborted incarnation is evicted so a fresh group can serve the diff --git a/js/net/src/util/sequence.ts b/js/net/src/util/sequence.ts index 6077d3e057f..5add01fe633 100644 --- a/js/net/src/util/sequence.ts +++ b/js/net/src/util/sequence.ts @@ -18,6 +18,9 @@ export function saturatingSub(a: bigint, b: bigint): bigint { /** An exclusive end past every group a wire can carry (2^64), which an open run ends at. */ export const UNBOUNDED = 1n << 64n; +/** The reserved group sequence, 2^64-1: no group is created there, so every group fits a half-open range. */ +export const RESERVED = UNBOUNDED - 1n; + /** Refuse a group sequence a u64 cannot hold, or that is not a bigint, either of which a plain JS caller can pass. */ export function checkSequence(sequence: bigint): bigint { if (typeof sequence !== "bigint") throw new TypeError(`group sequence must be a bigint: ${String(sequence)}`); @@ -26,10 +29,10 @@ export function checkSequence(sequence: bigint): bigint { return sequence; } -/** Refuse an exclusive end of a run of group sequences that is not a bigint in `[0, 2^64]`, so a run may end past group 2^64-1. */ +/** Refuse an exclusive end of a run of group sequences that is not a bigint in `[0, 2^64-1]`, so a run never names the reserved group. */ export function checkEnd(end: bigint): bigint { if (typeof end !== "bigint") throw new TypeError(`group end must be a bigint: ${String(end)}`); if (end < 0n) throw new RangeError(`group end must be non-negative: ${end}`); - if (end > UNBOUNDED) throw new RangeError(`group end exceeds 2^64: ${end}`); + if (end > RESERVED) throw new RangeError(`group end exceeds 2^64-1: ${end}`); return end; } diff --git a/quest/m0/README.md b/quest/m0/README.md index c463c9d263a..7491dc73b79 100644 --- a/quest/m0/README.md +++ b/quest/m0/README.md @@ -28,7 +28,7 @@ edge, which embeds moq-relay; it moved there on 2026-09-28. - [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 -- [kio's Instant has no panicking arithmetic, and peer values never wrap](/quest/m0/peer-arithmetic.md) - every deadline states what overflow means, so a peer's retry interval or a huge configured duration cannot panic a task +- [@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 index fdeec9536f8..5fb22d2636e 100644 --- a/quest/m0/peer-arithmetic.md +++ b/quest/m0/peer-arithmetic.md @@ -1,17 +1,9 @@ -# [M] kio's Instant has no panicking arithmetic, and peer values never wrap +# [M] @moq/clock's Instant has no throwing Duration arithmetic, mirroring kio ## Goal -No value a peer sends or an application configures can panic a moq task or silently wrap: - -- `kio::clock::Instant` drops `Add`, `AddAssign`, `Sub` and `SubAssign` with `Duration` (`rs/kio/src/clock/instant.rs`), which panic past the clock's range. Every call site picks `checked_add`/`checked_sub` with an explicit meaning for overflow (no deadline, refused) or a saturating form. This removes the class behind, among others, the IETF publisher's REQUEST_ERROR retry interval (`rs/moq-net/src/ietf/publisher.rs` `refusal`, which any peer can panic) and `rs/moq-net/src/reconnect.rs` deadlines from huge configured durations. -- Peer-supplied counters never wrap with `+ 1`: the ietf `save_join` `largest.object + 1`, the lite SUBSCRIBE_DROP end `u64::MAX` (`saturating_add(1)` that misses that group in `lite/subscriber.rs` and `subscriber/fills.rs`), and the router's advertised seqno in `route/mod.rs`. -- A datagram sequence of 2^62 or more relayed to a lite-05/06 subscriber is handled explicitly in `lite/publisher.rs` `DatagramSend::send` instead of dropped silently. +`@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 -Found by the 2026-11-07 invariant audit (ietf-1, ietf-2, lite-3, lite-4, lite-9, model-3). - -Decided 2026-11-07 (maintainer, invariant-audit root causes): remove the operators rather than make them saturate, so each of the roughly 600 sites states what overflow means; most edits are mechanical. Breaking for the published `kio` crate; it stays in m0 because a remote peer can panic the publisher today. Removing `Sub` alongside `Add` is the same class (underflow before the clock's start). Each peer-reachable site gets a test at the extreme value. - -`@moq/clock` mirrors kio (decided 2026-11-07, maintainer, /quest-plan from the API sweep): once kio drops the operators, JS `Instant` and `Duration` get `checkedAdd` and `saturatingAdd` too, with `add` and `sub` following whatever kio keeps. `Duration.sub` already throws below zero and `saturatingSub` exists. +`@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. diff --git a/rs/kio/src/clock/captured.rs b/rs/kio/src/clock/captured.rs index 6410fdbabdf..2aaca33d8a2 100644 --- a/rs/kio/src/clock/captured.rs +++ b/rs/kio/src/clock/captured.rs @@ -168,7 +168,7 @@ mod tests { tokio::time::advance(Duration::from_secs(5)).await; assert_eq!(Clock::current(), clock); }); - assert_eq!(clock.now(), at + Duration::from_secs(5)); + assert_eq!(clock.now(), at.saturating_add(Duration::from_secs(5))); } /// An installed manual clock is read wherever its capture goes. @@ -194,9 +194,12 @@ mod tests { crate::clock::sim::run(async move { let sim = Clock::current(); crate::clock::sleep(Duration::from_secs(10)).await; - assert_eq!(sim.now(), crate::clock::Instant::ZERO + Duration::from_secs(10)); + assert_eq!( + sim.now(), + crate::clock::Instant::ZERO.saturating_add(Duration::from_secs(10)) + ); assert_eq!(sim.wall(), crate::clock::Manual::WALL_START + Duration::from_secs(10)); - assert!(host.now() > crate::clock::Instant::ZERO + Duration::from_secs(1 << 31)); + assert!(host.now() > crate::clock::Instant::ZERO.saturating_add(Duration::from_secs(1 << 31))); assert_ne!(sim, host); }); } diff --git a/rs/kio/src/clock/deadline.rs b/rs/kio/src/clock/deadline.rs index da7727d7131..d76064c0196 100644 --- a/rs/kio/src/clock/deadline.rs +++ b/rs/kio/src/clock/deadline.rs @@ -405,7 +405,7 @@ mod tests { fn fires_only_on_supplied_time() { let mut clock = Manual::new(); let deadlines = Deadlines::new(clock.now()); - let at = clock.now() + Duration::from_secs(3); + let at = clock.now().saturating_add(Duration::from_secs(3)); let mut deadline = Deadline::new(&deadlines); deadline.set(Some(at)); assert_eq!(deadlines.next(), Some(at)); @@ -447,10 +447,10 @@ mod tests { let deadlines = Deadlines::new(clock.now()); let mut deadline = Deadline::after(&deadlines, Duration::from_secs(1)); - deadline.set(Some(clock.now() + Duration::from_secs(5))); + deadline.set(Some(clock.now().saturating_add(Duration::from_secs(5)))); assert_eq!( deadlines.next(), - Some(clock.now() + Duration::from_secs(5)), + Some(clock.now().saturating_add(Duration::from_secs(5))), "re-armed later" ); clock.advance(Duration::from_secs(1)); @@ -464,7 +464,7 @@ mod tests { deadlines.advance(clock.now()); assert!(deadline.poll(&crate::Waiter::noop()).is_ready()); - deadline.set(Some(clock.now() + Duration::from_secs(1))); + deadline.set(Some(clock.now().saturating_add(Duration::from_secs(1)))); assert!( deadline.poll(&crate::Waiter::noop()).is_pending(), "an elapsed deadline re-arms" @@ -478,7 +478,7 @@ mod tests { let deadlines = Deadlines::new(clock.now()); let mut deadline = Deadline::new(&deadlines); - deadline.set(Some(clock.now() - Duration::from_secs(1))); + deadline.set(Some(clock.now().saturating_sub(Duration::from_secs(1)))); assert!(deadline.poll(&crate::Waiter::noop()).is_ready(), "in the past"); deadline.set(Some(clock.now())); assert!(deadline.poll(&crate::Waiter::noop()).is_ready(), "exactly now"); @@ -532,7 +532,7 @@ mod tests { fn equal_deadlines_fire_in_arming_order() { let mut clock = Manual::new(); let deadlines = Deadlines::new(clock.now()); - let at = clock.now() + Duration::from_secs(1); + let at = clock.now().saturating_add(Duration::from_secs(1)); // Created in one order, armed in the other. let order = Arc::new(Mutex::new(Vec::new())); @@ -587,7 +587,7 @@ mod tests { let ticking = deadlines.clone(); tasks.push(move |waiter: &crate::Waiter| { while tick.poll(waiter).is_ready() { - tick.set(Some(ticking.now() + PERIOD)); + tick.set(Some(ticking.now().saturating_add(PERIOD))); } Poll::Pending }); @@ -609,9 +609,13 @@ mod tests { assert!(owner.as_mut().poll(&mut cx).is_pending()); for ticks in 1..=3 { - now.set(start + PERIOD * ticks); + now.set(start.saturating_add(PERIOD * ticks)); assert!(owner.as_mut().poll(&mut cx).is_pending()); - assert_eq!(next.get(), Some(now.get() + PERIOD), "the deadline re-armed"); + assert_eq!( + next.get(), + Some(now.get().saturating_add(PERIOD)), + "the deadline re-armed" + ); assert_eq!(wakes.count.load(Ordering::SeqCst), 0, "tick {ticks} woke its own poll"); } @@ -626,7 +630,7 @@ mod tests { #[test] #[should_panic(expected = "time moved backwards")] fn time_cannot_move_backwards() { - let deadlines = Deadlines::new(Instant::ZERO + Duration::from_secs(1)); + let deadlines = Deadlines::new(Instant::ZERO.saturating_add(Duration::from_secs(1))); deadlines.advance(Instant::ZERO); } @@ -634,7 +638,7 @@ mod tests { /// unwinding does not panic a second time. #[test] fn moving_backwards_leaves_the_queue_unpoisoned() { - let deadlines = Deadlines::new(Instant::ZERO + Duration::from_secs(1)); + let deadlines = Deadlines::new(Instant::ZERO.saturating_add(Duration::from_secs(1))); let deadline = Deadline::after(&deadlines, Duration::from_secs(1)); let moved = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| deadlines.advance(Instant::ZERO))); assert!(moved.is_err()); @@ -646,28 +650,28 @@ mod tests { /// handed, and the ambient timers arm on it and fire only as it advances. #[test] fn an_entered_queue_is_the_ambient_clock() { - let start = Instant::ZERO + Duration::from_secs(10); + let start = Instant::ZERO.saturating_add(Duration::from_secs(10)); let deadlines = Deadlines::new(start); let entered = deadlines.enter(); assert_eq!(crate::clock::now(), start); let mut sleep = std::pin::pin!(crate::clock::sleep(Duration::from_secs(1))); - assert_eq!(deadlines.next(), Some(start + Duration::from_secs(1))); + assert_eq!(deadlines.next(), Some(start.saturating_add(Duration::from_secs(1)))); let (wakes, waiter) = counter(); let waker = waiter.waker().clone(); let mut cx = Context::from_waker(&waker); assert!(sleep.as_mut().poll(&mut cx).is_pending()); - deadlines.advance(start + Duration::from_millis(999)); - assert_eq!(crate::clock::now(), start + Duration::from_millis(999)); + deadlines.advance(start.saturating_add(Duration::from_millis(999))); + assert_eq!(crate::clock::now(), start.saturating_add(Duration::from_millis(999))); assert_eq!(wakes.count.load(Ordering::SeqCst), 0); - deadlines.advance(start + Duration::from_secs(1)); + deadlines.advance(start.saturating_add(Duration::from_secs(1))); assert_eq!(wakes.count.load(Ordering::SeqCst), 1, "the sleep was not woken"); assert!(sleep.as_mut().poll(&mut cx).is_ready()); drop(entered); assert!( - crate::clock::now() > start + Duration::from_secs(1), + crate::clock::now() > start.saturating_add(Duration::from_secs(1)), "the host clock is back" ); } @@ -679,24 +683,33 @@ mod tests { let _entered = deadlines.enter(); let mut sleep = crate::clock::sleep(Duration::MAX); assert_eq!(deadlines.next(), None); - sleep.reset(Instant::ZERO + Duration::from_secs(1)); - assert_eq!(deadlines.next(), Some(Instant::ZERO + Duration::from_secs(1))); + sleep.reset(Instant::ZERO.saturating_add(Duration::from_secs(1))); + assert_eq!( + deadlines.next(), + Some(Instant::ZERO.saturating_add(Duration::from_secs(1))) + ); } /// Entering nests, and dropping a guard restores the queue entered before it. #[test] fn entering_nests() { - let outer = Deadlines::new(Instant::ZERO + Duration::from_secs(1)); - let inner = Deadlines::new(Instant::ZERO + Duration::from_secs(2)); + let outer = Deadlines::new(Instant::ZERO.saturating_add(Duration::from_secs(1))); + let inner = Deadlines::new(Instant::ZERO.saturating_add(Duration::from_secs(2))); let _outer = outer.enter(); { let _inner = inner.enter(); - assert_eq!(crate::clock::now(), Instant::ZERO + Duration::from_secs(2)); + assert_eq!( + crate::clock::now(), + Instant::ZERO.saturating_add(Duration::from_secs(2)) + ); } - assert_eq!(crate::clock::now(), Instant::ZERO + Duration::from_secs(1)); + assert_eq!( + crate::clock::now(), + Instant::ZERO.saturating_add(Duration::from_secs(1)) + ); std::thread::spawn(|| { assert!( - crate::clock::now() > Instant::ZERO + Duration::from_secs(2), + crate::clock::now() > Instant::ZERO.saturating_add(Duration::from_secs(2)), "other threads keep their own clock" ) }) @@ -720,8 +733,8 @@ mod tests { /// and the retired inner guard's drop does not bring a queue back. #[test] fn a_caught_out_of_order_drop_restores_the_clock() { - let outer = Deadlines::new(Instant::ZERO + Duration::from_secs(1)); - let inner = Deadlines::new(Instant::ZERO + Duration::from_secs(2)); + let outer = Deadlines::new(Instant::ZERO.saturating_add(Duration::from_secs(1))); + let inner = Deadlines::new(Instant::ZERO.saturating_add(Duration::from_secs(2))); let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let outer = outer.enter(); let _inner = inner.enter(); @@ -730,7 +743,7 @@ mod tests { assert!(result.is_err(), "the out-of-order drop did not panic"); assert!(super::entered().is_none(), "a dropped queue is still the ambient clock"); assert!( - crate::clock::now() > Instant::ZERO + Duration::from_secs(2), + crate::clock::now() > Instant::ZERO.saturating_add(Duration::from_secs(2)), "the host clock is back" ); } diff --git a/rs/kio/src/clock/installed.rs b/rs/kio/src/clock/installed.rs index 3218ef885b1..2a9052a637a 100644 --- a/rs/kio/src/clock/installed.rs +++ b/rs/kio/src/clock/installed.rs @@ -253,7 +253,7 @@ mod tests { assert!(poll_once(&mut sleep).is_pending()); clock.advance(Duration::from_millis(1)); sleep.await; - assert_eq!(crate::clock::now(), start + Duration::from_secs(1)); + assert_eq!(crate::clock::now(), start.saturating_add(Duration::from_secs(1))); }); } @@ -275,7 +275,10 @@ mod tests { }); armed_rx.recv().unwrap(); clock.advance(Duration::from_secs(5)); - assert_eq!(runtime.block_on(task).unwrap(), Instant::ZERO + Duration::from_secs(5)); + assert_eq!( + runtime.block_on(task).unwrap(), + Instant::ZERO.saturating_add(Duration::from_secs(5)) + ); } /// Resetting a timer re-arms it at the new deadline. @@ -286,7 +289,9 @@ mod tests { runtime.block_on(async { let mut sleep = pin!(crate::clock::sleep(Duration::from_secs(1))); assert!(poll_once(&mut sleep).is_pending()); - sleep.as_mut().reset(Instant::ZERO + Duration::from_secs(2)); + sleep + .as_mut() + .reset(Instant::ZERO.saturating_add(Duration::from_secs(2))); clock.advance(Duration::from_secs(1)); assert!(poll_once(&mut sleep).is_pending()); clock.advance(Duration::from_secs(1)); @@ -317,7 +322,7 @@ mod tests { let counter = std::sync::Arc::new(Wakes(Default::default())); let waker = Waker::from(counter.clone()); let mut cx = Context::from_waker(&waker); - let at = Instant::ZERO + Duration::from_secs(10); + let at = Instant::ZERO.saturating_add(Duration::from_secs(10)); let mut sleep = pin!(crate::clock::sleep(Duration::from_secs(10))); assert!(sleep.as_mut().poll(&mut cx).is_pending()); @@ -327,7 +332,7 @@ mod tests { } assert_eq!(wakes(&counter), 0, "a same-deadline reset woke the task"); - let earlier = Instant::ZERO + Duration::from_secs(2); + let earlier = Instant::ZERO.saturating_add(Duration::from_secs(2)); sleep.as_mut().reset(earlier); assert_eq!(wakes(&counter), 1, "an earlier reset left the task parked"); assert!(sleep.as_mut().poll(&mut cx).is_pending()); @@ -350,7 +355,10 @@ mod tests { assert_eq!(crate::clock::wall(), Manual::WALL_START + Duration::from_secs(5)); clock.step_wall(Manual::WALL_START); assert_eq!(crate::clock::wall(), Manual::WALL_START); - assert_eq!(crate::clock::now(), Instant::ZERO + Duration::from_secs(5)); + assert_eq!( + crate::clock::now(), + Instant::ZERO.saturating_add(Duration::from_secs(5)) + ); assert_eq!( crate::clock::origin(), (Instant::ZERO, Manual::WALL_START), @@ -365,7 +373,7 @@ mod tests { let _clock = Manual::new().install(installed.handle()); let other = runtime(false); // The host clock reads far past zero from its first instant. - let host = Instant::ZERO + Duration::from_secs(1 << 31); + let host = Instant::ZERO.saturating_add(Duration::from_secs(1 << 31)); assert!(other.block_on(async { crate::clock::now() }) > host); assert!(crate::clock::now() > host); assert_eq!(installed.block_on(async { crate::clock::now() }), Instant::ZERO); @@ -378,11 +386,11 @@ mod tests { let clock = Manual::new().install(runtime.handle()); assert_eq!( clock.advance(Duration::from_secs(1)), - Some(Instant::ZERO + Duration::from_secs(1)) + Some(Instant::ZERO.saturating_add(Duration::from_secs(1))) ); // The wall clock starts in 2025, so it runs out first. assert_eq!(clock.advance(Duration::from_nanos(u64::MAX - 1_000_000_000)), None); - assert_eq!(clock.now(), Instant::ZERO + Duration::from_secs(1)); + assert_eq!(clock.now(), Instant::ZERO.saturating_add(Duration::from_secs(1))); assert_eq!(clock.wall(), Manual::WALL_START + Duration::from_secs(1)); } diff --git a/rs/kio/src/clock/instant.rs b/rs/kio/src/clock/instant.rs index 61da59cc88b..cbf3c646d47 100644 --- a/rs/kio/src/clock/instant.rs +++ b/rs/kio/src/clock/instant.rs @@ -1,13 +1,10 @@ -use std::{ - fmt, - ops::{Add, AddAssign, Sub, SubAssign}, - time::Duration, -}; +use std::{fmt, ops::Sub, time::Duration}; /// A point on the monotonic clock, in nanoseconds from the clock's origin. /// -/// The methods mirror [`std::time::Instant`]'s, so swapping one for the other is an -/// import change. Instants are only comparable within one clock: the simulator +/// The methods mirror [`std::time::Instant`]'s, except that moving one by a [`Duration`] +/// has no operator: each caller picks `checked_` or `saturating_`, so a duration past the +/// clock's range is handled rather than panicking. Instants are only comparable within one clock: the simulator /// starts at [`Instant::ZERO`], and the runtime backends count from an origin they /// pick once, reading far past zero there so earlier moments stay representable. /// On native, [`Instant::into_std`] and [`Instant::from_std`] convert at a third-party @@ -59,6 +56,16 @@ impl Instant { self.0.checked_sub(nanos).map(Self) } + /// This instant moved forward by `duration`, stopping at the clock's last instant. + pub fn saturating_add(&self, duration: Duration) -> Self { + self.checked_add(duration).unwrap_or(Self::MAX) + } + + /// This instant moved back by `duration`, stopping at the clock's origin. + pub fn saturating_sub(&self, duration: Duration) -> Self { + self.checked_sub(duration).unwrap_or(Self::ZERO) + } + /// The instant `since` past the origin. Panics past the clock's range (584 years). pub(crate) fn from_origin(since: Duration) -> Self { Self::ZERO.checked_add(since).expect("instant past the clock's range") @@ -101,38 +108,6 @@ impl Instant { } } -impl Add for Instant { - type Output = Self; - - /// Panics past the clock's range; see [`Instant::checked_add`]. - fn add(self, duration: Duration) -> Self { - self.checked_add(duration) - .expect("overflow when adding duration to instant") - } -} - -impl AddAssign for Instant { - fn add_assign(&mut self, duration: Duration) { - *self = *self + duration; - } -} - -impl Sub for Instant { - type Output = Self; - - /// Panics before the clock's origin; see [`Instant::checked_sub`]. - fn sub(self, duration: Duration) -> Self { - self.checked_sub(duration) - .expect("overflow when subtracting duration from instant") - } -} - -impl SubAssign for Instant { - fn sub_assign(&mut self, duration: Duration) { - *self = *self - duration; - } -} - impl Sub for Instant { type Output = Duration; @@ -153,21 +128,17 @@ mod tests { use super::*; #[test] - fn arithmetic_mirrors_std() { - let start = Instant::ZERO + Duration::from_secs(2); - let later = start + Duration::from_millis(1500); + fn arithmetic() { + let start = Instant::ZERO.saturating_add(Duration::from_secs(2)); + let later = start.saturating_add(Duration::from_millis(1500)); assert_eq!(later - start, Duration::from_millis(1500)); assert_eq!(start - later, Duration::ZERO, "an earlier instant saturates"); assert_eq!(start.checked_duration_since(later), None); - assert_eq!(later - Duration::from_millis(1500), start); + assert_eq!(later.saturating_sub(Duration::from_millis(1500)), start); assert_eq!(Instant::ZERO.checked_sub(Duration::from_nanos(1)), None); assert_eq!(Instant(u64::MAX).checked_add(Duration::from_nanos(1)), None); assert_eq!(Instant::ZERO.checked_add(Duration::MAX), None); - } - - #[test] - #[should_panic(expected = "overflow")] - fn add_past_the_range_panics() { - let _ = Instant::ZERO + Duration::MAX; + assert_eq!(start.saturating_add(Duration::MAX), Instant::MAX); + assert_eq!(start.saturating_sub(Duration::MAX), Instant::ZERO); } } diff --git a/rs/kio/src/clock/manual.rs b/rs/kio/src/clock/manual.rs index 5985f0e6311..9084e123f60 100644 --- a/rs/kio/src/clock/manual.rs +++ b/rs/kio/src/clock/manual.rs @@ -40,7 +40,7 @@ impl Manual { /// Let `duration` pass, moving both the instant and the wall time. pub fn advance(&mut self, duration: Duration) { - self.now += duration; + self.now = self.now.saturating_add(duration); self.wall = self.wall + duration; } @@ -64,19 +64,19 @@ mod tests { fn a_wall_step_passes_no_time() { let mut clock = Manual::new(); clock.advance(Duration::from_secs(5)); - assert_eq!(clock.now(), Instant::ZERO + Duration::from_secs(5)); + assert_eq!(clock.now(), Instant::ZERO.saturating_add(Duration::from_secs(5))); assert_eq!(clock.wall(), Manual::WALL_START + Duration::from_secs(5)); clock.step_wall(Manual::WALL_START + Duration::from_secs(2)); assert_eq!( clock.now(), - Instant::ZERO + Duration::from_secs(5), + Instant::ZERO.saturating_add(Duration::from_secs(5)), "a step back passes no time" ); clock.step_wall(Manual::WALL_START + Duration::from_secs(3600)); assert_eq!( clock.now(), - Instant::ZERO + Duration::from_secs(5), + Instant::ZERO.saturating_add(Duration::from_secs(5)), "nor does a step forward" ); diff --git a/rs/kio/src/clock/runtime.rs b/rs/kio/src/clock/runtime.rs index 8e616a626eb..81afbbcf509 100644 --- a/rs/kio/src/clock/runtime.rs +++ b/rs/kio/src/clock/runtime.rs @@ -18,7 +18,7 @@ use crate::clock::{Instant, Wall}; /// How far past [`Instant::ZERO`] a runtime clock reads at its origin. /// -/// Like std's since-boot `Instant`, so `now() - d` names a moment before the +/// Like std's since-boot `Instant`, so `now().checked_sub(d)` names a moment before the /// process started instead of underflowing during its first seconds. 2^32 s /// (~136 years) outlasts any lookback, and leaves ~448 years of range ahead. const LEAD: std::time::Duration = std::time::Duration::from_secs(1 << 32); @@ -357,13 +357,13 @@ mod tests { runtime.block_on(async { let start = crate::clock::now(); crate::clock::sleep(Duration::from_secs(5)).await; - assert_eq!(crate::clock::now(), start + Duration::from_secs(5)); + assert_eq!(crate::clock::now(), start.saturating_add(Duration::from_secs(5))); tokio::time::advance(Duration::from_secs(60)).await; - assert_eq!(crate::clock::now(), start + Duration::from_secs(65)); - let at = crate::clock::sleep_until(start + Duration::from_secs(70)); - assert_eq!(at.deadline(), start + Duration::from_secs(70)); + assert_eq!(crate::clock::now(), start.saturating_add(Duration::from_secs(65))); + let at = crate::clock::sleep_until(start.saturating_add(Duration::from_secs(70))); + assert_eq!(at.deadline(), start.saturating_add(Duration::from_secs(70))); at.await; - assert_eq!(crate::clock::now(), start + Duration::from_secs(70)); + assert_eq!(crate::clock::now(), start.saturating_add(Duration::from_secs(70))); }); } @@ -435,7 +435,7 @@ mod tests { let host = now.into_std(); assert!(before <= host && host <= after, "{before:?} <= {host:?} <= {after:?}"); assert_eq!(crate::clock::Instant::from_std(host), now); - let earlier = now - Duration::from_secs(3_600); + let earlier = now.saturating_sub(Duration::from_secs(3_600)); assert_eq!(crate::clock::Instant::from_std(earlier.into_std()), earlier); } @@ -455,7 +455,7 @@ mod tests { assert_eq!(later.into_std() - host, Duration::from_secs(60)); assert_eq!( crate::clock::Instant::from_std(host + Duration::from_secs(5)), - start + Duration::from_secs(5) + start.saturating_add(Duration::from_secs(5)) ); }); } @@ -465,7 +465,7 @@ mod tests { fn std_conversion_saturates() { let now = crate::clock::now(); let far = now.into_std() + Duration::from_secs(1 << 40); - assert!(crate::clock::Instant::from_std(far) > now + Duration::from_secs(1 << 33)); + assert!(crate::clock::Instant::from_std(far) > now.saturating_add(Duration::from_secs(1 << 33))); } /// A fresh clock names moments before the process started, as std's does, so diff --git a/rs/kio/src/clock/sim.rs b/rs/kio/src/clock/sim.rs index d6c6f27cc72..cf63cc2a3e6 100644 --- a/rs/kio/src/clock/sim.rs +++ b/rs/kio/src/clock/sim.rs @@ -380,7 +380,7 @@ pub fn attach(deadlines: &Deadlines) { /// Outside [`run`]. pub async fn advance(duration: Duration) { let runtime = expect_current(); - let at = runtime.now() + duration; + let at = runtime.now().saturating_add(duration); runtime.advance_to(at); yield_now().await; } @@ -697,7 +697,7 @@ mod tests { /// until that deadline, rather than waking itself and spinning. #[crate::test] async fn a_same_deadline_reset_does_not_wake() { - let at = crate::clock::now() + Duration::from_secs(1); + let at = crate::clock::now().saturating_add(Duration::from_secs(1)); let mut sleep = Box::pin(crate::clock::sleep(Duration::from_secs(1))); let mut polls = 0; std::future::poll_fn(|cx| { @@ -808,7 +808,7 @@ mod tests { } fn at(secs: u64) -> Instant { - Instant::ZERO + Duration::from_secs(secs) + Instant::ZERO.saturating_add(Duration::from_secs(secs)) } #[test] @@ -1001,7 +1001,7 @@ mod tests { assert_eq!(ticks.tick().await, at(3)); assert_eq!( crate::clock::now(), - Instant::ZERO + Duration::from_millis(3500), + Instant::ZERO.saturating_add(Duration::from_millis(3500)), "caught up at once" ); assert_eq!(ticks.tick().await, at(4)); @@ -1023,7 +1023,10 @@ mod tests { ticks.tick().await; advance(Duration::from_millis(3500)).await; assert_eq!(ticks.tick().await, at(1)); - assert_eq!(ticks.tick().await, Instant::ZERO + Duration::from_millis(4500)); + assert_eq!( + ticks.tick().await, + Instant::ZERO.saturating_add(Duration::from_millis(4500)) + ); } #[crate::test] @@ -1166,7 +1169,7 @@ mod tests { Pin::new(&mut *polled.borrow_mut()).poll(cx) })); yield_now().await; - let target = crate::clock::now() + Duration::from_secs(3); + let target = crate::clock::now().saturating_add(Duration::from_secs(3)); sleep.borrow_mut().reset(target); task.await.unwrap(); assert_eq!(crate::clock::now(), target); @@ -1193,7 +1196,7 @@ mod tests { crate::clock::sleep(Duration::from_secs(1)).await; let mut deadline = Deadline::new(&deadlines); - deadline.set(Some(crate::clock::now() + Duration::from_secs(1))); + deadline.set(Some(crate::clock::now().saturating_add(Duration::from_secs(1)))); assert_eq!(count.0.load(Ordering::SeqCst), 1, "the parked owner was not woken"); } @@ -1245,7 +1248,7 @@ mod tests { polls.push(now); match polls.len() { 3 => Err("done"), - n => Ok(Some(now + Duration::from_secs(n as u64))), + n => Ok(Some(now.saturating_add(Duration::from_secs(n as u64)))), } }) .await; diff --git a/rs/kio/src/clock/timer.rs b/rs/kio/src/clock/timer.rs index f9cf5b4b94f..347376f0117 100644 --- a/rs/kio/src/clock/timer.rs +++ b/rs/kio/src/clock/timer.rs @@ -329,8 +329,12 @@ mod tests { .start_paused(true) .build() .unwrap(); - let (mut sleep, at) = - runtime.block_on(async { (sleep(Duration::MAX), crate::clock::now() + Duration::from_secs(1)) }); + let (mut sleep, at) = runtime.block_on(async { + ( + sleep(Duration::MAX), + crate::clock::now().saturating_add(Duration::from_secs(1)), + ) + }); sleep.reset(at); runtime.block_on(sleep); } diff --git a/rs/kio/src/clock/wall.rs b/rs/kio/src/clock/wall.rs index 5d3c7881c72..ad9975725cc 100644 --- a/rs/kio/src/clock/wall.rs +++ b/rs/kio/src/clock/wall.rs @@ -185,29 +185,29 @@ mod tests { #[test] fn maps_across_batches_until_a_step() { let mut map = WallMap::default(); - let now = Instant::ZERO + Duration::from_secs(100); + let now = Instant::ZERO.saturating_add(Duration::from_secs(100)); let wall = Wall::UNIX_EPOCH + Duration::from_secs(1_000); assert_eq!(map.map(wall), None); map.sample(now, wall); let at = wall - Duration::from_millis(3); - assert_eq!(map.map(at), Some(now - Duration::from_millis(3))); + assert_eq!(map.map(at), Some(now.saturating_sub(Duration::from_millis(3)))); assert_eq!(map.map(wall + Duration::from_millis(1)), None); // A second later on both clocks, within tolerance of each other, still maps let later = Duration::from_secs(1); - map.sample(now + later, wall + later + Duration::from_micros(500)); + map.sample(now.saturating_add(later), wall + later + Duration::from_micros(500)); assert!(map.map(wall + later).is_some()); // The wall clock stepped forward: this batch maps nothing, and the next one does again let step = Duration::from_secs(2) + Duration::from_millis(5); - map.sample(now + Duration::from_secs(2), wall + step); + map.sample(now.saturating_add(Duration::from_secs(2)), wall + step); assert_eq!(map.map(wall + step), None); - map.sample(now + Duration::from_secs(3), wall + step + later); + map.sample(now.saturating_add(Duration::from_secs(3)), wall + step + later); assert!(map.map(wall + step + later).is_some()); // And back - map.sample(now + Duration::from_secs(4), wall); + map.sample(now.saturating_add(Duration::from_secs(4)), wall); assert_eq!(map.map(wall), None); } } diff --git a/rs/moq-archive/src/producer/ordered.rs b/rs/moq-archive/src/producer/ordered.rs index e65c8823429..bab5d08e3bb 100644 --- a/rs/moq-archive/src/producer/ordered.rs +++ b/rs/moq-archive/src/producer/ordered.rs @@ -105,7 +105,7 @@ impl Ordered { if gap && !draining { // The oldest arrival still pending is when this gap was first seen. let (_, since) = self.arrivals.front().expect("a pending sequence arrived"); - let deadline = *since + self.max_delay; + let deadline = since.saturating_add(self.max_delay); if kio::clock::now() < deadline { let timer = self .timer diff --git a/rs/moq-archive/src/producer/track.rs b/rs/moq-archive/src/producer/track.rs index a2720df5530..65066905195 100644 --- a/rs/moq-archive/src/producer/track.rs +++ b/rs/moq-archive/src/producer/track.rs @@ -360,7 +360,7 @@ impl Track { /// When the object's oldest frame is due in the store. fn flush_at(&self) -> Option { - Some(self.object.as_ref()?.unstored + self.shared.config.flush) + Some(self.object.as_ref()?.unstored.saturating_add(self.shared.config.flush)) } /// Store the object once its oldest frame is due, so its group continues in the next. @@ -410,7 +410,7 @@ impl Track { fn prune_at(&self) -> Option { let dvr = self.shared.config.dvr.as_ref()?; let (superseded, _) = self.superseded.front()?; - Some(*superseded + dvr.window + dvr.grace) + Some(superseded.saturating_add(dvr.window).saturating_add(dvr.grace)) } /// Delete the superseded objects whose window and grace have passed. diff --git a/rs/moq-audio/src/aec.rs b/rs/moq-audio/src/aec.rs index 28c7269f236..dc5e698f23a 100644 --- a/rs/moq-audio/src/aec.rs +++ b/rs/moq-audio/src/aec.rs @@ -1093,7 +1093,7 @@ mod tests { // Until the tap hears it rather than for a fixed count: writes are dropped // until the device first reads, and a device can take seconds to start // (PulseAudio's idle null sink renders two seconds ahead). - let deadline = kio::clock::Instant::now() + std::time::Duration::from_secs(10); + let deadline = kio::clock::Instant::now().saturating_add(std::time::Duration::from_secs(10)); while energy <= 1.0 && kio::clock::Instant::now() < deadline { let _ = sink.write(&tone).expect("write"); kio::clock::sleep(std::time::Duration::from_millis(100)).await; diff --git a/rs/moq-audio/src/bus.rs b/rs/moq-audio/src/bus.rs index 6e0ee5dbded..a10e13a0181 100644 --- a/rs/moq-audio/src/bus.rs +++ b/rs/moq-audio/src/bus.rs @@ -1750,7 +1750,7 @@ mod tests { // 132.3 frames per tick, so the blocks alternate in size. let period = Duration::from_millis(3); // 333 ticks: 999 ms, which is 44,055.9 frames. - let end = start + period * 333; + let end = start.saturating_add(period * 333); let clock = tokio::spawn(async move { let mut interval = kio::clock::interval_at(start, period); interval.set_missed_tick_behavior(kio::clock::MissedTickBehavior::Skip); diff --git a/rs/moq-audio/src/capture.rs b/rs/moq-audio/src/capture.rs index ac65213af04..4c619ed2b32 100644 --- a/rs/moq-audio/src/capture.rs +++ b/rs/moq-audio/src/capture.rs @@ -966,16 +966,19 @@ mod tests { let start = Instant::now(); let mut clock = StreamClock::default(); for millis in [0, 10, 20] { - let at = start + Duration::from_millis(millis); + let at = start.saturating_add(Duration::from_millis(millis)); assert_eq!(clock.place(stream(millis), stream(millis), at), Some(at)); } // Captured at 25 ms, stamped by the host at 30 ms, run at 55 ms. - let placed = clock.place(stream(30), stream(25), start + Duration::from_millis(55)); + let placed = clock.place(stream(30), stream(25), start.saturating_add(Duration::from_millis(55))); let creep = Duration::from_millis(10) / MAX_DRIFT; - assert_eq!(placed, Some(start + Duration::from_millis(25) + creep)); + assert_eq!( + placed, + Some(start.saturating_add(Duration::from_millis(25)).saturating_add(creep)) + ); - let on_time = start + Duration::from_millis(40); + let on_time = start.saturating_add(Duration::from_millis(40)); assert_eq!(clock.place(stream(40), stream(40), on_time), Some(on_time)); } @@ -985,10 +988,10 @@ mod tests { fn an_on_time_callback_corrects_a_late_first_one() { let start = Instant::now(); let mut clock = StreamClock::default(); - let late = start + Duration::from_millis(30); + let late = start.saturating_add(Duration::from_millis(30)); assert_eq!(clock.place(stream(0), stream(0), late), Some(late)); - let on_time = start + Duration::from_millis(40); + let on_time = start.saturating_add(Duration::from_millis(40)); assert_eq!(clock.place(stream(40), stream(40), on_time), Some(on_time)); } @@ -1000,7 +1003,7 @@ mod tests { let mut clock = StreamClock::default(); // 500 ppm slow: 10 ms on the stream clock is 10.005 ms of `Instant`. for index in 0..10_000u64 { - let at = start + Duration::from_micros(10_005 * index); + let at = start.saturating_add(Duration::from_micros(10_005 * index)); assert_eq!(clock.place(stream(10 * index), stream(10 * index), at), Some(at)); } } diff --git a/rs/moq-audio/src/capture/buffer.rs b/rs/moq-audio/src/capture/buffer.rs index 2a6178eabd4..2aa7bc74659 100644 --- a/rs/moq-audio/src/capture/buffer.rs +++ b/rs/moq-audio/src/capture/buffer.rs @@ -459,7 +459,7 @@ mod tests { let step = Duration::from_micros(1_000_000 * CHUNK_FRAMES as u64 / 48_000); for index in 0..3 { let samples = reader.recv().await.unwrap(); - assert_eq!(samples.captured, Some(captured + step * (index as u32))); + assert_eq!(samples.captured, Some(captured.saturating_add(step * (index as u32)))); } } } diff --git a/rs/moq-audio/src/decode/consumer.rs b/rs/moq-audio/src/decode/consumer.rs index 754a2856bac..95ccb49848d 100644 --- a/rs/moq-audio/src/decode/consumer.rs +++ b/rs/moq-audio/src/decode/consumer.rs @@ -2282,7 +2282,7 @@ mod tests { } } sequence += 1; - CLOCK.set(Some(origin + duration(arrival))); + CLOCK.set(Some(origin.saturating_add(duration(arrival)))); producer .write(moq_mux::container::Frame { timestamp: Timestamp::from_micros(media as u64 * 1000).unwrap(), diff --git a/rs/moq-audio/src/encode/capture.rs b/rs/moq-audio/src/encode/capture.rs index af802e637fe..3a62c0c46d5 100644 --- a/rs/moq-audio/src/encode/capture.rs +++ b/rs/moq-audio/src/encode/capture.rs @@ -510,7 +510,7 @@ mod tests { let (capture, samples) = capture::test_source(); let mut broadcast = moq_net::broadcast::Info::new().produce(); let consumer = broadcast.consume(); - let epoch = Instant::now() - Duration::from_secs(1); + let epoch = Instant::now().saturating_sub(Duration::from_secs(1)); let clock = moq_mux::Clock::at(epoch, kio::clock::wall()).unwrap(); let catalog = moq_mux::catalog::Producer::new( &mut broadcast, @@ -702,7 +702,7 @@ mod tests { let encode_task = tokio::spawn(driver.run()); let mut track = subscribe(&broadcast, Duration::ZERO).await; for (index, gap) in [false, true, false].into_iter().enumerate() { - let captured = epoch + Duration::from_millis([100, 200, 220][index]); + let captured = epoch.saturating_add(Duration::from_millis([100, 200, 220][index])); let value = (index + 1) as f32 / 8.0; let mut block = Samples::plain(vec![value; 1920], gap); block.captured = Some(captured); @@ -735,7 +735,7 @@ mod tests { bus_pcm.extend_from_slice(&mix(2400)); assert_eq!(&bus_pcm[4800..], expected); drop(bus_run); - let captured = epoch + Duration::from_millis(240); + let captured = epoch.saturating_add(Duration::from_millis(240)); let mut block = Samples::plain(vec![0.625; 1920], false); block.captured = Some(captured); samples.try_push(Ok(block)).unwrap(); @@ -807,7 +807,7 @@ mod tests { let encode_task = tokio::spawn(driver.run()); status(&mut publication, |status| matches!(status, Status::Waiting)).await; let mut block = Samples::plain(vec![0.25; 1920], false); - block.captured = Some(epoch + Duration::from_millis(100)); + block.captured = Some(epoch.saturating_add(Duration::from_millis(100))); samples.try_push(Ok(block)).unwrap(); observer.read().await.unwrap(); retained(&publication).await; @@ -853,7 +853,7 @@ mod tests { let encode_task = tokio::spawn(driver.run()); status(&mut publication, |status| matches!(status, Status::Waiting)).await; let mut block = Samples::plain(vec![0.25; 1920], false); - block.captured = Some(epoch + Duration::from_millis(100)); + block.captured = Some(epoch.saturating_add(Duration::from_millis(100))); samples.try_push(Ok(block)).unwrap(); observer.read().await.unwrap(); retained(&publication).await; @@ -931,9 +931,9 @@ mod tests { let mut track = subscribe(&broadcast, Duration::ZERO).await; let now = Instant::now(); let (captured, expected) = match placement { - 0 => (Some(now - Duration::from_millis(40)), 960_000), - 1 => (Some(epoch - Duration::from_millis(10)), 0), - 2 => (Some(now + Duration::from_secs(1)), 1_000_000), + 0 => (Some(now.saturating_sub(Duration::from_millis(40))), 960_000), + 1 => (Some(epoch.saturating_sub(Duration::from_millis(10))), 0), + 2 => (Some(now.saturating_add(Duration::from_secs(1))), 1_000_000), _ => (None, 1_000_000), }; let mut block = Samples::plain(vec![0.25; 1920], false); diff --git a/rs/moq-audio/src/playback/driver.rs b/rs/moq-audio/src/playback/driver.rs index 7fb0ceb91d3..75bcce70297 100644 --- a/rs/moq-audio/src/playback/driver.rs +++ b/rs/moq-audio/src/playback/driver.rs @@ -967,7 +967,7 @@ impl Driver { fn schedule(&mut self) -> Instant { let wait = self.retry.mul_f64(0.5 + kio::clock::rng().random::() / 2.0); self.retry = (self.retry * 2).min(RETRY_MAX); - Instant::now() + wait + Instant::now().saturating_add(wait) } /// Whether the failures the live stream has reported require a rebuild. @@ -1315,7 +1315,7 @@ mod tests { // Deadlines rather than a plain park, so a lost wake fails the test // instead of hanging it. - let first = requests.wait_with(Some(Instant::now() + PATIENCE), |timeout| { + let first = requests.wait_with(Some(Instant::now().saturating_add(PATIENCE)), |timeout| { let _ = parking.send(()); park(timeout); }); @@ -1323,7 +1323,7 @@ mod tests { sent.send(()).unwrap(); // Syncs racing in behind the first are fine; only silence is not. - let deadline = Instant::now() + PATIENCE; + let deadline = Instant::now().saturating_add(PATIENCE); let stopped = loop { match requests.wait(Some(deadline)) { Work::Shutdown => break true, @@ -1360,7 +1360,7 @@ mod tests { let driver = std::thread::spawn(move || { requests.attach(); - requests.wait(Some(Instant::now() + PATIENCE)) + requests.wait(Some(Instant::now().saturating_add(PATIENCE))) }); assert!( @@ -1395,7 +1395,7 @@ mod tests { // The deadline is never reached: the first park returns with nothing // pending, as a spurious wake does, and the second brings the sync. let mut parks = 0; - let work = requests.wait_with(Some(Instant::now() + PATIENCE), |_| { + let work = requests.wait_with(Some(Instant::now().saturating_add(PATIENCE)), |_| { parks += 1; match parks { 1 => {} diff --git a/rs/moq-audio/tests/integration/playback.rs b/rs/moq-audio/tests/integration/playback.rs index 5a30a08a405..fd26a672ed3 100644 --- a/rs/moq-audio/tests/integration/playback.rs +++ b/rs/moq-audio/tests/integration/playback.rs @@ -55,7 +55,7 @@ async fn open() -> playback::Engine { // The first pull fills the device's buffer at once, so only a clock that // keeps moving after it shows the device is playing. - let deadline = kio::clock::Instant::now() + Duration::from_secs(10); + let deadline = kio::clock::Instant::now().saturating_add(Duration::from_secs(10)); let mut first = None; loop { let clock = observer.read().expect("an observation").clock; diff --git a/rs/moq-auth/src/client.rs b/rs/moq-auth/src/client.rs index 8c4389db9e6..a6766055014 100644 --- a/rs/moq-auth/src/client.rs +++ b/rs/moq-auth/src/client.rs @@ -1333,13 +1333,13 @@ mod tests { // somewhere inside `connect`, so bracket it: the bounds hold however long it takes. let (wall, tick) = (kio::clock::wall(), kio::clock::now()); let consumer = script.connect().await.unwrap(); - let earliest = tick + expires.checked_duration_since(kio::clock::wall()).unwrap(); - let latest = kio::clock::now() + expires.checked_duration_since(wall).unwrap(); + let earliest = tick.saturating_add(expires.checked_duration_since(kio::clock::wall()).unwrap()); + let latest = kio::clock::now().saturating_add(expires.checked_duration_since(wall).unwrap()); // A millisecond either side for Tokio's timer resolution. let tolerance = Duration::from_millis(1); assert!( - kio::clock::timeout_at(earliest - tolerance, consumer.closed()) + kio::clock::timeout_at(earliest.saturating_sub(tolerance), consumer.closed()) .await .is_err(), "an outage must not close before expires" @@ -1350,7 +1350,7 @@ mod tests { patterns(&["**"]), "the grant stands through the outage" ); - let reason = kio::clock::timeout_at(latest + tolerance, consumer.closed()) + let reason = kio::clock::timeout_at(latest.saturating_add(tolerance), consumer.closed()) .await .expect("closed at expires, not later"); assert_eq!(reason, Reason::Expired); diff --git a/rs/moq-auth/src/grant.rs b/rs/moq-auth/src/grant.rs index 4871aefe104..11ce9129ea7 100644 --- a/rs/moq-auth/src/grant.rs +++ b/rs/moq-auth/src/grant.rs @@ -259,12 +259,12 @@ mod tests { grant.expires = Some(now + Duration::from_secs(10)); kio::clock::sim::advance(Duration::from_secs(4)).await; - assert_eq!(grant.deadline(), Some(start + Duration::from_secs(10))); + assert_eq!(grant.deadline(), Some(start.saturating_add(Duration::from_secs(10)))); grant.expires = Some(now - Duration::from_secs(1)); assert_eq!( grant.deadline(), - Some(start + Duration::from_secs(4)), + Some(start.saturating_add(Duration::from_secs(4))), "a past expiry is now, not a grace window" ); } diff --git a/rs/moq-auth/src/lease.rs b/rs/moq-auth/src/lease.rs index a2b1af9b160..80165b77eba 100644 --- a/rs/moq-auth/src/lease.rs +++ b/rs/moq-auth/src/lease.rs @@ -253,7 +253,7 @@ impl Producer { let base = Duration::from_secs(1) * 2u32.saturating_pow(clock.failures.saturating_sub(1).min(16)); let base = base.min(clock.cadence.unwrap_or(BACKOFF_MAX)).min(BACKOFF_MAX); let delay = base.mul_f64(kio::clock::rng().random_range(0.75..=1.25)); - clock.next = Some(kio::clock::now() + delay); + clock.next = Some(kio::clock::now().saturating_add(delay)); delay } diff --git a/rs/moq-boy/src/main.rs b/rs/moq-boy/src/main.rs index 79451db470a..915401a4773 100644 --- a/rs/moq-boy/src/main.rs +++ b/rs/moq-boy/src/main.rs @@ -482,7 +482,7 @@ fn run_emulator( )] std::thread::sleep(next_frame - now); } - next_frame += frame_duration; + next_frame = next_frame.saturating_add(frame_duration); // Capture a single reference timestamp for this tick. // Used for both video and audio PTS so they stay aligned. diff --git a/rs/moq-c/src/test.rs b/rs/moq-c/src/test.rs index 61296ab8c73..4399f904cca 100644 --- a/rs/moq-c/src/test.rs +++ b/rs/moq-c/src/test.rs @@ -6719,7 +6719,7 @@ fn a_stalled_encode_does_not_block_unrelated_calls() { // Wait until it has resolved the handle, so it is genuinely inside the stalled // call rather than still on its way in: the slab holds one reference, this test // a second, and the parked publish is the third. - let deadline = kio::clock::now() + TIMEOUT; + let deadline = kio::clock::now().saturating_add(TIMEOUT); while handle.holders() < 3 { assert!(kio::clock::now() < deadline, "the publish never reached the encoder"); std::thread::yield_now(); @@ -7798,7 +7798,7 @@ fn rate(reservation: u32) -> Option { /// Wait for `reservation`'s grant to reach `bps`, since a subscription reaches the /// allocator asynchronously and an unwatched track already reads a would-be share. fn wait_rate(reservation: u32, bps: u64) { - let deadline = kio::clock::now() + TIMEOUT; + let deadline = kio::clock::now().saturating_add(TIMEOUT); loop { let last = rate(reservation); if last == Some(bps) { diff --git a/rs/moq-cli/src/complete.rs b/rs/moq-cli/src/complete.rs index 8e32eecd207..ff9fb097c61 100644 --- a/rs/moq-cli/src/complete.rs +++ b/rs/moq-cli/src/complete.rs @@ -95,7 +95,7 @@ pub async fn answer(argv: &[OsString]) -> Option { // Whatever happens below, the shell gets an answer. `render` of an empty result // is a well-formed "no candidates", which is the right thing to say when a // lookup has outlived the keystroke that asked for it. - let answer = timeout_at(Instant::now() + CEILING, complete(&request, staged)) + let answer = timeout_at(Instant::now().saturating_add(CEILING), complete(&request, staged)) .await .unwrap_or_default(); @@ -239,7 +239,7 @@ async fn sources( found: impl Future, E>>, describe: impl Fn(&T) -> Candidate<'static>, ) -> Vec> { - match timeout_at(Instant::now() + BUDGET, found).await { + match timeout_at(Instant::now().saturating_add(BUDGET), found).await { Ok(Ok(items)) => items.iter().map(describe).collect(), Ok(Err(_)) | Err(_) => Vec::new(), } diff --git a/rs/moq-cli/src/fetch.rs b/rs/moq-cli/src/fetch.rs index 49ce22168b2..da702d102af 100644 --- a/rs/moq-cli/src/fetch.rs +++ b/rs/moq-cli/src/fetch.rs @@ -44,7 +44,7 @@ struct Frame { /// Fetch the group `args` names from the broadcast `--broadcast` names and write it to stdout. pub async fn run(moq: MoqSide, args: Args, net: crate::Net) -> anyhow::Result<()> { let mut stdout = tokio::io::stdout(); - fetch(&moq, &args, &net, Instant::now() + TIMEOUT, &mut stdout).await + fetch(&moq, &args, &net, Instant::now().saturating_add(TIMEOUT), &mut stdout).await } async fn fetch( @@ -229,7 +229,7 @@ mod tests { Request { args: &args, path: "demo", - deadline: Instant::now() + timeout, + deadline: Instant::now().saturating_add(timeout), }, std::future::ready(Ok((self.origin.clone(), ()))), &mut out, @@ -308,7 +308,7 @@ mod tests { async fn fetch(&self, broadcast: &str, args: &[&str], timeout: Duration) -> (anyhow::Result<()>, Vec) { let (moq, args) = parse(&self.connect, broadcast, args); let mut out = Vec::new(); - let result = super::fetch(&moq, &args, &net(), Instant::now() + timeout, &mut out).await; + let result = super::fetch(&moq, &args, &net(), Instant::now().saturating_add(timeout), &mut out).await; (result, out) } @@ -444,7 +444,7 @@ mod tests { Request { args: &args, path: "demo", - deadline: started + TIMEOUT, + deadline: started.saturating_add(TIMEOUT), }, async { // Advance simulated discovery time before handing back the ready origin. @@ -471,7 +471,7 @@ mod tests { Request { args: &args, path: "demo", - deadline: started + TIMEOUT, + deadline: started.saturating_add(TIMEOUT), }, std::future::pending(), &mut Vec::new(), diff --git a/rs/moq-cli/src/play/fake.rs b/rs/moq-cli/src/play/fake.rs index 656952ff292..7b59498e3ab 100644 --- a/rs/moq-cli/src/play/fake.rs +++ b/rs/moq-cli/src/play/fake.rs @@ -127,7 +127,7 @@ impl Speaker for Recorder { queued: Duration::ZERO, // A real sink's ring starts out holding its latency in silence, which is // why the first sample written sounds that much later. - end: Instant::now() + input.latency, + end: Instant::now().saturating_add(input.latency), }) } } @@ -176,7 +176,7 @@ impl Sink for FakeSink { // models its emergency recovery: no synthetic padding, and no PCM // heard until fresh writes refill the target after a genuine gap. if let Some(prime) = self.prime.take() { - self.end = now + prime; + self.end = now.saturating_add(prime); // The opening silence already holds the first utterance one latency out. if std::mem::take(&mut self.next) { self.declared = false; @@ -190,7 +190,7 @@ impl Sink for FakeSink { } self.declared = false; let ahead = self.end.saturating_duration_since(now); - self.end = self.end.max(now) + self.latency.saturating_sub(ahead); + self.end = self.end.max(now).saturating_add(self.latency.saturating_sub(ahead)); } else if self.end < now { // Comfort noise filled a declared silence, so this plays as it lands. if self.declared { @@ -246,9 +246,9 @@ impl FakeSink { utterance: self.utterance, sample, from: self.end, - to: self.end + duration, + to: self.end.saturating_add(duration), }); - self.end += duration; + self.end = self.end.saturating_add(duration); } fn resume(&mut self) { @@ -315,7 +315,7 @@ mod tests { sink.finish().await; let played = recorder.played(); assert_eq!(played[1].from, now); - assert_eq!(played[1].to, now + Duration::from_millis(20)); + assert_eq!(played[1].to, now.saturating_add(Duration::from_millis(20))); assert!(Instant::now() >= played[1].to); } } diff --git a/rs/moq-cli/src/play/media.rs b/rs/moq-cli/src/play/media.rs index 9c6b71f1c0a..7a6f5a80586 100644 --- a/rs/moq-cli/src/play/media.rs +++ b/rs/moq-cli/src/play/media.rs @@ -1256,7 +1256,7 @@ mod tests { ); assert!(shown.len() > 50, "video stalled: {} pictures", shown.len()); for (timestamp, at) in shown { - let due = start + delay + Duration::from(timestamp); + let due = start.saturating_add(delay).saturating_add(Duration::from(timestamp)); assert!( at.saturating_duration_since(due) <= Duration::from_millis(1) && due.saturating_duration_since(at) <= Duration::from_millis(1), @@ -1437,7 +1437,7 @@ mod tests { let (picture, sample) = if audio_end && video_end { (shown[3].1, new[0].from) } else if audio_end { - let timestamp = new[0].from.duration_since(playback_start + delay); + let timestamp = new[0].from.duration_since(playback_start.saturating_add(delay)); let shown = shown .iter() .find(|(shown, _)| { @@ -1445,12 +1445,12 @@ mod tests { start <= timestamp && timestamp < start + PACKET_DURATION }) .expect("continuous video reaches resumed audio"); - (shown.1 + (timestamp - Duration::from(shown.0)), new[0].from) + (shown.1.saturating_add(timestamp - Duration::from(shown.0)), new[0].from) } else { let timestamp = Duration::from(shown[3].0); let index = (shown[3].0.as_millis() / 20) as usize; let offset = timestamp - PACKET_DURATION * index as u32; - (shown[3].1, new[index - 3].from + offset) + (shown[3].1, new[index - 3].from.saturating_add(offset)) }; assert!( picture.saturating_duration_since(sample) <= Duration::from_millis(1) @@ -1864,7 +1864,7 @@ mod tests { while index < 50 { old.write(packet(index, OLD)).unwrap(); index += 1; - kio::clock::sleep_until(start + PACKET_DURATION * index as u32).await; + kio::clock::sleep_until(start.saturating_add(PACKET_DURATION * index as u32)).await; } // The replacement joins the catalog, then the old track finishes. @@ -1875,7 +1875,7 @@ mod tests { drop(old); while index < 100 { - kio::clock::sleep_until(start + PACKET_DURATION * index as u32).await; + kio::clock::sleep_until(start.saturating_add(PACKET_DURATION * index as u32)).await; new.write(packet(index, NEW)).unwrap(); index += 1; } @@ -1960,7 +1960,7 @@ mod tests { _ => a.write(packet(index, BACK)).unwrap(), } index += 1; - kio::clock::sleep_until(start + PACKET_DURATION * index as u32).await; + kio::clock::sleep_until(start.saturating_add(PACKET_DURATION * index as u32)).await; } settle(player, &recorder).await; @@ -2370,7 +2370,8 @@ mod tests { let start = Instant::now(); for index in 0..COUNT { let ready = ((index + 1) * PACKET).div_ceil(BLOCK) * BLOCK; - kio::clock::sleep_until(start + Duration::from_secs_f64(ready as f64 / SAMPLE_RATE as f64)).await; + kio::clock::sleep_until(start.saturating_add(Duration::from_secs_f64(ready as f64 / SAMPLE_RATE as f64))) + .await; audio.write(packet(index, 0.25)).unwrap(); } settle(player, &recorder).await; @@ -2451,14 +2452,20 @@ mod tests { ); loop { tokio::task::yield_now().await; - if media.video.lock().unwrap().len() == 30 || media.presentation.due(last) == Some(now + delay) { + if media.video.lock().unwrap().len() == 30 + || media.presentation.due(last) == Some(now.saturating_add(delay)) + { break; } } let due = media.presentation.due(last); task.abort(); let _ = task.await; - assert_eq!(due, Some(now + delay), "the decoder did not observe the live edge"); + assert_eq!( + due, + Some(now.saturating_add(delay)), + "the decoder did not observe the live edge" + ); assert!(recorder.present(&media).is_none(), "nothing is due before its delay"); } } diff --git a/rs/moq-cli/src/play/timeline.rs b/rs/moq-cli/src/play/timeline.rs index 83e0f835f81..32bb3f64991 100644 --- a/rs/moq-cli/src/play/timeline.rs +++ b/rs/moq-cli/src/play/timeline.rs @@ -179,15 +179,15 @@ mod tests { /// end, which is what a speaker that ran dry is still sounding. #[test] fn the_playhead_projects_the_last_write_and_holds_at_its_end() { - let now = Instant::ZERO + Duration::from_secs(1); + let now = Instant::ZERO.saturating_add(Duration::from_secs(1)); let playhead = Playhead::default(); assert_eq!(playhead.at(now), None); playhead.wrote(Duration::from_secs(10), Duration::from_millis(200), now); assert_eq!(playhead.at(now), Some(Duration::from_millis(9_800))); - let later = now + Duration::from_millis(150); + let later = now.saturating_add(Duration::from_millis(150)); assert_eq!(playhead.at(later), Some(Duration::from_millis(9_950))); - let dry = now + Duration::from_secs(1); + let dry = now.saturating_add(Duration::from_secs(1)); assert_eq!(playhead.at(dry), Some(Duration::from_secs(10))); playhead.clear(); @@ -197,7 +197,7 @@ mod tests { /// A replaced broadcast's late writes never reach the reader. #[test] fn a_reset_playhead_isolates_the_old_broadcast() { - let now = Instant::ZERO + Duration::from_secs(1); + let now = Instant::ZERO.saturating_add(Duration::from_secs(1)); let reader = Playhead::default(); let old = reader.clone(); let new = reader.clone().reset(); @@ -211,18 +211,18 @@ mod tests { /// so the playhead holds instead of replaying media already heard. #[test] fn the_playhead_holds_through_refill_padding() { - let now = Instant::ZERO + Duration::from_secs(1); + let now = Instant::ZERO.saturating_add(Duration::from_secs(1)); let playhead = Playhead::default(); playhead.wrote(Duration::from_secs(10), Duration::from_millis(200), now); - let dry = now + Duration::from_secs(1); + let dry = now.saturating_add(Duration::from_secs(1)); assert_eq!(playhead.at(dry), Some(Duration::from_secs(10))); // 100 ms of padding, then a 20 ms frame continuing from 10 s. playhead.wrote(Duration::from_millis(10_020), Duration::from_millis(120), dry); assert_eq!(playhead.at(dry), Some(Duration::from_secs(10))); - let padded = dry + Duration::from_millis(100); + let padded = dry.saturating_add(Duration::from_millis(100)); assert_eq!(playhead.at(padded), Some(Duration::from_secs(10))); - let played = dry + Duration::from_millis(110); + let played = dry.saturating_add(Duration::from_millis(110)); assert_eq!(playhead.at(played), Some(Duration::from_millis(10_010))); // A new timeline may start anywhere. diff --git a/rs/moq-cli/src/play/video.rs b/rs/moq-cli/src/play/video.rs index c36600503a1..514091dae8a 100644 --- a/rs/moq-cli/src/play/video.rs +++ b/rs/moq-cli/src/play/video.rs @@ -861,7 +861,7 @@ mod tests { }; tokio::task::yield_now().await; // The burst is the live edge, which no speaker holds video back from. - let last_due = start + delay; + let last_due = start.saturating_add(delay); assert_eq!(media.presentation.due(last), Some(last_due)); // Audio's own tune-in burst lands on the same edge, so the tail keeps its // schedule once video's track goes. @@ -870,8 +870,8 @@ mod tests { assert!(media.video.lock().unwrap().len() <= MAX_FRAMES); let mut shown = Vec::new(); let mut sizes = Vec::new(); - while Instant::now() <= last_due + Duration::from_millis(10) { - if (!paused_window || Instant::now() >= start + Duration::from_secs(1)) + while Instant::now() <= last_due.saturating_add(Duration::from_millis(10)) { + if (!paused_window || Instant::now() >= start.saturating_add(Duration::from_secs(1))) && let Some(picture) = media.output.present_frame(&media) { shown.push((picture.timestamp, Instant::now())); @@ -990,7 +990,7 @@ mod tests { tokio::task::yield_now().await; assert_eq!( media.presentation.due(moq_net::Timestamp::from_millis(500).unwrap()), - Some(restarted + delay) + Some(restarted.saturating_add(delay)) ); assert!(media.output.present(&media).is_none()); tokio::time::advance(delay + Duration::from_millis(1)).await; @@ -1728,7 +1728,7 @@ mod tests { let mut shown = Vec::new(); let mut restarted = false; while !task.is_finished() { - if !restarted && Instant::now() >= start + late { + if !restarted && Instant::now() >= start.saturating_add(late) { restart(&mut min); restarted = true; } @@ -1773,7 +1773,7 @@ mod tests { let last = moq_net::Timestamp::from_millis(order.iter().max().unwrap() * 33).unwrap(); let end = media.presentation.due(last).unwrap(); let mut shown = Vec::new(); - while Instant::now() <= end + Duration::from_millis(10) { + while Instant::now() <= end.saturating_add(Duration::from_millis(10)) { if let Some(timestamp) = media.output.present(&media) { shown.push((timestamp, Instant::now())); } diff --git a/rs/moq-cli/src/play/window.rs b/rs/moq-cli/src/play/window.rs index a87905a7ec7..37c72a6d9da 100644 --- a/rs/moq-cli/src/play/window.rs +++ b/rs/moq-cli/src/play/window.rs @@ -202,7 +202,7 @@ impl App { }; let mut video = self.video.lock().unwrap(); // Re-read the shared schedule on every redraw: any track may have moved it. - let cutoff = Instant::now() + VIDEO_EARLY_TOLERANCE; + let cutoff = Instant::now().saturating_add(VIDEO_EARLY_TOLERANCE); let mut due = None; if let Some(index) = self .presentation diff --git a/rs/moq-congestion/src/bbr3/bench.rs b/rs/moq-congestion/src/bbr3/bench.rs index 8632d8d9e0b..f7f751e3959 100644 --- a/rs/moq-congestion/src/bbr3/bench.rs +++ b/rs/moq-congestion/src/bbr3/bench.rs @@ -45,7 +45,9 @@ fn measure(flight: usize, batch: usize, steady: bool) -> (Duration, usize) { let mut elapsed = Duration::ZERO; for first in (0..flight).step_by(batch) { let end = (first + batch).min(flight); - let now = base + Duration::from_millis(10) + Duration::from_micros(first as u64); + let now = base + .saturating_add(Duration::from_millis(10)) + .saturating_add(Duration::from_micros(first as u64)); let in_flight = if steady { flight - (end - first) } else { diff --git a/rs/moq-congestion/src/bbr3/delay.rs b/rs/moq-congestion/src/bbr3/delay.rs index 5ad2a03da8e..bd09996fc67 100644 --- a/rs/moq-congestion/src/bbr3/delay.rs +++ b/rs/moq-congestion/src/bbr3/delay.rs @@ -366,9 +366,9 @@ mod test { ) -> Vec { (0..count) .map(|i| { - let sent = base + spacing * i as u32; + let sent = base.saturating_add(spacing * i as u32); let received = sent - base + delay(i); - detector.on_packet(sent, received, sent + delay(i)); + detector.on_packet(sent, received, sent.saturating_add(delay(i))); detector.usage() }) .collect() @@ -445,14 +445,14 @@ mod test { let delay = Duration::from_millis(20); let mut usage = Vec::new(); for i in 0..1000u32 { - let sent = base + spacing * i; + let sent = base.saturating_add(spacing * i); // The peer's clock jumps 10s ahead halfway, which its ACKs' arrivals do not let jump = if i < 500 { Duration::ZERO } else { Duration::from_secs(10) }; - detector.on_packet(sent, sent - base + delay + jump, sent + delay); + detector.on_packet(sent, sent - base + delay + jump, sent.saturating_add(delay)); usage.push(detector.usage()); } assert!(!usage.contains(&Usage::Overusing)); @@ -470,7 +470,7 @@ mod test { // Every other packet is 30ms slower than its neighbors let packets: Vec = (0..1000u32) .map(|i| { - let sent = base + spacing * i; + let sent = base.saturating_add(spacing * i); let delay = Duration::from_millis(if i % 2 == 0 { 20 } else { 50 }); Acked { sent, @@ -490,7 +490,11 @@ mod test { .filter(|p| p.received.is_some_and(|r| r >= from && r < to)) .copied() .collect(); - detector.on_ack(&acked, base + to + Duration::from_millis(20)); + detector.on_ack( + &acked, + base.saturating_add(to) + .saturating_add(Duration::from_millis(20)), + ); usage.push(detector.usage()); signaled |= detector.take_signal(); } @@ -515,7 +519,7 @@ mod test { detector.on_packet( base, Duration::from_millis(500), - base + Duration::from_secs(1), + base.saturating_add(Duration::from_secs(1)), ); assert_eq!(detector.deltas, before.deltas); assert_eq!(detector.usage(), Usage::Normal); diff --git a/rs/moq-congestion/src/bbr3/mod.rs b/rs/moq-congestion/src/bbr3/mod.rs index 374183f8594..e6c965b22b5 100644 --- a/rs/moq-congestion/src/bbr3/mod.rs +++ b/rs/moq-congestion/src/bbr3/mod.rs @@ -2387,7 +2387,7 @@ mod test { /// Convert a simulator-nanosecond offset into an `Instant`. fn at(&self, off_ns: u64) -> Instant { - self.base + Duration::from_nanos(off_ns) + self.base.saturating_add(Duration::from_nanos(off_ns)) } /// Send `count` packets at `now_ns` outside the link model, for scripted tests that @@ -2512,7 +2512,7 @@ mod test { let ce = self.ce_above_ns.is_some_and(|limit| queue_ns > limit); self.bbr.send( - self.base + Duration::from_nanos(send_ns), + self.base.saturating_add(Duration::from_nanos(send_ns)), self.mss as u16, self.pn, ); @@ -2536,8 +2536,8 @@ mod test { } else if let Some(p) = self.flight.pop_front() { self.now_ns = self.now_ns.max(p.ack_ns); self.inflight -= self.mss; - let now_at = self.base + Duration::from_nanos(self.now_ns); - let send_at = self.base + Duration::from_nanos(p.send_ns); + let now_at = self.base.saturating_add(Duration::from_nanos(self.now_ns)); + let send_at = self.base.saturating_add(Duration::from_nanos(p.send_ns)); let received = self.timestamps.then(|| Duration::from_nanos(p.recv_ns)); self.bbr .ack_received(now_at, send_at, self.mss, p.pn, received); @@ -2702,7 +2702,7 @@ mod test { assert_eq!(bbr.state, BbrState::Startup); let base = Instant::now(); - let at = |off_ns: u64| base + Duration::from_nanos(off_ns); + let at = |off_ns: u64| base.saturating_add(Duration::from_nanos(off_ns)); struct InFlight { pn: u64, @@ -2961,7 +2961,7 @@ mod test { assert_eq!(bbr.state, BbrState::Startup); let base = Instant::now(); - let at = |off_ns: u64| base + Duration::from_nanos(off_ns); + let at = |off_ns: u64| base.saturating_add(Duration::from_nanos(off_ns)); struct InFlight { pn: u64, @@ -3283,7 +3283,7 @@ mod test { assert_eq!(bbr.state, BbrState::Startup); let base = Instant::now(); - let at = |off_ns: u64| base + Duration::from_nanos(off_ns); + let at = |off_ns: u64| base.saturating_add(Duration::from_nanos(off_ns)); struct InFlight { pn: u64, @@ -3431,7 +3431,7 @@ mod test { const MSS: u16 = 1200; let mut bbr = Driver::new(Arc::new(Config::default()), MSS); let base = Instant::now(); - let at = |ms: u64| base + Duration::from_millis(ms); + let at = |ms: u64| base.saturating_add(Duration::from_millis(ms)); let mut inflight = 0; let send = |bbr: &mut Driver, ms: u64, pn: u64, inflight: &mut u64| { bbr.send(at(ms), MSS, pn); @@ -3539,7 +3539,7 @@ mod test { assert_eq!(bbr.state, BbrState::Startup); let base = Instant::now(); - let at = |off_ns: u64| base + Duration::from_nanos(off_ns); + let at = |off_ns: u64| base.saturating_add(Duration::from_nanos(off_ns)); struct InFlight { pn: u64, @@ -4186,7 +4186,7 @@ mod test { assert_eq!(bbr.state, BbrState::Startup); let base = Instant::now(); - let at = |off_ns: u64| base + Duration::from_nanos(off_ns); + let at = |off_ns: u64| base.saturating_add(Duration::from_nanos(off_ns)); struct InFlight { pn: u64, @@ -4440,7 +4440,7 @@ mod test { assert_eq!(bbr.state, BbrState::Startup); let base = Instant::now(); - let at = |off_ns: u64| base + Duration::from_nanos(off_ns); + let at = |off_ns: u64| base.saturating_add(Duration::from_nanos(off_ns)); struct InFlight { pn: u64, @@ -4649,7 +4649,7 @@ mod test { assert_eq!(bbr.state, BbrState::Startup); let base = Instant::now(); - let at = |off_ns: u64| base + Duration::from_nanos(off_ns); + let at = |off_ns: u64| base.saturating_add(Duration::from_nanos(off_ns)); struct InFlight { pn: u64, @@ -4948,7 +4948,7 @@ mod test { assert_eq!(bbr.state, BbrState::Startup); let base = Instant::now(); - let at = |off_ns: u64| base + Duration::from_nanos(off_ns); + let at = |off_ns: u64| base.saturating_add(Duration::from_nanos(off_ns)); struct InFlight { pn: u64, @@ -5223,7 +5223,7 @@ mod test { assert_eq!(bbr.state, BbrState::Startup); let base = Instant::now(); - let at = |off_ns: u64| base + Duration::from_nanos(off_ns); + let at = |off_ns: u64| base.saturating_add(Duration::from_nanos(off_ns)); struct InFlight { pn: u64, @@ -5467,7 +5467,7 @@ mod test { assert_eq!(bbr.state, BbrState::Startup); let base = Instant::now(); - let at = |off_ns: u64| base + Duration::from_nanos(off_ns); + let at = |off_ns: u64| base.saturating_add(Duration::from_nanos(off_ns)); struct InFlight { pn: u64, @@ -5682,7 +5682,7 @@ mod test { assert_eq!(bbr.state, BbrState::Startup); let base = Instant::now(); - let at = |off_ns: u64| base + Duration::from_nanos(off_ns); + let at = |off_ns: u64| base.saturating_add(Duration::from_nanos(off_ns)); struct InFlight { pn: u64, @@ -5897,7 +5897,7 @@ mod test { assert_eq!(bbr.state, BbrState::Startup); let base = Instant::now(); - let at = |off_ns: u64| base + Duration::from_nanos(off_ns); + let at = |off_ns: u64| base.saturating_add(Duration::from_nanos(off_ns)); struct InFlight { pn: u64, @@ -6155,7 +6155,7 @@ mod test { assert_eq!(bbr.state, BbrState::Startup); let base = Instant::now(); - let at = |off_ns: u64| base + Duration::from_nanos(off_ns); + let at = |off_ns: u64| base.saturating_add(Duration::from_nanos(off_ns)); struct InFlight { pn: u64, @@ -6427,7 +6427,7 @@ mod test { assert_eq!(bbr.state, BbrState::Startup); let base = Instant::now(); - let at = |off_ns: u64| base + Duration::from_nanos(off_ns); + let at = |off_ns: u64| base.saturating_add(Duration::from_nanos(off_ns)); struct InFlight { pn: u64, @@ -6685,7 +6685,7 @@ mod test { assert_eq!(bbr.state, BbrState::Startup); let base = Instant::now(); - let at = |off_ns: u64| base + Duration::from_nanos(off_ns); + let at = |off_ns: u64| base.saturating_add(Duration::from_nanos(off_ns)); struct InFlight { pn: u64, @@ -6920,7 +6920,7 @@ mod test { assert_eq!(bbr.state, BbrState::Startup); let base = Instant::now(); - let at = |off_ns: u64| base + Duration::from_nanos(off_ns); + let at = |off_ns: u64| base.saturating_add(Duration::from_nanos(off_ns)); struct InFlight { pn: u64, diff --git a/rs/moq-congestion/src/cubic.rs b/rs/moq-congestion/src/cubic.rs index 2adb8b0d9ae..37b4f51b1c2 100644 --- a/rs/moq-congestion/src/cubic.rs +++ b/rs/moq-congestion/src/cubic.rs @@ -356,7 +356,12 @@ mod tests { cubic.state.ssthresh = window; cubic.state.w_max = 12.0 * BASE_DATAGRAM_SIZE as f64; - cubic.on_congestion(now, now + Duration::from_millis(1), false, false); + cubic.on_congestion( + now, + now.saturating_add(Duration::from_millis(1)), + false, + false, + ); assert_eq!(cubic.state.w_max, window as f64 * (1.0 + BETA_CUBIC) / 2.0); assert_eq!(cubic.state.ssthresh, (window as f64 * BETA_CUBIC) as u64); @@ -373,7 +378,12 @@ mod tests { cubic.state.ssthresh = window; cubic.state.w_max = window as f64; - cubic.on_congestion(now, now + Duration::from_millis(1), true, false); + cubic.on_congestion( + now, + now.saturating_add(Duration::from_millis(1)), + true, + false, + ); // RFC 9438 §4.8 (Timeout): ssthresh is the pre-event window reduced by β_cubic // exactly once, as in §4.6; only cwnd is lowered to the minimum window. @@ -398,7 +408,7 @@ mod tests { cubic.on_acked( now, - now + Duration::from_millis(1), + now.saturating_add(Duration::from_millis(1)), BASE_DATAGRAM_SIZE, false, ); @@ -421,7 +431,7 @@ mod tests { // After ten days without a congestion event, w_cubic exceeds u64::MAX. // Before this fix, computing the window increment overflowed. - let later = now + Duration::from_secs(10 * 24 * 60 * 60); + let later = now.saturating_add(Duration::from_secs(10 * 24 * 60 * 60)); cubic.on_acked(later, later, BASE_DATAGRAM_SIZE, false); assert_eq!(cubic.state.window, window + BASE_DATAGRAM_SIZE); diff --git a/rs/moq-congestion/src/gcc/bench.rs b/rs/moq-congestion/src/gcc/bench.rs index db9a2300893..42b0585174a 100644 --- a/rs/moq-congestion/src/gcc/bench.rs +++ b/rs/moq-congestion/src/gcc/bench.rs @@ -10,7 +10,7 @@ const PACKET: u16 = 1200; /// Times the controller callbacks for `flight` packets acknowledged `batch` at a time, refilled as /// they are acknowledged if `steady`, each with a receive time fn measure(flight: usize, batch: usize, steady: bool) -> Duration { - let base = Instant::ZERO + Duration::from_secs(1); + let base = Instant::ZERO.saturating_add(Duration::from_secs(1)); let mut gcc = Gcc::new(Init { now: base, mtu: PACKET, @@ -20,7 +20,7 @@ fn measure(flight: usize, batch: usize, steady: bool) -> Duration { let bytes = u64::from(PACKET); let mut sent = Vec::with_capacity(2 * flight); for pn in 0..flight { - let now = base + Duration::from_micros(pn as u64); + let now = base.saturating_add(Duration::from_micros(pn as u64)); sent.push(( now, gcc.on_sent(Sent { @@ -34,7 +34,9 @@ fn measure(flight: usize, batch: usize, steady: bool) -> Duration { let mut elapsed = Duration::ZERO; for first in (0..flight).step_by(batch) { let end = (first + batch).min(flight); - let now = base + Duration::from_millis(10) + Duration::from_micros(first as u64); + let now = base + .saturating_add(Duration::from_millis(10)) + .saturating_add(Duration::from_micros(first as u64)); let in_flight = if steady { flight - (end - first) } else { @@ -47,7 +49,7 @@ fn measure(flight: usize, batch: usize, steady: bool) -> Duration { sent: at, bytes: PACKET, packet, - received: Some(at - base + Duration::from_millis(5)), + received: Some((at - base).saturating_add(Duration::from_millis(5))), })); gcc.on_ack(Ack { now, diff --git a/rs/moq-congestion/src/gcc/mod.rs b/rs/moq-congestion/src/gcc/mod.rs index 61e2ea049c1..2614226e404 100644 --- a/rs/moq-congestion/src/gcc/mod.rs +++ b/rs/moq-congestion/src/gcc/mod.rs @@ -236,7 +236,7 @@ impl Gcc { if now < self.next_process { return; } - self.next_process = now + PROCESS_INTERVAL; + self.next_process = now.saturating_add(PROCESS_INTERVAL); let update = self.cc.on_process_interval(ProcessInterval { at_time: timestamp(now), pacer_queue: None, @@ -457,7 +457,7 @@ impl Controller for Gcc { if next <= at { return None; } - return Some(now + Duration::from_micros((next - at).us().max(0) as u64)); + return Some(now.saturating_add(Duration::from_micros((next - at).us().max(0) as u64))); } let rate = Rate { window: self.congestion_window(), diff --git a/rs/moq-congestion/src/gcc/tests.rs b/rs/moq-congestion/src/gcc/tests.rs index 29b763f9df9..a833a1cfa8c 100644 --- a/rs/moq-congestion/src/gcc/tests.rs +++ b/rs/moq-congestion/src/gcc/tests.rs @@ -59,7 +59,7 @@ struct Sim { impl Sim { fn new(rate: u64, source: Source) -> Self { - let epoch = Instant::ZERO + Duration::from_secs(1000); + let epoch = Instant::ZERO.saturating_add(Duration::from_secs(1000)); let gcc = Gcc::new(Init { now: epoch, mtu: MTU, @@ -94,7 +94,7 @@ impl Sim { self.ack(); self.write(); self.send(); - self.now += Duration::from_millis(1); + self.now = self.now.saturating_add(Duration::from_millis(1)); } } @@ -102,7 +102,7 @@ impl Sim { if let Source::Media(rate) = self.source { while self.next_frame <= self.now { self.backlog += rate / 30; - self.next_frame += Duration::from_secs(1) / 30; + self.next_frame = self.next_frame.saturating_add(Duration::from_secs(1) / 30); } } } @@ -143,10 +143,10 @@ impl Sim { let start = self.busy_until.max(self.now); let wait = start - self.now; let arrival = (wait <= self.queue).then(|| { - self.busy_until = - start + Duration::from_secs_f64(f64::from(MTU) / self.rate as f64); + self.busy_until = start + .saturating_add(Duration::from_secs_f64(f64::from(MTU) / self.rate as f64)); self.queued.push((self.elapsed(), wait)); - self.busy_until + DELAY + self.busy_until.saturating_add(DELAY) }); self.flight.push_back(Flight { sent: self.now, @@ -160,7 +160,7 @@ impl Sim { /// Acknowledges what arrived a propagation delay ago, and declares lost a packet the /// bottleneck dropped once three later packets were acknowledged or [`LOSS_TIMEOUT`] passed fn ack(&mut self) { - let acked_by = |arrival: Instant| arrival + DELAY; + let acked_by = |arrival: Instant| arrival.saturating_add(DELAY); let mut acked = Vec::new(); let mut lost = Vec::new(); while let Some(front) = self.flight.front() { @@ -175,7 +175,7 @@ impl Sim { .take(3) .filter(|f| f.arrival.is_some_and(|a| acked_by(a) <= self.now)) .count(); - if acked_later < 3 && self.now < front.sent + LOSS_TIMEOUT { + if acked_later < 3 && self.now < front.sent.saturating_add(LOSS_TIMEOUT) { break; } } @@ -371,7 +371,7 @@ fn probes_aim_at_the_target() { /// holding the sender to the bytes and leaving it unfinished #[test] fn probe_inflight_rounds_up_to_a_packet() { - let now = Instant::ZERO + Duration::from_secs(1000); + let now = Instant::ZERO.saturating_add(Duration::from_secs(1000)); let mut gcc = Gcc::new(Init { now, mtu: MTU, @@ -442,7 +442,7 @@ fn restart_ids_never_alias_googcc_ids() { /// leave the estimate outside GoogCC's bounds #[test] fn survives_hostile_receive_times() { - let mut now = Instant::ZERO + Duration::from_secs(1000); + let mut now = Instant::ZERO.saturating_add(Duration::from_secs(1000)); let mut gcc = Gcc::new(Init { now, mtu: MTU, @@ -459,7 +459,7 @@ fn survives_hostile_receive_times() { Some(Duration::from_nanos(1)), ]; for round in 0..2000 { - now += Duration::from_millis(1); + now = now.saturating_add(Duration::from_millis(1)); let packet = gcc.on_sent(Sent { now, bytes: MTU, @@ -490,7 +490,7 @@ fn survives_hostile_receive_times() { #[test] fn window_floor_tracks_mtu() { const LARGE: u16 = 65527; - let mut now = Instant::ZERO + Duration::from_secs(1000); + let mut now = Instant::ZERO.saturating_add(Duration::from_secs(1000)); let mut gcc = Gcc::new(Init { now, mtu: LARGE, @@ -498,7 +498,7 @@ fn window_floor_tracks_mtu() { seed: 0, }); for _ in 0..200 { - now += Duration::from_millis(10); + now = now.saturating_add(Duration::from_millis(10)); let packet = gcc.on_sent(Sent { now, bytes: MTU, diff --git a/rs/moq-congestion/src/pacer.rs b/rs/moq-congestion/src/pacer.rs index a8dbb8d0900..85b3ea21104 100644 --- a/rs/moq-congestion/src/pacer.rs +++ b/rs/moq-congestion/src/pacer.rs @@ -144,7 +144,7 @@ impl Pacer { // divisions come before multiplications to prevent overflow // this is the time at which the pacing window becomes empty - Some(now + (unscaled_delay / 5) * 4) + Some(now.saturating_add((unscaled_delay / 5) * 4)) } /// Return how long we need to wait before sending `bytes_to_send` when the congestion @@ -198,7 +198,9 @@ impl Pacer { // a nanosecond, and truncating that to zero would re-arm the timer at `now` forever. let deficit = target.saturating_sub(self.tokens) + self.debt; let nanos = (u128::from(deficit) * 1_000_000_000).div_ceil(u128::from(rate)); - Some(now + Duration::from_nanos(u64::try_from(nanos).unwrap_or(u64::MAX))) + Some(now.saturating_add(Duration::from_nanos( + u64::try_from(nanos).unwrap_or(u64::MAX), + ))) } } @@ -322,7 +324,7 @@ mod tests { /// pacer needs for ten seconds at [`TEST_PACING_RATE`]. const MAX_POLLS: u64 = 1_000_000; - let deadline = start + duration; + let deadline = start.saturating_add(duration); let mut at = start; let mut sent = 0; let mut polls = 0; @@ -424,14 +426,20 @@ mod tests { pacer.on_transmit(mtu); let packet_time = Duration::from_nanos((u64::from(mtu) * 1_000_000_000).div_ceil(rate)); - let resume = start + packet_time * 2; + let resume = start.saturating_add(packet_time * 2); assert_eq!( pacer.delay(rtt, u64::from(mtu), mtu, start, metrics), Some(resume) ); // Earning one packet repays the overdraw; the next packet still needs credit. assert_eq!( - pacer.delay(rtt, u64::from(mtu), mtu, start + packet_time, metrics), + pacer.delay( + rtt, + u64::from(mtu), + mtu, + start.saturating_add(packet_time), + metrics + ), Some(resume), ); assert_eq!(pacer.delay(rtt, u64::from(mtu), mtu, resume, metrics), None); @@ -465,8 +473,9 @@ mod tests { window: rate / 25, pacing_rate: explicit_rate.then_some(rate), }; - let resume = start - + Duration::from_nanos((2 * u64::from(mtu) * 1_000_000_000).div_ceil(rate)); + let resume = start.saturating_add(Duration::from_nanos( + (2 * u64::from(mtu) * 1_000_000_000).div_ceil(rate), + )); assert_eq!( pacer.delay(rtt, u64::from(mtu), mtu, start, metrics), Some(resume) @@ -526,7 +535,7 @@ mod tests { #[test] fn does_not_panic_on_bad_instant() { let old_instant = Instant::now(); - let new_instant = old_instant + Duration::from_micros(15); + let new_instant = old_instant.saturating_add(Duration::from_micros(15)); let rtt = Duration::from_micros(400); assert!( @@ -666,7 +675,7 @@ mod tests { rtt, mtu as u64, mtu, - old_instant + pace_duration / 2, + old_instant.saturating_add(pace_duration / 2), unpaced_metrics(window), ), None @@ -689,7 +698,7 @@ mod tests { rtt, mtu as u64, mtu, - old_instant + pace_duration * 3 / 2, + old_instant.saturating_add(pace_duration * 3 / 2), unpaced_metrics(window), ), None diff --git a/rs/moq-congestion/src/scream.rs b/rs/moq-congestion/src/scream.rs index 41d6ddcd339..c34b10745b1 100644 --- a/rs/moq-congestion/src/scream.rs +++ b/rs/moq-congestion/src/scream.rs @@ -639,7 +639,7 @@ mod tests { now, rate, busy_until: now, - basis: now - Duration::from_secs(1), + basis: now.saturating_sub(Duration::from_secs(1)), drift_ppm: 0.0, media, backlog: 0.0, @@ -654,9 +654,9 @@ mod tests { /// Runs for `duration`, returning the bytes delivered and each packet's queueing delay fn run(&mut self, duration: Duration) -> (u64, Vec) { let (delivered, queued) = (self.delivered, self.queue.len()); - let end = self.now + duration; + let end = self.now.saturating_add(duration); while self.now < end { - self.now += TICK; + self.now = self.now.saturating_add(TICK); self.deliver(); self.send(); } @@ -680,12 +680,13 @@ mod tests { }); let start = Ord::max(self.busy_until, self.now); self.queue.push(start - self.now); - self.busy_until = start + Duration::from_secs_f64(bytes as f64 / self.rate); - let arrival = self.busy_until + PROPAGATION; + self.busy_until = + start.saturating_add(Duration::from_secs_f64(bytes as f64 / self.rate)); + let arrival = self.busy_until.saturating_add(PROPAGATION); self.flights.push_back(Flight { sent: self.now, arrival, - acked: arrival + PROPAGATION, + acked: arrival.saturating_add(PROPAGATION), }); } } @@ -773,7 +774,7 @@ mod tests { let mut windows = Vec::new(); for basis in [Duration::ZERO, Duration::from_secs(3600)] { let mut path = Path::new(250_000.0, None, Config::default()); - path.basis = path.now - basis; + path.basis = path.now.saturating_sub(basis); path.run(Duration::from_secs(10)); windows.push(path.scream.window()); } @@ -833,9 +834,13 @@ mod tests { let now = Instant::now(); let mut base = BaseDelay::new(now); base.update(now, 1_000); - base.update(now + BASE_INTERVAL * 3, 5_000); + base.update(now.saturating_add(BASE_INTERVAL * 3), 5_000); assert_eq!(base.get(), 1_000, "a minimum inside the history expired"); - base.update(now + BASE_INTERVAL * 3 + Duration::from_secs(600), 9_000); + base.update( + now.saturating_add(BASE_INTERVAL * 3) + .saturating_add(Duration::from_secs(600)), + 9_000, + ); assert_eq!( base.get(), 9_000, @@ -877,17 +882,29 @@ mod tests { let now = Instant::now(); let mut scream = scream(now, Config::default()); scream.ref_wnd = 100_000.0; - lose(&mut scream, now + ms(50), now + ms(1)); + lose( + &mut scream, + now.saturating_add(ms(50)), + now.saturating_add(ms(1)), + ); assert_eq!(scream.ref_wnd, 100_000.0 * BETA_LOSS); - lose(&mut scream, now + ms(200), now + ms(40)); + lose( + &mut scream, + now.saturating_add(ms(200)), + now.saturating_add(ms(40)), + ); assert_eq!( scream.ref_wnd, 100_000.0 * BETA_LOSS, "reacted to a loss it answered" ); - lose(&mut scream, now + ms(300), now + ms(100)); + lose( + &mut scream, + now.saturating_add(ms(300)), + now.saturating_add(ms(100)), + ); assert_eq!(scream.ref_wnd, 100_000.0 * BETA_LOSS * BETA_LOSS); } @@ -903,7 +920,7 @@ mod tests { scream.bytes_newly_acked = 100_000; // Just past half the target: alpha 0.1 scream.qdelay_avg = Duration::from_millis(33); - scream.update(now + Duration::from_millis(50)); + scream.update(now.saturating_add(Duration::from_millis(50))); // At a 333ms RTT, a reaction every 25ms takes 1/13.3 of alpha / 2 let reduced = 100_000.0 * (1.0 - 0.1 / 2.0 / (333.0 / 25.0)); diff --git a/rs/moq-ffi/src/test/rung.rs b/rs/moq-ffi/src/test/rung.rs index 4d27196e4ed..d6f00e70250 100644 --- a/rs/moq-ffi/src/test/rung.rs +++ b/rs/moq-ffi/src/test/rung.rs @@ -132,7 +132,7 @@ async fn shaped_uplink_disables_and_resumes() { let mut previous_second = None; loop { tokio::select! { - _ = kio::clock::sleep_until(start + END) => break, + _ = kio::clock::sleep_until(start.saturating_add(END)) => break, _ = ticker.tick() => { let elapsed = start.elapsed(); let timestamp = elapsed.as_micros() as u64; diff --git a/rs/moq-gst/src/source/imp.rs b/rs/moq-gst/src/source/imp.rs index 5c81a981e35..01b61f92971 100644 --- a/rs/moq-gst/src/source/imp.rs +++ b/rs/moq-gst/src/source/imp.rs @@ -3975,7 +3975,7 @@ mod session_tests { /// Move the timestamps of later frames `by` ahead. fn skip(&mut self, by: Duration) { - self.start -= by; + self.start = self.start.saturating_sub(by); } } @@ -6348,7 +6348,7 @@ mod session_tests { let errors = || { [&publisher, &subscriber].map(|pipeline| pipeline.bus().unwrap().pop_filtered(&[gst::MessageType::Error])) }; - let deadline = kio::clock::now() + Duration::from_secs(30); + let deadline = kio::clock::now().saturating_add(Duration::from_secs(30)); let mut samples = Vec::new(); while samples.len() < FRAMES * CHANNELS { assert!( diff --git a/rs/moq-hls/src/export/mod.rs b/rs/moq-hls/src/export/mod.rs index 1cd058f7cab..bff782b6321 100644 --- a/rs/moq-hls/src/export/mod.rs +++ b/rs/moq-hls/src/export/mod.rs @@ -1899,7 +1899,7 @@ mod tests { media.write(vp8_frame(micros, true)).unwrap(); } - let deadline = kio::clock::now() + Duration::from_secs(5); + let deadline = kio::clock::now().saturating_add(Duration::from_secs(5)); let new = loop { let current = broadcaster.rendition(Kind::Video, "video0").expect("rendition"); if !Arc::ptr_eq(¤t, &old) { @@ -2695,7 +2695,7 @@ mod tests { media.finish().unwrap(); catalog.finish().unwrap(); - let deadline = kio::clock::now() + Duration::from_secs(5); + let deadline = kio::clock::now().saturating_add(Duration::from_secs(5)); let manifest = loop { let manifest = broadcaster.manifest(None).unwrap().expect("manifest renders"); if manifest.contains(" type=\"static\"") { diff --git a/rs/moq-hls/src/import.rs b/rs/moq-hls/src/import.rs index dd5b7cded9f..cadaba9f29c 100644 --- a/rs/moq-hls/src/import.rs +++ b/rs/moq-hls/src/import.rs @@ -846,7 +846,7 @@ impl Import { /// amount of waiting changes either. pub async fn run(&mut self) -> Result<()> { let mut delay = STEP_RETRY_MIN; - let mut deadline = kio::clock::now() + STEP_RETRY_BUDGET; + let mut deadline = kio::clock::now().saturating_add(STEP_RETRY_BUDGET); loop { // A step where *nothing* ingested while a rendition was failing is a failed pass wearing @@ -870,7 +870,7 @@ impl Import { Ok(outcome) => { // The source is alive, so the earlier failures no longer describe it. delay = STEP_RETRY_MIN; - deadline = kio::clock::now() + STEP_RETRY_BUDGET; + deadline = kio::clock::now().saturating_add(STEP_RETRY_BUDGET); outcome } Err(err @ Error::ResourceRefused) => return Err(err), diff --git a/rs/moq-hls/src/server/include_tests.rs b/rs/moq-hls/src/server/include_tests.rs index f3b9ff55049..1f5bc15e577 100644 --- a/rs/moq-hls/src/server/include_tests.rs +++ b/rs/moq-hls/src/server/include_tests.rs @@ -88,7 +88,7 @@ async fn request(server: &Server, uri: &str) -> (StatusCode, String) { } async fn master(server: &Server, contains: &str, present: bool) -> String { - let deadline = kio::clock::now() + Duration::from_secs(10); + let deadline = kio::clock::now().saturating_add(Duration::from_secs(10)); loop { let (status, body) = request(server, "/room/live/master.m3u8?jwt=viewer").await; if status == StatusCode::OK && body.contains(contains) == present { @@ -225,7 +225,7 @@ async fn a_failed_parent_catalog_stops_its_includes() { master(&server, "include/", true).await; let uri = format!("/room/live/@{root}/include/rung%2Fa/video/same/@{child}/media.m3u8"); parent_catalog_track.abort(moq_net::Error::Cancel).unwrap(); - let deadline = kio::clock::now() + Duration::from_secs(10); + let deadline = kio::clock::now().saturating_add(Duration::from_secs(10)); // A live include's playlist waits for media this test never writes, so bound each request. while !matches!( kio::clock::timeout(Duration::from_secs(1), request(&server, &uri)).await, @@ -305,7 +305,7 @@ async fn idle_release_keeps_an_ended_playlists_inherited_segments() { frames(&next, 3); let _next = next.finish().unwrap(); drop(held); - let deadline = kio::clock::now() + Duration::from_secs(10); + let deadline = kio::clock::now().saturating_add(Duration::from_secs(10)); let ended = loop { let (status, playlist) = request(&server, &uri).await; if status == StatusCode::OK && playlist.contains("#EXT-X-ENDLIST") { diff --git a/rs/moq-hls/src/server/routes.rs b/rs/moq-hls/src/server/routes.rs index 4f653399656..7acc470ad6c 100644 --- a/rs/moq-hls/src/server/routes.rs +++ b/rs/moq-hls/src/server/routes.rs @@ -342,7 +342,7 @@ mod tests { } async fn wait_listed(app: &axum::Router, playlist: &str, segment: &str) { - let deadline = kio::clock::now() + TIMEOUT; + let deadline = kio::clock::now().saturating_add(TIMEOUT); let mut last = String::new(); loop { let response = oneshot(app.clone(), playlist).await; @@ -532,7 +532,7 @@ mod tests { assert_eq!(status(&app, &old_segment).await, StatusCode::OK); drop((old_catalog, old_track, old_media, old)); - let deadline = kio::clock::now() + TIMEOUT; + let deadline = kio::clock::now().saturating_add(TIMEOUT); while status(&app, &old_playlist).await != StatusCode::NOT_FOUND { assert!(kio::clock::now() < deadline, "the closed instance kept serving"); kio::clock::sleep(Duration::from_millis(50)).await; @@ -574,7 +574,7 @@ mod tests { publish_video(&mut new.broadcast().clone(), video_config(), timed()); write_three_gops(&mut new_media); - let deadline = kio::clock::now() + TIMEOUT; + let deadline = kio::clock::now().saturating_add(TIMEOUT); let successor = loop { let current = server.broadcaster("live").await.expect("announced"); if current.instance().as_ref() == next.as_str() { @@ -653,7 +653,7 @@ mod tests { .abort(moq_net::Error::Transport("connection lost".into())) .unwrap(); for uri in [&format!("/live/@{RUN}/video/video0/media.m3u8"), "/live/manifest.mpd"] { - let deadline = kio::clock::now() + TIMEOUT; + let deadline = kio::clock::now().saturating_add(TIMEOUT); let response = loop { let response = oneshot(app.clone(), uri).await; if response.status() != StatusCode::OK { diff --git a/rs/moq-hls/tests/integration/conformance.rs b/rs/moq-hls/tests/integration/conformance.rs index 897b9589763..157a7a75971 100644 --- a/rs/moq-hls/tests/integration/conformance.rs +++ b/rs/moq-hls/tests/integration/conformance.rs @@ -108,7 +108,7 @@ async fn segments_match_their_manifests() { import.finish().expect("finish import"); catalog.finish().expect("finish catalog"); - let deadline = kio::clock::now() + TIMEOUT; + let deadline = kio::clock::now().saturating_add(TIMEOUT); while seen.poll(&app).await != Polled::Ended { assert!(kio::clock::now() < deadline, "the playlists never ended"); kio::clock::sleep(Duration::from_millis(50)).await; @@ -282,7 +282,7 @@ impl Recorder { /// Wait until each rendition's cursor has recorded the `newest` segment its playlist listed, /// or failed. async fn caught_up(&self, newest: &BTreeMap<&str, u64>) { - let deadline = kio::clock::now() + TIMEOUT; + let deadline = kio::clock::now().saturating_add(TIMEOUT); loop { let behind = { let recorded = self.recorded.lock().unwrap(); diff --git a/rs/moq-hls/tests/integration/finish.rs b/rs/moq-hls/tests/integration/finish.rs index 4d9ec919db4..f3544b9a77d 100644 --- a/rs/moq-hls/tests/integration/finish.rs +++ b/rs/moq-hls/tests/integration/finish.rs @@ -47,7 +47,7 @@ async fn finish(order: Order) { publisher.media.finish().expect("finish media"); publisher.route.broadcast().close(); // The server stops serving the instance once `End` reaches it. - let deadline = kio::clock::now() + TIMEOUT; + let deadline = kio::clock::now().saturating_add(TIMEOUT); while get(&app, &media).await.status() != StatusCode::NOT_FOUND { assert!(kio::clock::now() < deadline, "End never reached the export"); kio::clock::sleep(Duration::from_millis(50)).await; diff --git a/rs/moq-hls/tests/integration/restart.rs b/rs/moq-hls/tests/integration/restart.rs index 5a9e2200946..2d473f2a50b 100644 --- a/rs/moq-hls/tests/integration/restart.rs +++ b/rs/moq-hls/tests/integration/restart.rs @@ -74,7 +74,7 @@ async fn takeover(version: &str, case: Case) { // The new instance numbers its groups and segments from zero again. let mut new = Publisher::new(&pair.publisher, "live", Default::default()); - let deadline = kio::clock::now() + TIMEOUT; + let deadline = kio::clock::now().saturating_add(TIMEOUT); let current = loop { let current = server.broadcaster("live").await.expect("announced"); // Each broadcaster builds its own renditions, so only the replaced one still holds this. diff --git a/rs/moq-hls/tests/integration/server.rs b/rs/moq-hls/tests/integration/server.rs index 98b9a47ab56..6e465de49cb 100644 --- a/rs/moq-hls/tests/integration/server.rs +++ b/rs/moq-hls/tests/integration/server.rs @@ -18,7 +18,7 @@ async fn respond_serves_a_route_rewritten_into_scope() { let mut route = Route::parse(&format!("/tenant{media}")).expect("media route"); route.broadcast = route.broadcast.strip_prefix("tenant/").expect("scoped").to_string(); - let deadline = kio::clock::now() + TIMEOUT; + let deadline = kio::clock::now().saturating_add(TIMEOUT); let body = loop { let response = server.respond(&route, Some("jwt=abc")).await; if response.status() == StatusCode::OK { diff --git a/rs/moq-hls/tests/integration/support.rs b/rs/moq-hls/tests/integration/support.rs index 5e68764ab8c..0bdb2c2dda5 100644 --- a/rs/moq-hls/tests/integration/support.rs +++ b/rs/moq-hls/tests/integration/support.rs @@ -223,7 +223,7 @@ pub async fn get(app: &axum::Router, uri: &str) -> Response { /// Poll `uri` until it answers 200 with a body containing `needle`, returning the body. pub async fn listed(app: &axum::Router, uri: &str, needle: &str) -> String { - let deadline = kio::clock::now() + TIMEOUT; + let deadline = kio::clock::now().saturating_add(TIMEOUT); loop { let response = get(app, uri).await; let body = String::from_utf8_lossy(response.body()).into_owned(); diff --git a/rs/moq-mux/benches/decode_clock.rs b/rs/moq-mux/benches/decode_clock.rs index f3ddb0567a3..4ab3bf305a9 100644 --- a/rs/moq-mux/benches/decode_clock.rs +++ b/rs/moq-mux/benches/decode_clock.rs @@ -76,7 +76,7 @@ fn read(c: &mut Criterion) { let mut clock = decode::DecodeClock::default(); let (mut held, mut most) = (0, 0); for index in 0..frames { - let latest = Instant::ZERO + Duration::from_millis(index); + let latest = Instant::ZERO.saturating_add(Duration::from_millis(index)); clock.push(index, pts(shape, index), latest, 0); held += 1; loop { diff --git a/rs/moq-mux/benches/jitter.rs b/rs/moq-mux/benches/jitter.rs index 0d7e40e3a68..fef7f0e50ab 100644 --- a/rs/moq-mux/benches/jitter.rs +++ b/rs/moq-mux/benches/jitter.rs @@ -20,7 +20,7 @@ async fn steer(tracks: u16, floors: u64) -> u64 { buffer.expect(1..=tracks); let waiter = kio::Waiter::noop(); for second in 0..floors * 2 { - let at = start + Duration::from_secs(second); + let at = start.saturating_add(Duration::from_secs(second)); tokio::time::advance(at.saturating_duration_since(kio::clock::now())).await; for track in 1..=tracks { let arrival = jitter::Arrival { diff --git a/rs/moq-mux/benches/sync.rs b/rs/moq-mux/benches/sync.rs index 32104b1d27c..77b04a33a2a 100644 --- a/rs/moq-mux/benches/sync.rs +++ b/rs/moq-mux/benches/sync.rs @@ -8,7 +8,7 @@ use moq_net::Timestamp; fn presentation(c: &mut Criterion) { let mut group = c.benchmark_group("sync_present"); - let now = Instant::ZERO + Duration::from_secs(1); + let now = Instant::ZERO.saturating_add(Duration::from_secs(1)); for readers in [1, 8, 64] { for frames in [1, 3, 30] { let clock = sync::Producer::new(Duration::from_millis(100)); @@ -24,8 +24,10 @@ fn presentation(c: &mut Criterion) { group.bench_function(BenchmarkId::new(readers.to_string(), frames), |b| { b.iter(|| { for consumer in &consumers { - let selected = - consumer.present(black_box(timestamps.iter().copied()), now + Duration::from_secs(1)); + let selected = consumer.present( + black_box(timestamps.iter().copied()), + now.saturating_add(Duration::from_secs(1)), + ); assert_eq!(selected, Some(frames as usize - 1)); } }); @@ -36,7 +38,7 @@ fn presentation(c: &mut Criterion) { } fn update(c: &mut Criterion) { - let now = Instant::ZERO + Duration::from_secs(1); + let now = Instant::ZERO.saturating_add(Duration::from_secs(1)); let clock = sync::Producer::new(Duration::from_millis(100)); let audio = clock.track(Kind::Audio); let _video = clock.track(Kind::Video); diff --git a/rs/moq-mux/src/catalog/producer.rs b/rs/moq-mux/src/catalog/producer.rs index a40ab4fd911..5a020bdf06e 100644 --- a/rs/moq-mux/src/catalog/producer.rs +++ b/rs/moq-mux/src/catalog/producer.rs @@ -1189,7 +1189,11 @@ impl Guard<'_, E> { return Ok(()); } let now = kio::clock::now(); - if throttle && estimates.last.is_some_and(|last| now < last + ESTIMATE_WINDOW) { + if throttle + && estimates + .last + .is_some_and(|last| now < last.saturating_add(ESTIMATE_WINDOW)) + { return Ok(()); } self.updated = true; @@ -2346,7 +2350,7 @@ mod test { kio::clock::sleep(Duration::from_secs(5)).await; let mut broadcast = moq_net::broadcast::Info::new().produce(); let wall = kio::clock::Wall::MOQ_EPOCH + Duration::from_millis(60_000); - let start = kio::clock::now() - Duration::from_secs(5); + let start = kio::clock::now().saturating_sub(Duration::from_secs(5)); let config = Config::default().with_clock(crate::Clock::at(start, wall).expect("a representable wall")); let catalog = Producer::new(&mut broadcast, config).unwrap(); diff --git a/rs/moq-mux/src/clock.rs b/rs/moq-mux/src/clock.rs index c1c9eb61d36..550cbeb4813 100644 --- a/rs/moq-mux/src/clock.rs +++ b/rs/moq-mux/src/clock.rs @@ -301,15 +301,18 @@ mod tests { async fn a_capture_maps_onto_the_clock() { kio::clock::sleep(Duration::from_secs(6)).await; let now = kio::clock::now(); - let clock = Clock::at(now - Duration::from_secs(5), moq_epoch()).unwrap(); - assert_eq!(clock.capture(now - Duration::from_secs(2)).unwrap(), us(3_000_000)); + let clock = Clock::at(now.saturating_sub(Duration::from_secs(5)), moq_epoch()).unwrap(); + assert_eq!( + clock.capture(now.saturating_sub(Duration::from_secs(2))).unwrap(), + us(3_000_000) + ); assert!(matches!( - clock.capture(kio::clock::now() + Duration::from_secs(1)), + clock.capture(kio::clock::now().saturating_add(Duration::from_secs(1))), Err(crate::Error::InvalidCapture) )); assert!(matches!( - clock.capture(now - Duration::from_secs(6)), + clock.capture(now.saturating_sub(Duration::from_secs(6))), Err(crate::Error::InvalidCapture) )); } @@ -341,14 +344,14 @@ mod tests { "a new mapping samples the corrected wall" ); - let captured = epoch + Duration::from_secs(2); + let captured = epoch.saturating_add(Duration::from_secs(2)); assert_eq!(clock.capture(captured).unwrap(), us(2_000_000)); assert!(matches!( - clock.capture(epoch + Duration::from_secs(4)), + clock.capture(epoch.saturating_add(Duration::from_secs(4))), Err(crate::Error::InvalidCapture) )); assert!(matches!( - clock.capture(epoch - Duration::from_secs(1)), + clock.capture(epoch.saturating_sub(Duration::from_secs(1))), Err(crate::Error::InvalidCapture) )); } @@ -403,7 +406,9 @@ mod tests { assert!(drift < Duration::from_secs(1), "the first timestamp is live on arrival"); // A capture from before the arrival still maps, down to PTS zero. - let earlier = clock.capture(kio::clock::now() - Duration::from_secs(1)).unwrap(); + let earlier = clock + .capture(kio::clock::now().saturating_sub(Duration::from_secs(1))) + .unwrap(); assert!(earlier.as_micros() < now.as_micros()); // PTS zero before 2020 cannot be named on the wire. diff --git a/rs/moq-mux/src/container/ts/damage.rs b/rs/moq-mux/src/container/ts/damage.rs index fbbdb9f570a..5f165d49f5f 100644 --- a/rs/moq-mux/src/container/ts/damage.rs +++ b/rs/moq-mux/src/container/ts/damage.rs @@ -51,7 +51,7 @@ impl Log { if first { tracing::warn!(pid, count = 1, %error, "dropped a damaged TS unit"); } - self.next.get_or_insert(now + stats::Log::INTERVAL); + self.next.get_or_insert(now.saturating_add(stats::Log::INTERVAL)); } pub fn flush(&mut self, now: Instant) { @@ -63,7 +63,7 @@ impl Log { // A quiet interval ends the burst, so its next damage warns immediately. now.duration_since(burst.last) < stats::Log::INTERVAL }); - self.next = (!self.bursts.is_empty()).then_some(now + stats::Log::INTERVAL); + self.next = (!self.bursts.is_empty()).then_some(now.saturating_add(stats::Log::INTERVAL)); } } diff --git a/rs/moq-mux/src/container/ts/export.rs b/rs/moq-mux/src/container/ts/export.rs index f2fca18a1f7..e623914922e 100644 --- a/rs/moq-mux/src/container/ts/export.rs +++ b/rs/moq-mux/src/container/ts/export.rs @@ -895,8 +895,8 @@ impl Track { let ahead = ahead.min(arrived.duration_since(kio::clock::Instant::ZERO)); let ahead = ahead.min(read.duration_since(kio::clock::Instant::ZERO)); let arrival = Arrival { - arrived: arrived - ahead, - read: read - ahead, + arrived: arrived.saturating_sub(ahead), + read: read.saturating_sub(ahead), decode: key.into(), restart, sync, @@ -2892,7 +2892,8 @@ where self.cancel_pending(); let next = self.replacement(self.program.source.switched(broadcast), catalog); self.pending = Some(Box::new(next)); - self.follow_until.get_or_insert_with(|| kio::clock::now() + follow); + self.follow_until + .get_or_insert_with(|| kio::clock::now().saturating_add(follow)); return Ok(()); } if let Some(mut pending) = self.pending.take() { @@ -5343,7 +5344,11 @@ mod tests { // The last available audio frame, including its scheduling lead, anchors both orders. let (decode, key, _) = tracks[1].released.unwrap(); assert_eq!(decode.as_micros(), 800_000); - assert_eq!(jitter.at(0, key), Some(start + Duration::from_millis(500)), "{order:?}"); + assert_eq!( + jitter.at(0, key), + Some(start.saturating_add(Duration::from_millis(500))), + "{order:?}" + ); tokio::time::advance(Duration::from_millis(500)).await; let video = std::iter::from_fn(|| match jitter.poll_next(&waiter) { std::task::Poll::Ready(ready) => Some(ready), diff --git a/rs/moq-mux/src/container/ts/export_test.rs b/rs/moq-mux/src/container/ts/export_test.rs index a1a637f9631..5689c40e792 100644 --- a/rs/moq-mux/src/container/ts/export_test.rs +++ b/rs/moq-mux/src/container/ts/export_test.rs @@ -1085,7 +1085,7 @@ async fn export_trims_leading_pictures_after_a_late_drop() { (2080, 2060, false), (2120, 2120, false), ] { - kio::clock::sleep_until(start + Duration::from_millis(at)).await; + kio::clock::sleep_until(start.saturating_add(Duration::from_millis(at))).await; // Finding the source empty dates the next frame's arrival. out.extend(poll_frames(&mut export)); video @@ -1171,7 +1171,7 @@ async fn export_resumes_whole_mpeg2_video_at_a_sequence_header() { for (index, (at, pts, sequence)) in pictures.into_iter().enumerate() { // The audio arrives on time throughout, so only the video is late. while sample * AUDIO_US <= at * 1_000 { - kio::clock::sleep_until(start + Duration::from_micros(sample * AUDIO_US)).await; + kio::clock::sleep_until(start.saturating_add(Duration::from_micros(sample * AUDIO_US))).await; out.extend(poll_frames(&mut export)); audio .write(Frame { @@ -1183,7 +1183,7 @@ async fn export_resumes_whole_mpeg2_video_at_a_sequence_header() { .unwrap(); sample += 1; } - kio::clock::sleep_until(start + Duration::from_millis(at)).await; + kio::clock::sleep_until(start.saturating_add(Duration::from_millis(at))).await; out.extend(poll_frames(&mut export)); let mut payload = if sequence { vec![0, 0, 1, 0xb3] } else { Vec::new() }; payload.extend_from_slice(&[0, 0, 1, 0x00, index as u8]); @@ -5990,7 +5990,7 @@ impl Interleave { /// Run the paused clock to `micros` of media time, as a live source would. async fn at(&mut self, micros: u64) { let start = *self.start.get_or_insert_with(kio::clock::now); - kio::clock::sleep_until(start + Duration::from_micros(micros)).await; + kio::clock::sleep_until(start.saturating_add(Duration::from_micros(micros))).await; } fn video(&mut self, tick: u64) { @@ -8194,7 +8194,7 @@ async fn export_reordered( let mut b = None; let (mut out_a, mut out_b) = (Vec::new(), Vec::new()); for tick in 0..TICKS { - kio::clock::sleep_until(start + Duration::from_micros(tick * VIDEO_US)).await; + kio::clock::sleep_until(start.saturating_add(Duration::from_micros(tick * VIDEO_US))).await; if let Some((at, jitter)) = jitter && at == tick { @@ -8349,7 +8349,7 @@ async fn reordered_video_loses_nothing_on_a_clean_path() { let start = kio::clock::now(); let mut out = Vec::new(); for tick in 0..TICKS / 2 { - kio::clock::sleep_until(start + Duration::from_micros(tick * VIDEO_US)).await; + kio::clock::sleep_until(start.saturating_add(Duration::from_micros(tick * VIDEO_US))).await; rig.video(tick); while rig.audio_before(tick + 1) {} out.extend(poll_frames(&mut export)); @@ -8388,7 +8388,7 @@ async fn padded_video_needs_the_delay_its_hrd_declares() { let mut out = Vec::new(); let mut failed = None; 'run: for tick in 0..TICKS / 2 { - kio::clock::sleep_until(start + Duration::from_micros(tick * VIDEO_US)).await; + kio::clock::sleep_until(start.saturating_add(Duration::from_micros(tick * VIDEO_US))).await; rig.video(tick); while rig.audio_before(tick + 1) {} while let std::task::Poll::Ready(frame) = export.poll_next(&waiter) { @@ -8526,7 +8526,7 @@ async fn a_skipped_group_flags_the_clock() { let mut out = Vec::new(); // 100 ms groups of five 20 ms frames, a minute in, with two short or long holes. for sequence in 0..80 + 2 * missing { - kio::clock::sleep_until(start + Duration::from_millis(sequence * 100)).await; + kio::clock::sleep_until(start.saturating_add(Duration::from_millis(sequence * 100))).await; if !(20..20 + missing).contains(&sequence) && !(40 + missing..40 + 2 * missing).contains(&sequence) { let mut group = track.create_group(moq_net::group::Info { sequence }).unwrap(); for k in 0..5u64 { @@ -8660,7 +8660,7 @@ async fn a_timeline_restarting_at_zero_fails_the_export() { // One-second groups of 20 ms frames for 10 s, then a group back at zero. The track refuses // a group whose first frame rewinds, so that group opens at the previous start. for sequence in 0..11u64 { - kio::clock::sleep_until(start + Duration::from_secs(sequence)).await; + kio::clock::sleep_until(start.saturating_add(Duration::from_secs(sequence))).await; let base = if sequence < 10 { sequence * 1_000 } else { 0 }; let mut group = track.create_group(moq_net::group::Info { sequence }).unwrap(); for k in 0..50u64 { @@ -8701,7 +8701,7 @@ async fn a_late_join_starts_at_the_live_edge() { let mut out = Vec::new(); // One-second groups of 20 ms frames; the exporter joins 5.5 s in with a 2 s delay. for k in 0..400u64 { - kio::clock::sleep_until(start + Duration::from_millis(k * 20)).await; + kio::clock::sleep_until(start.saturating_add(Duration::from_millis(k * 20))).await; if k % 50 == 0 && k > 0 { audio.cut(None).unwrap(); } diff --git a/rs/moq-mux/src/container/ts/export_timing_test.rs b/rs/moq-mux/src/container/ts/export_timing_test.rs index 7a12cbb967d..05054a88923 100644 --- a/rs/moq-mux/src/container/ts/export_timing_test.rs +++ b/rs/moq-mux/src/container/ts/export_timing_test.rs @@ -189,7 +189,8 @@ impl Live { /// The receivers' instant at which the source's clock reads media time `micros`. fn sent(&self, micros: u64) -> Instant { - self.start + Duration::from_secs_f64(micros as f64 / 1e6 / self.scale) + self.start + .saturating_add(Duration::from_secs_f64(micros as f64 / 1e6 / self.scale)) } /// When the source sends the video frame of media time `video` and the audio frame of @@ -200,7 +201,7 @@ impl Live { true => (Duration::ZERO, lag), false => (lag, Duration::ZERO), }; - (self.sent(video) + v, self.sent(audio) + a) + (self.sent(video).saturating_add(v), self.sent(audio).saturating_add(a)) } /// Declare that video decodes up to `jitter` before it is presented, as a deep B-pyramid's @@ -233,7 +234,7 @@ impl Live { /// same timeline from the next group, as its replacement or the other half of a 1+1 pair /// would. fn fall_silent(&mut self, gap: Duration, legs: &mut [&mut Leg]) { - let resume = kio::clock::now() + gap; + let resume = kio::clock::now().saturating_add(gap); self.advance(resume, legs); let media = (resume.duration_since(self.start).as_secs_f64() * self.scale * 1e6) as u64; self.tick = media.div_ceil(VIDEO_US * GOP) * GOP; @@ -380,7 +381,7 @@ impl Live { assert!(!leg.poll(), "export ended while the broadcast is live"); if !leg.every.is_zero() { while leg.next_poll <= now { - leg.next_poll += leg.every; + leg.next_poll = leg.next_poll.saturating_add(leg.every); } } } diff --git a/rs/moq-mux/src/container/ts/follower.rs b/rs/moq-mux/src/container/ts/follower.rs index 2370f4a537d..286c0026c2d 100644 --- a/rs/moq-mux/src/container/ts/follower.rs +++ b/rs/moq-mux/src/container/ts/follower.rs @@ -200,7 +200,7 @@ impl Follower { self.following(&end); self.state = State::Settling { end, - deadline: kio::clock::now() + self.follow, + deadline: kio::clock::now().saturating_add(self.follow), }; } State::Settling { end, deadline } => { @@ -377,7 +377,7 @@ impl Follower { end: Err( anyhow::anyhow!("replacement broadcast `{}` ended before serving its catalog", self.path).into(), ), - deadline: kio::clock::now() + self.follow, + deadline: kio::clock::now().saturating_add(self.follow), }, } } diff --git a/rs/moq-mux/src/container/ts/health.rs b/rs/moq-mux/src/container/ts/health.rs index 99e790f92cd..6e0199eb777 100644 --- a/rs/moq-mux/src/container/ts/health.rs +++ b/rs/moq-mux/src/container/ts/health.rs @@ -1147,7 +1147,7 @@ mod test { health.packet( (&*feed.last_packet()).try_into().unwrap(), super::Continuation::Contiguous, - at(i + 1, start + std::time::Duration::from_millis(ms)), + at(i + 1, start.saturating_add(std::time::Duration::from_millis(ms))), ); health.flush(); } @@ -1331,7 +1331,10 @@ mod test { health.packet( (&*feed.last_packet()).try_into().unwrap(), super::Continuation::Broken, - at(count as u64 + 1, start + std::time::Duration::from_millis(ms)), + at( + count as u64 + 1, + start.saturating_add(std::time::Duration::from_millis(ms)), + ), ); health.flush(); } diff --git a/rs/moq-mux/src/container/ts/recovery_test.rs b/rs/moq-mux/src/container/ts/recovery_test.rs index a77becf2e72..829faa13f86 100644 --- a/rs/moq-mux/src/container/ts/recovery_test.rs +++ b/rs/moq-mux/src/container/ts/recovery_test.rs @@ -918,7 +918,7 @@ async fn run(recording: &Recording, arm: &Arm) -> Run { let mut open: Vec> = producers.iter().map(|_| None).collect(); let mut kept = vec![0; producers.len()]; for (at, event) in events { - kio::clock::sleep_until(start + at).await; + kio::clock::sleep_until(start.saturating_add(at)).await; let Some((t, g, step)) = event else { let snapshot = snapshot.clone(); catalog @@ -960,7 +960,7 @@ async fn run(recording: &Recording, arm: &Arm) -> Run { std::future::pending::<()>().await; }); - kio::clock::sleep_until(start + arm.join).await; + kio::clock::sleep_until(start.saturating_add(arm.join)).await; let source = crate::source::announced(&consumer).await; let mut export = open_ts(source, crate::catalog::CatalogFormat::Hang, DELAY) .await diff --git a/rs/moq-mux/src/container/ts/release_test.rs b/rs/moq-mux/src/container/ts/release_test.rs index dd8df163874..b6e9b941d7d 100644 --- a/rs/moq-mux/src/container/ts/release_test.rs +++ b/rs/moq-mux/src/container/ts/release_test.rs @@ -116,7 +116,7 @@ fn republish_cut( let mut due = Duration::ZERO; for (i, object) in objects.into_iter().enumerate() { due = due.max(at(i, &object)); - kio::clock::sleep_until(start + due).await; + kio::clock::sleep_until(start.saturating_add(due)).await; if group.as_ref().map(|(sequence, _)| *sequence) != Some(object.group) { if let Some((sequence, group)) = group.take() { end(sequence, group, &cut); diff --git a/rs/moq-mux/src/container/ts/revision_test.rs b/rs/moq-mux/src/container/ts/revision_test.rs index eeaf1a804e0..b861c62bee5 100644 --- a/rs/moq-mux/src/container/ts/revision_test.rs +++ b/rs/moq-mux/src/container/ts/revision_test.rs @@ -1385,7 +1385,7 @@ async fn a_pmt_moved_while_its_tables_go_out_moves_behind_them() { let start = kio::clock::now(); let mut export = export_of(&consumer).await.with_mux_rate(rate(4)); for millis in (0..6_000).step_by(50) { - kio::clock::sleep_until(start + Duration::from_millis(millis)).await; + kio::clock::sleep_until(start.saturating_add(Duration::from_millis(millis))).await; match millis { // Three packets of PMT from here, in slots of four. 2_500 => { @@ -1496,7 +1496,7 @@ async fn a_revision_out_before_the_one_it_follows_takes_its_version() { ); let (_, mut added) = aac_track(&mut broadcast, &mut catalog, Some(OTHER_AUDIO_PID)); settle(&mut export, &mut frames).await; - kio::clock::sleep_until(start + Duration::from_millis(3_000)).await; + kio::clock::sleep_until(start.saturating_add(Duration::from_millis(3_000))).await; cue.write(Frame { timestamp: moq_net::Timestamp::from_millis(3_000).unwrap(), duration: None, @@ -1578,7 +1578,7 @@ async fn a_stream_taking_a_pid_over_leaves_the_buffer_before_it() { crate::catalog::hang::Container::Legacy(crate::container::Kind::Data), ); settle(&mut export, &mut frames).await; - kio::clock::sleep_until(start + Duration::from_millis(6_000)).await; + kio::clock::sleep_until(start.saturating_add(Duration::from_millis(6_000))).await; let mut section = vec![0x80, 0x7f, 0xfd]; section.resize(4_096, 0xab); private @@ -1721,7 +1721,7 @@ async fn live( S::Ext: super::catalog::Catalog, { for millis in (from..to).step_by(20) { - kio::clock::sleep_until(start + Duration::from_millis(millis)).await; + kio::clock::sleep_until(start.saturating_add(Duration::from_millis(millis))).await; for (track, mark) in tracks.iter_mut() { write_marked(track, millis, *mark); } @@ -1763,7 +1763,7 @@ async fn the_clock_moves_behind_the_last_packet_of_the_pmt_naming_its_pid() { // Frames 50 ms apart, for room beside the tables; the second track's from 500 ms, for room // beside the first tables. for millis in (0..6_000).step_by(50) { - kio::clock::sleep_until(start + Duration::from_millis(millis)).await; + kio::clock::sleep_until(start.saturating_add(Duration::from_millis(millis))).await; match millis { ..3_000 => write_marked(&mut clock, millis, 0x21), // The revision moving the clock lays three packets of PMT, in slots of four. diff --git a/rs/moq-mux/src/jitter.rs b/rs/moq-mux/src/jitter.rs index ce31dceaf11..ab66b4ba5b8 100644 --- a/rs/moq-mux/src/jitter.rs +++ b/rs/moq-mux/src/jitter.rs @@ -641,12 +641,12 @@ impl Acquire { let (_, fresh) = self.fresh(); let due = |frame: &Arrival| { let ahead = frame.decode.as_nanos() - fresh.decode.as_nanos(); - offset(fresh.read + delay, ahead) + offset(fresh.read.saturating_add(delay), ahead) }; self.frames .iter() .filter_map(|(_, frame)| due(frame).filter(|due| *due >= frame.read)) - .chain([self.since + delay]) + .chain([self.since.saturating_add(delay)]) .min() .expect("a bound") } @@ -984,7 +984,7 @@ impl Engine { let mut clock = Clock { generation: acquire.generation, anchor: match acquiring { - true => fresh.read + self.unheard_lag(&acquire, key), + true => fresh.read.saturating_add(self.unheard_lag(&acquire, key)), false => fresh.arrived, }, base: fresh.decode, @@ -1002,7 +1002,7 @@ impl Engine { if let (Some(horizon), Some(kept)) = (self.horizon, kept) && kept < horizon { - clock.anchor += horizon - kept; + clock.anchor = clock.anchor.saturating_add(horizon - kept); } // Admission needs each track's lead before the first steering window completes. for (key, frame) in acquire.freshest() { @@ -1117,7 +1117,10 @@ impl Engine { /// leaves only theirs queued, its next frame is not taken for a leap. fn bound(&self, key: &K, arrived: Instant) -> Instant { let lead = Duration::from_secs_f64(self.lead(key).unwrap_or(0.0).max(0.0)); - arrived.max(self.horizon.unwrap_or(arrived)) + self.delay + lead + arrived + .max(self.horizon.unwrap_or(arrived)) + .saturating_add(self.delay) + .saturating_add(lead) } /// Account for the slack a frame arrived with, and every [`STEER`] of our time step the @@ -1349,7 +1352,7 @@ impl Engine { fn ends(&self, acquire: &Acquire) -> Instant { match self.heard(acquire) { true => acquire.end(self.delay), - false => acquire.since + 2 * self.delay, + false => acquire.since.saturating_add(2 * self.delay), } } @@ -1704,7 +1707,10 @@ mod tests { assert_eq!(held.item, "B"); buffer.cancel(); assert_eq!(buffer.reporting().dropped(), 2); - assert_eq!(buffer.at(0, ms(200)), Some(start + delay + Duration::from_millis(200))); + assert_eq!( + buffer.at(0, ms(200)), + Some(start.saturating_add(delay).saturating_add(Duration::from_millis(200))) + ); buffer.push(0, arrival(kio::clock::now(), 200, "A resumed")).unwrap(); buffer.start([2], [2]); buffer.push(2, arrival(kio::clock::now(), 20_000, "C")).unwrap(); @@ -1786,7 +1792,7 @@ mod tests { let mut buffer = Buffer::new(DELAY).replay(); // A's clock runs a millisecond behind B's, so B shifts behind A's last frame out. buffer - .push(0u16, arrival(start + Duration::from_millis(1), 0, "A")) + .push(0u16, arrival(start.saturating_add(Duration::from_millis(1)), 0, "A")) .unwrap(); buffer.start([1], [1]); buffer.push(1, arrival(start, 0, "B first")).unwrap(); @@ -1895,9 +1901,9 @@ mod tests { .unwrap(); assert_eq!( buffer.at(0, before_zero), - Some(start + DELAY - Duration::from_nanos(22_223)) + Some(start.saturating_add(DELAY).saturating_sub(Duration::from_nanos(22_223))) ); - assert_eq!(buffer.at(0, ms(0)), Some(start + DELAY)); + assert_eq!(buffer.at(0, ms(0)), Some(start.saturating_add(DELAY))); kio::clock::sleep(DELAY).await; assert_eq!(due(&mut buffer), ["video", "audio"]); } @@ -2023,7 +2029,10 @@ mod tests { } } assert!(due(&mut buffer).is_empty()); - assert_eq!(buffer.at(0, ms(800)), Some(start + Duration::from_millis(500))); + assert_eq!( + buffer.at(0, ms(800)), + Some(start.saturating_add(Duration::from_millis(500))) + ); tokio::time::advance(Duration::from_millis(500)).await; let first = buffer.poll_next(&kio::Waiter::noop()); assert!( @@ -2042,13 +2051,13 @@ mod tests { // Audio arrives later than the video, with an earlier decode time. assert_eq!( buffer - .push(2, arrival(start + Duration::from_millis(30), 20, "a20")) + .push(2, arrival(start.saturating_add(Duration::from_millis(30)), 20, "a20")) .unwrap(), Push::Queued ); assert_eq!( buffer - .push(2, arrival(start + Duration::from_millis(30), 40, "a40")) + .push(2, arrival(start.saturating_add(Duration::from_millis(30)), 40, "a40")) .unwrap(), Push::Queued ); @@ -2068,7 +2077,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn the_margin_is_the_least_spare_over_a_second() { let start = Instant::now(); - let at = |ms: u64| start + Duration::from_millis(ms); + let at = |ms: u64| start.saturating_add(Duration::from_millis(ms)); let mut buffer = Buffer::new(DELAY).replay(); assert_eq!(buffer.push(1, arrival(at(0), 0, "v0")).unwrap(), Push::Queued); assert_eq!(buffer.push(1, arrival(at(30), 40, "v40")).unwrap(), Push::Queued); @@ -2115,11 +2124,14 @@ mod tests { let skew = if key == 2 { 90 } else { 0 }; assert_eq!( early - .push(key, arrival(start + Duration::from_millis(decode), decode, item)) + .push( + key, + arrival(start.saturating_add(Duration::from_millis(decode)), decode, item) + ) .unwrap(), Push::Queued ); - let arrived = start + Duration::from_millis(decode + skew); + let arrived = start.saturating_add(Duration::from_millis(decode + skew)); assert_eq!(late.push(key, arrival(arrived, decode, item)).unwrap(), Push::Queued); } tokio::time::advance(Duration::from_secs(1)).await; @@ -2138,7 +2150,7 @@ mod tests { buffer.push(2, arrival(start, 0, "a0")).unwrap(); tokio::time::advance(DELAY).await; assert_eq!(due(&mut buffer), ["v0", "a0"]); - let late = start + Duration::from_millis(200); + let late = start.saturating_add(Duration::from_millis(200)); let video = |decode, sync, item| Arrival { sync, ..arrival(late, decode, item) @@ -2168,7 +2180,7 @@ mod tests { buffer.push(1, video(start, 0, true, false, "v0")).unwrap(); tokio::time::advance(DELAY).await; assert_eq!(due(&mut buffer), ["v0"]); - let late = start + Duration::from_millis(200); + let late = start.saturating_add(Duration::from_millis(200)); assert_eq!( buffer.push(1, video(late, 40, false, false, "v40")).unwrap(), Push::Late @@ -2208,7 +2220,7 @@ mod tests { buffer.push(1, arrival(start, 0, "v0")).unwrap(); buffer.push(2, arrival(start, 900, "a900")).unwrap(); // The video consumer skips to the live group. - let skip = start + Duration::from_millis(5); + let skip = start.saturating_add(Duration::from_millis(5)); assert_eq!( buffer.push(1, after(1, arrival(skip, 900, "v900"))).unwrap(), Push::Queued @@ -2297,14 +2309,14 @@ mod tests { assert_eq!(due(&mut buffer), ["v0", "a0", "d0"]); // The publisher resumes a second later with its timeline five seconds on. - let resume = start + Duration::from_secs(1); + let resume = start.saturating_add(Duration::from_secs(1)); tokio::time::advance(resume - kio::clock::now()).await; assert_eq!( buffer.push(1, after(1, arrival(resume, 5_000, "v5000"))).unwrap(), Push::Queued ); // The audio crosses no restart of its own; the data crosses the same one. - let late = resume + Duration::from_millis(10); + let late = resume.saturating_add(Duration::from_millis(10)); assert_eq!(buffer.push(2, arrival(late, 5_000, "a5000")).unwrap(), Push::Queued); assert_eq!( buffer.push(3, after(1, arrival(late, 5_000, "d5000"))).unwrap(), @@ -2334,20 +2346,20 @@ mod tests { // The publisher resumes a second later with its timeline five seconds on, and sends // the audio further behind the video than the delay. - let resume = start + Duration::from_secs(1); + let resume = start.saturating_add(Duration::from_secs(1)); tokio::time::advance(resume - kio::clock::now()).await; assert_eq!( buffer.push(1, after(1, arrival(resume, 5_000, "v5000"))).unwrap(), Push::Queued ); - let lag = resume + DELAY + Duration::from_millis(50); + let lag = resume.saturating_add(DELAY).saturating_add(Duration::from_millis(50)); tokio::time::advance(lag - kio::clock::now()).await; assert_eq!(buffer.push(2, arrival(lag, 5_000, "a5000")).unwrap(), Push::Queued); tokio::time::advance(Duration::from_millis(20)).await; let next = kio::clock::now(); assert_eq!(buffer.push(2, arrival(next, 5_020, "a5020")).unwrap(), Push::Queued); - tokio::time::advance(lag + DELAY - kio::clock::now()).await; + tokio::time::advance(lag.saturating_add(DELAY) - kio::clock::now()).await; assert_eq!(released(&mut buffer), [("v5000", 1), ("a5000", 1)]); tokio::time::advance(Duration::from_millis(20)).await; assert_eq!(released(&mut buffer), [("a5020", 1)]); @@ -2369,7 +2381,7 @@ mod tests { assert_eq!(released(&mut buffer), [("v300", 0)]); assert!(buffer.is_empty()); - let resume = start + Duration::from_secs(1); + let resume = start.saturating_add(Duration::from_secs(1)); tokio::time::advance(resume - kio::clock::now()).await; buffer.push(1, after(1, arrival(resume, 5_000, "v5000"))).unwrap(); tokio::time::advance(DELAY).await; @@ -2410,7 +2422,7 @@ mod tests { } tokio::time::advance(DELAY).await; assert!(due(&mut buffer).is_empty()); - let tail = start + Duration::from_millis(500); + let tail = start.saturating_add(Duration::from_millis(500)); assert_eq!( buffer.at(1, ms(5_000)), Some(tail), @@ -2456,7 +2468,7 @@ mod tests { let mut out = Vec::new(); for (read, key, restart, decode) in frames { - let at = start + Duration::from_millis(read); + let at = start.saturating_add(Duration::from_millis(read)); tokio::time::advance(at - kio::clock::now()).await; out.extend(released(&mut buffer).into_iter().map(|(_, generation)| generation)); buffer.push(key, after(restart, arrival(at, decode, "frame"))).unwrap(); @@ -2503,7 +2515,7 @@ mod tests { tokio::time::advance(DELAY).await; assert_eq!(due(&mut buffer), ["v", "d"]); - let resume = start + Duration::from_secs(1); + let resume = start.saturating_add(Duration::from_secs(1)); tokio::time::advance(resume - kio::clock::now()).await; buffer.push(1, after(1, arrival(resume, to, "v'"))).unwrap(); tokio::time::advance(DELAY).await; @@ -2539,7 +2551,7 @@ mod tests { assert_eq!(due(&mut buffer), ["a0"]); // Group 1 is skipped: frames from 100 ms on arrive after a 250 ms stall. - let stalled = start + Duration::from_millis(350); + let stalled = start.saturating_add(Duration::from_millis(350)); tokio::time::advance(stalled - kio::clock::now()).await; assert_eq!(buffer.push(1, arrival(stalled, 200, "a200")).unwrap(), Push::Late); assert_eq!(buffer.push(1, arrival(stalled, 300, "a300")).unwrap(), Push::Queued); @@ -2577,7 +2589,7 @@ mod tests { assert_eq!(released(&mut buffer), [("a0", 0)]); // A second on, past a skipped group, the next frame is 20 ms less queued than the first. - let resume = start + Duration::from_secs(1); + let resume = start.saturating_add(Duration::from_secs(1)); tokio::time::advance(resume - kio::clock::now()).await; assert_eq!(buffer.push(1, arrival(resume, 1_020, "a1020")).unwrap(), Push::Queued); tokio::time::advance(Duration::from_secs(1)).await; @@ -2595,7 +2607,7 @@ mod tests { buffer.expect([1, 2]); let mut out = Vec::new(); for at in (0..12_000).step_by(40) { - tokio::time::advance(start + Duration::from_millis(at) - kio::clock::now()).await; + tokio::time::advance(start.saturating_add(Duration::from_millis(at)) - kio::clock::now()).await; let now = kio::clock::now(); assert_eq!(buffer.push(1, arrival(now, at, "v")).unwrap(), Push::Queued); // Track 2 is sent LEAD ahead, and skips a second of its own. @@ -2697,7 +2709,9 @@ mod tests { run.clock_before = buffer.clock.map_or(0.0, |clock| clock.drift); } let source = decode.as_secs_f64() * (1.0 + ppm * 1e-6); - let arrived = start + Duration::from_secs_f64(source) + queued; + let arrived = start + .saturating_add(Duration::from_secs_f64(source)) + .saturating_add(queued); clock.advance(arrived.max(clock.now())); let frame = Arrival { arrived, @@ -2885,7 +2899,7 @@ mod tests { }; let waiter = kio::Waiter::noop(); for (sent, track, decode) in frames { - let arrived = start + Duration::from_secs_f64(sent); + let arrived = start.saturating_add(Duration::from_secs_f64(sent)); clock.advance(arrived.max(clock.now())); let frame = Arrival { arrived, @@ -3019,7 +3033,7 @@ mod tests { for k in 0..(secs * 10.0) as u64 { let sent = k as f64 / 10.0; let jitter = ((k / 20) * 3) % 5; - let arrived = start + Duration::from_secs_f64(sent + jitter as f64 * 0.002); + let arrived = start.saturating_add(Duration::from_secs_f64(sent + jitter as f64 * 0.002)); clock.advance(arrived.max(clock.now())); if sent < at { stepped.before = buffer.clock.map_or(0.0, |clock| clock.drift); @@ -3205,12 +3219,12 @@ mod tests { buffer.push(1, video(start, decode, false, item)).unwrap(); } tokio::time::advance(Duration::from_millis(40)).await; - let next = start + Duration::from_millis(40); + let next = start.saturating_add(Duration::from_millis(40)); buffer.push(1, video(next, 240, true, "v240")).unwrap(); buffer.push(1, video(next, 280, false, "v280")).unwrap(); assert!(due(&mut buffer).is_empty()); // Both frames were available together: v280, not its group's v240, is freshest. - assert_eq!(buffer.next_deadline(), Some(start + DELAY)); + assert_eq!(buffer.next_deadline(), Some(start.saturating_add(DELAY))); tokio::time::advance(Duration::from_millis(60)).await; assert_eq!(due(&mut buffer), ["v240"]); tokio::time::advance(Duration::from_millis(40)).await; @@ -3294,7 +3308,7 @@ mod tests { }; buffer.push(1, video(start, 0, true, "v0")).unwrap(); tokio::time::advance(Duration::from_millis(250)).await; - let later = start + Duration::from_millis(250); + let later = start.saturating_add(Duration::from_millis(250)); for (decode, sync, item) in [(40, false, "v40"), (80, false, "v80"), (400, true, "v400")] { buffer.push(1, video(later, decode, sync, item)).unwrap(); } @@ -3315,11 +3329,14 @@ mod tests { buffer.push(1, arrival(start, 300, "v300")).unwrap(); tokio::time::advance(Duration::from_millis(20)).await; buffer - .push(2, arrival(start + Duration::from_millis(20), 20, "a20")) + .push(2, arrival(start.saturating_add(Duration::from_millis(20)), 20, "a20")) .unwrap(); tokio::time::advance(Duration::from_millis(100)).await; assert_eq!(due(&mut buffer), ["a20"], "the audio keeps the delay"); - assert_eq!(buffer.next_deadline(), Some(start + Duration::from_millis(400))); + assert_eq!( + buffer.next_deadline(), + Some(start.saturating_add(Duration::from_millis(400))) + ); assert!( !buffer.full(&1, &kio::Waiter::noop()), "acquisition measures the video lead before steering starts" @@ -3335,7 +3352,7 @@ mod tests { let mut buffer = Buffer::new(DELAY); buffer.expect([1, 2]); buffer.push(1, arrival(start, 0, "v0")).unwrap(); - assert_eq!(buffer.next_deadline(), Some(start + 2 * DELAY)); + assert_eq!(buffer.next_deadline(), Some(start.saturating_add(2 * DELAY))); tokio::time::advance(2 * DELAY).await; assert_eq!(due(&mut buffer), ["v0"]); } @@ -3350,7 +3367,12 @@ mod tests { let mut buffer = Buffer::new(DELAY).replay(); buffer.push(1, arrival(start, 0, "v0")).unwrap(); buffer.push(first.0, arrival(start, 100, first.1)).unwrap(); - buffer.clock.as_mut().unwrap().anchor += Duration::from_nanos(1); + buffer.clock.as_mut().unwrap().anchor = buffer + .clock + .as_mut() + .unwrap() + .anchor + .saturating_add(Duration::from_nanos(1)); buffer.push(second.0, arrival(start, 100, second.1)).unwrap(); buffer }; @@ -3382,7 +3404,10 @@ mod tests { }, ) .unwrap(); - assert_eq!(buffer.next_deadline(), Some(start + Duration::from_millis(40))); + assert_eq!( + buffer.next_deadline(), + Some(start.saturating_add(Duration::from_millis(40))) + ); tokio::time::advance(Duration::from_millis(40)).await; assert_eq!(due(&mut buffer), ["v0"]); } @@ -3398,7 +3423,7 @@ mod tests { buffer.push(2, arrival(start, 20, "a20")).unwrap(); assert_eq!(due(&mut buffer), ["v0", "a20", "v40"]); - let late = start + Duration::from_secs(1); + let late = start.saturating_add(Duration::from_secs(1)); assert_eq!(buffer.push(2, arrival(late, 40, "a40")).unwrap(), Push::Queued); assert_eq!(due(&mut buffer), ["a40"]); assert_eq!(buffer.dropped(), 0); @@ -3461,7 +3486,7 @@ mod tests { let mut next = [0, 0]; let mut peak = 0; for step in 0..6_000 { - let at = start + Duration::from_millis(step * 20); + let at = start.saturating_add(Duration::from_millis(step * 20)); tokio::time::advance(at.saturating_duration_since(kio::clock::now())).await; for (key, speed) in [(0, 1), (1, 3)] { while next[key] <= step * 20 * speed && !buffer.full(&(key as u16), &kio::Waiter::noop()) { @@ -3498,7 +3523,7 @@ mod tests { } }) .await; - assert_eq!(reopened, start + Duration::from_millis(1_500)); + assert_eq!(reopened, start.saturating_add(Duration::from_millis(1_500))); } /// A frame of `bytes` against the byte budget. @@ -3542,7 +3567,7 @@ mod tests { let mut honest = 0; let mut peak = 0; for step in 0..500u64 { - let at = start + Duration::from_millis(step * 20); + let at = start.saturating_add(Duration::from_millis(step * 20)); tokio::time::advance(at.saturating_duration_since(kio::clock::now())).await; while honest <= step * 20 && !buffer.full(&0, &kio::Waiter::noop()) { buffer.push(0, sized(at, honest, 100)).unwrap(); diff --git a/rs/moq-mux/src/pace.rs b/rs/moq-mux/src/pace.rs index 2ac863de442..70e4e3783d4 100644 --- a/rs/moq-mux/src/pace.rs +++ b/rs/moq-mux/src/pace.rs @@ -148,9 +148,9 @@ impl Pacer { } self.slack += shift; if let Some((anchor, _)) = self.anchor.as_mut() { - *anchor += shift; + *anchor = anchor.saturating_add(shift); } - at + shift + at.saturating_add(shift) } /// How much of the producer's standing delivery lag the anchor has absorbed. @@ -212,31 +212,31 @@ mod tests { // Tune-in burst: the live edge (4132ms of media) is produced ~8ms after the // first frame (1400ms). It must re-anchor to `now` rather than schedule // ~2.7s into the future. - let start = Instant::ZERO + Duration::from_secs(1); + let start = Instant::ZERO.saturating_add(Duration::from_secs(1)); let mut pacer = Pacer::default(); assert_eq!(pacer.pace(ms(1_400), start), start, "the first frame anchors at now"); - let now = start + Duration::from_millis(8); + let now = start.saturating_add(Duration::from_millis(8)); assert_eq!(pacer.pace(ms(4_132), now), now, "the live edge paces to now"); // The re-anchor moved the base up to the live edge (4132ms <-> now). A frame // 33ms newer in MEDIA that arrives 80ms later in WALL-clock (jitter) paces // from that carried-forward anchor: its media instant (+33ms off the edge), // not its 80ms arrival instant. - let jittered = pacer.pace(ms(4_165), now + Duration::from_millis(80)); + let jittered = pacer.pace(ms(4_165), now.saturating_add(Duration::from_millis(80))); assert_eq!( jittered, - now + Duration::from_millis(33), + now.saturating_add(Duration::from_millis(33)), "a late frame keeps its media instant, not its arrival instant" ); // A reordered B-frame can carry a timestamp before the re-anchored live // edge. Keep that earlier media instant instead of flattening it onto the // anchor. - let reordered = pacer.pace(ms(4_099), now + Duration::from_millis(100)); + let reordered = pacer.pace(ms(4_099), now.saturating_add(Duration::from_millis(100))); assert_eq!( reordered, - now - Duration::from_millis(33), + now.saturating_sub(Duration::from_millis(33)), "a reordered frame can pace before the anchor" ); } @@ -256,10 +256,16 @@ mod tests { // A media frame 40ms later at 90 kHz (3600 ticks) paces on the same clock. let media = Timestamp::from_scale(3_600, 90_000).unwrap(); - assert_eq!(pacer.pace(media, start), start + Duration::from_millis(40)); + assert_eq!( + pacer.pace(media, start), + start.saturating_add(Duration::from_millis(40)) + ); // The next PCR slot, back at microsecond scale, lands on its own boundary. - assert_eq!(pacer.pace(ms(50), start), start + Duration::from_millis(50)); + assert_eq!( + pacer.pace(ms(50), start), + start.saturating_add(Duration::from_millis(50)) + ); } /// Regression: the lead comparison must not construct `now + lead`, which @@ -269,7 +275,10 @@ mod tests { let start = kio::clock::now(); let mut pacer = Pacer::default().with_lead(Duration::MAX); assert_eq!(pacer.pace(ms(0), start), start); - assert_eq!(pacer.pace(ms(40), start), start + Duration::from_millis(40)); + assert_eq!( + pacer.pace(ms(40), start), + start.saturating_add(Duration::from_millis(40)) + ); } /// A producer that delivers a constant distance behind the media clock (the TS @@ -284,13 +293,13 @@ mod tests { assert_eq!(pacer.pace(ms(0), start), start, "the first frame anchors at now"); // Steady state: the producer is 40ms behind, so this frame is already due. - let now = start + Duration::from_millis(80); + let now = start.saturating_add(Duration::from_millis(80)); assert_eq!(pacer.pace(ms(40), now), now, "a late frame still goes out at once"); // The anchor absorbed those 40ms, so the next frame has room to be paced. assert_eq!( pacer.pace(ms(80), now), - now + Duration::from_millis(40), + now.saturating_add(Duration::from_millis(40)), "the discovered lag becomes the sink's margin" ); } @@ -304,11 +313,11 @@ mod tests { assert_eq!(pacer.pace(ms(0), start), start); // 200ms behind, but only 50ms of that may be taken. - let now = start + Duration::from_millis(240); - assert_eq!(pacer.pace(ms(40), now), start + Duration::from_millis(90)); + let now = start.saturating_add(Duration::from_millis(240)); + assert_eq!(pacer.pace(ms(40), now), start.saturating_add(Duration::from_millis(90))); assert_eq!( pacer.pace(ms(80), now), - start + Duration::from_millis(130), + start.saturating_add(Duration::from_millis(130)), "the anchor moved by the cap, not by the shortfall" ); } @@ -320,9 +329,9 @@ mod tests { let mut pacer = Pacer::default(); assert_eq!(pacer.pace(ms(0), start), start); - let now = start + Duration::from_millis(80); - assert_eq!(pacer.pace(ms(40), now), start + Duration::from_millis(40)); - assert_eq!(pacer.pace(ms(80), now), start + Duration::from_millis(80)); + let now = start.saturating_add(Duration::from_millis(80)); + assert_eq!(pacer.pace(ms(40), now), start.saturating_add(Duration::from_millis(40))); + assert_eq!(pacer.pace(ms(80), now), start.saturating_add(Duration::from_millis(80))); } #[test] @@ -333,9 +342,9 @@ mod tests { // A caller's stricter lag detection can force the re-anchor `pace` alone // would not apply: the frame goes out at `now` and becomes the new base. - let now = start + Duration::from_millis(100); + let now = start.saturating_add(Duration::from_millis(100)); assert_eq!(pacer.hurry(ms(800), now), now); - assert_eq!(pacer.pace(ms(840), now), now + Duration::from_millis(40)); + assert_eq!(pacer.pace(ms(840), now), now.saturating_add(Duration::from_millis(40))); } /// The delay shifts the schedule without entering the anchor, so the frame @@ -346,14 +355,23 @@ mod tests { let start = kio::clock::now(); let mut pacer = Pacer::default().with_delay(Duration::from_millis(100)); - assert_eq!(pacer.pace(ms(0), start), start + Duration::from_millis(100)); + assert_eq!( + pacer.pace(ms(0), start), + start.saturating_add(Duration::from_millis(100)) + ); // 40ms of media arriving 40ms later: on the anchor, so it must not re-anchor. - let now = start + Duration::from_millis(40); - assert_eq!(pacer.pace(ms(40), now), start + Duration::from_millis(140)); + let now = start.saturating_add(Duration::from_millis(40)); + assert_eq!( + pacer.pace(ms(40), now), + start.saturating_add(Duration::from_millis(140)) + ); // And another 40ms on, still on the original anchor rather than a re-anchor // the delay provoked. - let now = start + Duration::from_millis(80); - assert_eq!(pacer.pace(ms(80), now), start + Duration::from_millis(180)); + let now = start.saturating_add(Duration::from_millis(80)); + assert_eq!( + pacer.pace(ms(80), now), + start.saturating_add(Duration::from_millis(180)) + ); } /// The headline player defect: a first frame that arrives late pins the delay @@ -365,19 +383,22 @@ mod tests { let mut pacer = Pacer::default().with_delay(Duration::from_millis(100)); // The first frame was produced 500ms ago; nothing here knows that yet. - assert_eq!(pacer.pace(ms(0), start), start + Duration::from_millis(100)); + assert_eq!( + pacer.pace(ms(0), start), + start.saturating_add(Duration::from_millis(100)) + ); // 40ms of media later, but the next frame took only 20ms to arrive, so the // anchor is 480ms behind live. Re-anchor onto it, delay intact. - let now = start + Duration::from_millis(20); - assert_eq!(pacer.pace(ms(40), now), now + Duration::from_millis(100)); + let now = start.saturating_add(Duration::from_millis(20)); + assert_eq!(pacer.pace(ms(40), now), now.saturating_add(Duration::from_millis(100))); // A frame that merely arrives late keeps its media instant instead: the // delay is exactly the room it has to be late in. - let late = now + Duration::from_millis(70); + let late = now.saturating_add(Duration::from_millis(70)); assert_eq!( pacer.pace(ms(80), late), - now + Duration::from_millis(140), + now.saturating_add(Duration::from_millis(140)), "a late arrival must not re-anchor" ); } @@ -388,10 +409,16 @@ mod tests { fn hurry_keeps_the_delay() { let start = kio::clock::now(); let mut pacer = Pacer::default().with_delay(Duration::from_millis(100)); - assert_eq!(pacer.hurry(ms(800), start), start + Duration::from_millis(100)); + assert_eq!( + pacer.hurry(ms(800), start), + start.saturating_add(Duration::from_millis(100)) + ); - let now = start + Duration::from_millis(40); - assert_eq!(pacer.pace(ms(840), now), start + Duration::from_millis(140)); + let now = start.saturating_add(Duration::from_millis(40)); + assert_eq!( + pacer.pace(ms(840), now), + start.saturating_add(Duration::from_millis(140)) + ); } /// A player queues frames on arrival and asks again when it presents them, by @@ -404,13 +431,19 @@ mod tests { assert_eq!(pacer.due(ms(0)), None, "no anchor until the first frame"); pacer.pace(ms(0), start); - assert_eq!(pacer.due(ms(40)), Some(start + Duration::from_millis(140))); - assert_eq!(pacer.due(ms(40)), Some(start + Duration::from_millis(140))); + assert_eq!( + pacer.due(ms(40)), + Some(start.saturating_add(Duration::from_millis(140))) + ); + assert_eq!( + pacer.due(ms(40)), + Some(start.saturating_add(Duration::from_millis(140))) + ); // Another track re-anchors, and the queued frame is due earlier for it. - let now = start + Duration::from_millis(10); + let now = start.saturating_add(Duration::from_millis(10)); pacer.hurry(ms(20), now); - assert_eq!(pacer.due(ms(40)), Some(now + Duration::from_millis(120))); + assert_eq!(pacer.due(ms(40)), Some(now.saturating_add(Duration::from_millis(120)))); } #[test] @@ -420,12 +453,21 @@ mod tests { assert_eq!(pacer.pace(ms(0), start), start); // An arrival burst within the lead window is spaced, not re-anchored. - assert_eq!(pacer.pace(ms(40), start), start + Duration::from_millis(40)); - assert_eq!(pacer.pace(ms(500), start), start + Duration::from_millis(500)); + assert_eq!( + pacer.pace(ms(40), start), + start.saturating_add(Duration::from_millis(40)) + ); + assert_eq!( + pacer.pace(ms(500), start), + start.saturating_add(Duration::from_millis(500)) + ); // One step beyond the lead is a discontinuity: re-anchor to now. assert_eq!(pacer.pace(ms(1_200), start), start); // And later frames pace off the new anchor. - assert_eq!(pacer.pace(ms(1_240), start), start + Duration::from_millis(40)); + assert_eq!( + pacer.pace(ms(1_240), start), + start.saturating_add(Duration::from_millis(40)) + ); } } diff --git a/rs/moq-mux/src/rate.rs b/rs/moq-mux/src/rate.rs index 75ede7cdca4..d25993fd5e2 100644 --- a/rs/moq-mux/src/rate.rs +++ b/rs/moq-mux/src/rate.rs @@ -583,7 +583,7 @@ mod tests { // Losing the estimate (disconnected) is not evidence the uplink is // healthy again, so the target must not jump back to max. - assert_eq!(control.update(None, now + Duration::from_secs(10)), None); + assert_eq!(control.update(None, now.saturating_add(Duration::from_secs(10))), None); assert_eq!(control.target(), on(bps(2_000_000))); } @@ -612,7 +612,7 @@ mod tests { // The pipe reopens to 4 Mbps. One second later the default 25%/s ramp // allows only 1M -> 1.25M, not the full 4 Mbps the estimate wants. let raised = control - .update(Some(bps(4_000_000)), start + Duration::from_secs(1)) + .update(Some(bps(4_000_000)), start.saturating_add(Duration::from_secs(1))) .unwrap(); assert_eq!(raised, on(bps(1_250_000))); } @@ -631,7 +631,10 @@ mod tests { // Tick at 100ms: each tick alone is under the 5% threshold. let mut raised = None; for tick in 1..=10 { - if let Some(next) = control.update(Some(bps(4_000_000)), start + Duration::from_millis(100 * tick)) { + if let Some(next) = control.update( + Some(bps(4_000_000)), + start.saturating_add(Duration::from_millis(100 * tick)), + ) { raised = Some((tick, next)); break; } @@ -657,7 +660,10 @@ mod tests { // Walk up until it settles, then confirm where it settled. let mut last = None; for tick in 1..=200 { - if let Some(next) = control.update(Some(bps(4_000_000)), start + Duration::from_millis(100 * tick)) { + if let Some(next) = control.update( + Some(bps(4_000_000)), + start.saturating_add(Duration::from_millis(100 * tick)), + ) { last = Some(next); } } @@ -665,7 +671,7 @@ mod tests { assert_eq!(last, Some(on(bps(4_000_000)))); // And it stops there rather than reapplying the same value forever. assert_eq!( - control.update(Some(bps(4_000_000)), start + Duration::from_secs(60)), + control.update(Some(bps(4_000_000)), start.saturating_add(Duration::from_secs(60))), None ); } @@ -682,7 +688,7 @@ mod tests { // A 0.5% rise: inside the 5% deadband, and nowhere near the ceiling. assert_eq!( - control.update(Some(bps(2_010_000)), start + Duration::from_millis(100)), + control.update(Some(bps(2_010_000)), start.saturating_add(Duration::from_millis(100))), None ); @@ -691,7 +697,10 @@ mod tests { for tick in 2..=9 { let estimate = 2_000_000 + tick * 10_000; assert_eq!( - control.update(Some(bps(estimate)), start + Duration::from_millis(100 * tick)), + control.update( + Some(bps(estimate)), + start.saturating_add(Duration::from_millis(100 * tick)) + ), None, "estimate {estimate} is inside the deadband" ); @@ -701,7 +710,7 @@ mod tests { // And the deadband is still only a deadband: once the estimate does clear it, // the raise lands normally, without needing the ceiling exemption. assert_eq!( - control.update(Some(bps(2_200_000)), start + Duration::from_secs(2)), + control.update(Some(bps(2_200_000)), start.saturating_add(Duration::from_secs(2))), Some(on(bps(2_200_000))) ); } @@ -713,12 +722,15 @@ mod tests { control.update(Some(bps(2_000_000)), now).unwrap(); // target 2M // 2% under the current target: inside the 5% deadband, so no reconfigure. - assert_eq!(control.update(Some(bps(1_960_000)), now + Duration::from_secs(1)), None); + assert_eq!( + control.update(Some(bps(1_960_000)), now.saturating_add(Duration::from_secs(1))), + None + ); assert_eq!(control.target(), on(bps(2_000_000))); // 20% under: outside the deadband, so it applies. assert_eq!( - control.update(Some(bps(1_600_000)), now + Duration::from_secs(2)), + control.update(Some(bps(1_600_000)), now.saturating_add(Duration::from_secs(2))), Some(on(bps(1_600_000))) ); } @@ -762,7 +774,7 @@ mod tests { control.update(Some(bps(1_000_000)), start).unwrap(); assert_eq!(control.deadline(), None, "a drop lands at once"); - let recovered = start + Duration::from_secs(1); + let recovered = start.saturating_add(Duration::from_secs(1)); assert_eq!( control.update(Some(bps(4_000_000)), recovered), Some(on(bps(1_250_000))) @@ -788,7 +800,7 @@ mod tests { for floor in [1, max / 10, max / 3, max - max / 25] { let mut control = Control::new(Policy::new(bps(max))); control.update(Some(bps(floor)), start); - let at = start + Duration::from_millis(7); + let at = start.saturating_add(Duration::from_millis(7)); control.update(Some(bps(max)), at); let (applied, _) = follow(&mut control, bps(max)); assert_eq!(control.target(), on(bps(max)), "{max} from {floor}: {applied:?}"); @@ -803,7 +815,7 @@ mod tests { let start = kio::clock::now(); control.update(Some(bps(1_000_000)), start).unwrap(); assert_eq!( - control.update(Some(bps(1_100_000)), start + Duration::from_secs(1)), + control.update(Some(bps(1_100_000)), start.saturating_add(Duration::from_secs(1))), Some(on(bps(1_100_000))) ); assert_eq!(control.deadline(), None); @@ -817,7 +829,7 @@ mod tests { let start = kio::clock::now(); control.update(Some(bps(1_000_000)), start).unwrap(); control - .update(Some(bps(2_000_000)), start + Duration::from_secs(1)) + .update(Some(bps(2_000_000)), start.saturating_add(Duration::from_secs(1))) .unwrap(); assert!(control.deadline().is_some()); @@ -833,14 +845,17 @@ mod tests { let start = kio::clock::now(); let mut whole = control(); whole.update(Some(bps(2_000_000)), start).unwrap(); - assert_eq!(whole.update(Some(bps(2_050_000)), start + Duration::from_secs(1)), None); + assert_eq!( + whole.update(Some(bps(2_050_000)), start.saturating_add(Duration::from_secs(1))), + None + ); assert_eq!(whole.deadline(), None); // 1M to 1.3M: one second allows 1.25M, leaving 50k under the 62.5k band. let mut remainder = control(); remainder.update(Some(bps(1_000_000)), start).unwrap(); assert_eq!( - remainder.update(Some(bps(1_300_000)), start + Duration::from_secs(1)), + remainder.update(Some(bps(1_300_000)), start.saturating_add(Duration::from_secs(1))), Some(on(bps(1_250_000))) ); assert_eq!(remainder.deadline(), None); @@ -854,19 +869,19 @@ mod tests { let mut control = control(); control.update(Some(bps(1_000_000)), start).unwrap(); control - .update(Some(bps(4_000_000)), start + Duration::from_secs(1)) + .update(Some(bps(4_000_000)), start.saturating_add(Duration::from_secs(1))) .unwrap(); assert!(control.deadline().is_some()); control }; let mut control = scheduled(); - assert_eq!(control.update(None, start + Duration::from_secs(2)), None); + assert_eq!(control.update(None, start.saturating_add(Duration::from_secs(2))), None); assert_eq!(control.deadline(), None); let mut control = scheduled(); assert_eq!( - control.update(Some(bps(800_000)), start + Duration::from_secs(2)), + control.update(Some(bps(800_000)), start.saturating_add(Duration::from_secs(2))), Some(on(bps(800_000))) ); assert_eq!(control.deadline(), None); @@ -880,23 +895,23 @@ mod tests { let start = kio::clock::now(); control.update(Some(bps(1_000_000)), start).unwrap(); control - .update(Some(bps(4_000_000)), start + Duration::from_secs(1)) + .update(Some(bps(4_000_000)), start.saturating_add(Duration::from_secs(1))) .unwrap(); let (applied, last) = follow(&mut control, bps(4_000_000)); assert_eq!(applied.last(), Some(&bps(4_000_000))); let before = applied[applied.len() - 2]; - let failed = last.unwrap() + Duration::from_millis(1); + let failed = last.unwrap().saturating_add(Duration::from_millis(1)); control.failed(failed); assert_eq!(control.target(), on(before), "the previous target is restored"); let retry = control.deadline().expect("the failed raise is retried"); assert!( - retry >= failed + RETRY, + retry >= failed.saturating_add(RETRY), "{retry:?} is sooner than one step after {failed:?}" ); // A second report has nothing left to take back. - control.failed(failed + Duration::from_secs(1)); + control.failed(failed.saturating_add(Duration::from_secs(1))); assert_eq!(control.target(), on(before)); assert_eq!(control.deadline(), Some(retry)); @@ -912,9 +927,9 @@ mod tests { control.update(Some(bps(1_000_000)), start).unwrap(); control.failed(start); assert_eq!(control.target(), on(bps(4_000_000))); - assert_eq!(control.deadline(), Some(start + RETRY)); + assert_eq!(control.deadline(), Some(start.saturating_add(RETRY))); assert_eq!( - control.update(Some(bps(1_000_000)), start + RETRY), + control.update(Some(bps(1_000_000)), start.saturating_add(RETRY)), Some(on(bps(1_000_000))) ); assert_eq!(control.deadline(), None); @@ -927,10 +942,10 @@ mod tests { let start = kio::clock::now(); control.update(Some(bps(2_000_000)), start).unwrap(); assert_eq!( - control.update(Some(bps(1_960_000)), start + Duration::from_secs(1)), + control.update(Some(bps(1_960_000)), start.saturating_add(Duration::from_secs(1))), None ); - control.failed(start + Duration::from_secs(1)); + control.failed(start.saturating_add(Duration::from_secs(1))); assert_eq!(control.target(), on(bps(2_000_000))); assert_eq!(control.deadline(), None); } @@ -1110,7 +1125,7 @@ mod tests { // Squeezed, but still inside its band: it adapts like any sender. assert_eq!(rung.update(Some(bps(3_500_000)), start), Some(on(bps(3_500_000)))); // Below it, the lower rendition is the better picture, so stop. - let off = start + Duration::from_millis(100); + let off = start.saturating_add(Duration::from_millis(100)); assert_eq!(rung.update(Some(bps(3_000_000)), off), Some(Target::Disabled)); assert_eq!(rung.target(), Target::Disabled); assert_eq!(rung.deadline(), None, "only a new estimate resumes it"); @@ -1147,7 +1162,7 @@ mod tests { rung.set_probed(false); assert_eq!( - rung.update(Some(bps(1_000_000)), start + Duration::from_secs(1)), + rung.update(Some(bps(1_000_000)), start.saturating_add(Duration::from_secs(1))), Some(on(bps(1_000_000))) ); } @@ -1159,12 +1174,18 @@ mod tests { assert_eq!(rung.update(Some(bps(3_000_000)), start), Some(Target::Disabled)); // Back over the boundary, but not by the 5% hysteresis: stay off. - assert_eq!(rung.update(Some(bps(3_400_000)), start + Duration::from_secs(1)), None); - assert_eq!(rung.update(Some(bps(3_499_000)), start + Duration::from_secs(2)), None); + assert_eq!( + rung.update(Some(bps(3_400_000)), start.saturating_add(Duration::from_secs(1))), + None + ); + assert_eq!( + rung.update(Some(bps(3_499_000)), start.saturating_add(Duration::from_secs(2))), + None + ); assert_eq!(rung.target(), Target::Disabled); // Clear of it: resume at the boundary rather than the whole estimate. - let resumed = start + Duration::from_secs(3); + let resumed = start.saturating_add(Duration::from_secs(3)); assert_eq!(rung.update(Some(bps(5_000_000)), resumed), Some(on(bps(3_333_333)))); // Then ramp at 25%/s like any raise, on deadlines alone. @@ -1184,16 +1205,16 @@ mod tests { // About 3% either side of the boundary, every 100ms for 10s. let jitter = |tick: u64| if tick.is_multiple_of(2) { 3_250_000 } else { 3_430_000 }; for tick in 1..=100u64 { - let at = start + Duration::from_millis(100 * tick); + let at = start.saturating_add(Duration::from_millis(100 * tick)); assert_eq!(rung.update(Some(bps(jitter(tick))), at), None, "tick {tick}"); } assert_eq!(rung.target(), on(bps(3_400_000))); // A real drop turns it off, and the same jitter can't bring it back. - let off = start + Duration::from_secs(20); + let off = start.saturating_add(Duration::from_secs(20)); assert_eq!(rung.update(Some(bps(3_000_000)), off), Some(Target::Disabled)); for tick in 1..=100u64 { - let at = off + Duration::from_millis(100 * tick); + let at = off.saturating_add(Duration::from_millis(100 * tick)); assert_eq!(rung.update(Some(bps(jitter(tick))), at), None, "tick {tick}"); } assert_eq!(rung.target(), Target::Disabled); @@ -1204,7 +1225,7 @@ mod tests { let mut rung = rung(); let now = kio::clock::now(); rung.update(Some(bps(1_000_000)), now).unwrap(); - assert_eq!(rung.update(None, now + Duration::from_secs(10)), None); + assert_eq!(rung.update(None, now.saturating_add(Duration::from_secs(10))), None); assert_eq!(rung.target(), Target::Disabled); } @@ -1219,7 +1240,7 @@ mod tests { let now = kio::clock::now(); assert_eq!(rung.update(Some(bps(500_000)), now), Some(Target::Disabled)); assert_eq!( - rung.update(Some(bps(10_000_000)), now + Duration::from_secs(1)), + rung.update(Some(bps(10_000_000)), now.saturating_add(Duration::from_secs(1))), Some(on(bps(966_666))) ); } @@ -1243,16 +1264,19 @@ mod tests { assert_eq!(rung.update(Some(bps(3_000_000)), start), Some(Target::Disabled)); rung.failed(start); assert_eq!(rung.target(), on(bps(5_000_000))); - assert_eq!(rung.deadline(), Some(start + RETRY)); - assert_eq!(rung.update(Some(bps(3_000_000)), start + RETRY), Some(Target::Disabled)); + assert_eq!(rung.deadline(), Some(start.saturating_add(RETRY))); + assert_eq!( + rung.update(Some(bps(3_000_000)), start.saturating_add(RETRY)), + Some(Target::Disabled) + ); - let resumed = start + Duration::from_secs(5); + let resumed = start.saturating_add(Duration::from_secs(5)); assert_eq!(rung.update(Some(bps(5_000_000)), resumed), Some(on(bps(3_333_333)))); rung.failed(resumed); assert_eq!(rung.target(), Target::Disabled); - assert_eq!(rung.deadline(), Some(resumed + RETRY)); + assert_eq!(rung.deadline(), Some(resumed.saturating_add(RETRY))); assert_eq!( - rung.update(Some(bps(5_000_000)), resumed + RETRY), + rung.update(Some(bps(5_000_000)), resumed.saturating_add(RETRY)), Some(on(bps(3_333_333))) ); } @@ -1265,12 +1289,15 @@ mod tests { let mut rung = rung(); let start = kio::clock::now(); assert_eq!(rung.update(Some(bps(3_000_000)), start), Some(Target::Disabled)); - let resumed = start + Duration::from_secs(1); + let resumed = start.saturating_add(Duration::from_secs(1)); assert_eq!(rung.update(Some(bps(5_000_000)), resumed), Some(on(bps(3_333_333)))); rung.failed(resumed); - assert_eq!(rung.deadline(), Some(resumed + RETRY)); + assert_eq!(rung.deadline(), Some(resumed.saturating_add(RETRY))); - assert_eq!(rung.update(Some(bps(3_000_000)), resumed + RETRY / 2), None); + assert_eq!( + rung.update(Some(bps(3_000_000)), resumed.saturating_add(RETRY / 2)), + None + ); assert_eq!(rung.target(), Target::Disabled); assert_eq!(rung.deadline(), None); } @@ -1287,14 +1314,14 @@ mod tests { let mut funded = rung.clone(); rung.set_probed(true); assert_eq!( - rung.update(Some(bps(3_000_000)), start + Duration::from_millis(100)), + rung.update(Some(bps(3_000_000)), start.saturating_add(Duration::from_millis(100))), Some(Target::Disabled) ); // A grant over the boundary funds it, so it ramps up from under it instead. funded.set_probed(true); assert_eq!( - funded.update(Some(bps(5_000_000)), start + Duration::from_secs(1)), + funded.update(Some(bps(5_000_000)), start.saturating_add(Duration::from_secs(1))), Some(on(bps(3_750_000))) ); } @@ -1311,7 +1338,7 @@ mod tests { policy.lower = Some(bps(3_000_000)); assert!(rung.set_policy(policy)); assert_eq!( - rung.update(Some(bps(3_500_000)), start + Duration::from_millis(100)), + rung.update(Some(bps(3_500_000)), start.saturating_add(Duration::from_millis(100))), Some(Target::Disabled) ); } @@ -1375,14 +1402,14 @@ mod tests { // Shrinking further takes the middle one next, still keeping the lowest whole. estimate.set(Some(bps(2_000_000))).unwrap(); assert_eq!( - update(start + Duration::from_secs(1)), + update(start.saturating_add(Duration::from_secs(1))), [on(bps(1_000_000)), Target::Disabled, Target::Disabled] ); // Below every boundary, the lowest still encodes at what it gets. estimate.set(Some(bps(200_000))).unwrap(); assert_eq!( - update(start + Duration::from_secs(2)), + update(start.saturating_add(Duration::from_secs(2))), [on(bps(200_000)), Target::Disabled, Target::Disabled] ); @@ -1391,7 +1418,7 @@ mod tests { viewers[1] = None; viewers[2] = None; estimate.set(Some(bps(8_000_000))).unwrap(); - let recovered = update(start + Duration::from_secs(3)); + let recovered = update(start.saturating_add(Duration::from_secs(3))); assert_eq!(recovered[1], on(bps(1_333_333))); assert_eq!(recovered[2], on(bps(2_666_666))); } @@ -1468,7 +1495,7 @@ mod tests { self.set_policy(policy, fail); } Op::Advance(elapsed) => { - let end = self.now + elapsed; + let end = self.now.saturating_add(elapsed); while let Some(at) = self.control.deadline().filter(|at| *at <= end) { self.now = at; self.wake(fail); diff --git a/rs/moq-mux/src/sync.rs b/rs/moq-mux/src/sync.rs index c56adbf5aba..47aaaa807d8 100644 --- a/rs/moq-mux/src/sync.rs +++ b/rs/moq-mux/src/sync.rs @@ -750,25 +750,25 @@ mod tests { /// live edge without giving up the delay; late ones leave it alone. #[test] fn the_earliest_arrival_sets_the_schedule() { - let start = Instant::ZERO + Duration::from_secs(1); + let start = Instant::ZERO.saturating_add(Duration::from_secs(1)); let clock = Producer::new(DELAY); let video = clock.track(Kind::Video); assert_eq!(clock.due(ms(0)), None, "nothing anchors before the first frame"); assert!(video.received(ms(0), start), "the first anchor"); - assert_eq!(clock.due(ms(0)), Some(start + DELAY)); + assert_eq!(clock.due(ms(0)), Some(start.saturating_add(DELAY))); // 40ms of media later, but only 20ms of wall clock: the first frame was // 20ms late, so the schedule moves onto this one. - let now = start + Duration::from_millis(20); + let now = start.saturating_add(Duration::from_millis(20)); assert!(video.received(ms(40), now), "an early frame left the schedule alone"); - assert_eq!(clock.due(ms(40)), Some(now + DELAY)); + assert_eq!(clock.due(ms(40)), Some(now.saturating_add(DELAY))); // A frame that merely arrives late keeps its media instant. The delay is // the room it has to be late in. - let late = now + Duration::from_millis(70); + let late = now.saturating_add(Duration::from_millis(70)); assert!(!video.received(ms(80), late), "a late arrival moved the schedule"); - assert_eq!(clock.due(ms(80)), Some(now + Duration::from_millis(140))); + assert_eq!(clock.due(ms(80)), Some(now.saturating_add(Duration::from_millis(140)))); } /// The required decoupling: audio stalled by congestion arrives late, which @@ -776,27 +776,30 @@ mod tests { /// the steady state. #[test] fn stalled_audio_no_longer_holds_video() { - let start = Instant::ZERO + Duration::from_secs(1); + let start = Instant::ZERO.saturating_add(Duration::from_secs(1)); let clock = Producer::new(DELAY); let audio = clock.track(Kind::Audio); let video = clock.track(Kind::Video); audio.received(ms(0), start); video.received(ms(0), start); let steady = clock.due(ms(1_000)); - assert_eq!(steady, Some(start + DELAY + Duration::from_secs(1))); + assert_eq!( + steady, + Some(start.saturating_add(DELAY).saturating_add(Duration::from_secs(1))) + ); // Video keeps arriving on time while audio stalls for 500ms, then audio // lands in a late burst and resets its timeline on a fresh sink. for frame in 1..=25 { - let at = start + Duration::from_millis(frame * 40); + let at = start.saturating_add(Duration::from_millis(frame * 40)); assert!(!video.received(ms(frame * 40), at)); } - let resumed = start + Duration::from_millis(1_000); + let resumed = start.saturating_add(Duration::from_millis(1_000)); for frame in 0..25 { assert!(!audio.received(ms(500 + frame * 20), resumed), "late audio moved video"); } audio.reset(); - assert!(!audio.received(ms(1_000), resumed + Duration::from_millis(100))); + assert!(!audio.received(ms(1_000), resumed.saturating_add(Duration::from_millis(100)))); assert_eq!(clock.due(ms(1_000)), steady, "stalled audio held video"); } @@ -804,51 +807,54 @@ mod tests { /// moves every track onto it, audio included. #[test] fn a_video_burst_moves_audio_onto_the_live_edge() { - let start = Instant::ZERO + Duration::from_secs(1); + let start = Instant::ZERO.saturating_add(Duration::from_secs(1)); let clock = Producer::new(DELAY); let audio = clock.track(Kind::Audio); let video = clock.track(Kind::Video); audio.received(ms(1_000), start); assert!(video.received(ms(4_000), start)); - assert_eq!(clock.due(ms(4_000)), Some(start + DELAY)); + assert_eq!(clock.due(ms(4_000)), Some(start.saturating_add(DELAY))); } /// A track that resets gives up its arrivals: the schedule falls back to the /// earliest track left, and with none left the next frame anchors afresh. #[test] fn a_reset_hands_the_schedule_to_the_tracks_left() { - let start = Instant::ZERO + Duration::from_secs(1); + let start = Instant::ZERO.saturating_add(Duration::from_secs(1)); let clock = Producer::new(DELAY); let audio = clock.track(Kind::Audio); let video = clock.track(Kind::Video); video.received(ms(0), start); // Audio runs 30ms ahead of video, so it holds the schedule. audio.received(ms(30), start); - assert_eq!(clock.due(ms(30)), Some(start + DELAY)); + assert_eq!(clock.due(ms(30)), Some(start.saturating_add(DELAY))); audio.reset(); - assert_eq!(clock.due(ms(30)), Some(start + DELAY + Duration::from_millis(30))); + assert_eq!( + clock.due(ms(30)), + Some(start.saturating_add(DELAY).saturating_add(Duration::from_millis(30))) + ); video.reset(); assert_eq!(clock.due(ms(30)), None); - let now = start + Duration::from_secs(5); + let now = start.saturating_add(Duration::from_secs(5)); audio.received(ms(500), now); - assert_eq!(clock.due(ms(500)), Some(now + DELAY)); + assert_eq!(clock.due(ms(500)), Some(now.saturating_add(DELAY))); // The last track to go leaves its schedule for what it queued, until // another anchors afresh. drop(audio); - assert_eq!(clock.due(ms(500)), Some(now + DELAY)); - let later = now + Duration::from_secs(5); + assert_eq!(clock.due(ms(500)), Some(now.saturating_add(DELAY))); + let later = now.saturating_add(Duration::from_secs(5)); video.received(ms(0), later); - assert_eq!(clock.due(ms(0)), Some(later + DELAY)); + assert_eq!(clock.due(ms(0)), Some(later.saturating_add(DELAY))); } /// Playback holds the deepest target a live track asks for, and the default /// while none asks. #[test] fn the_delay_is_the_largest_target_held() { - let start = Instant::ZERO + Duration::from_secs(1); + let start = Instant::ZERO.saturating_add(Duration::from_secs(1)); let clock = Producer::new(DELAY); let reader = clock.consume(); let audio = clock.track(Kind::Audio); @@ -858,7 +864,7 @@ mod tests { assert!(audio.set_target(Duration::from_millis(60))); assert_eq!(reader.delay(), Duration::from_millis(60)); - assert_eq!(clock.due(ms(0)), Some(start + Duration::from_millis(60))); + assert_eq!(clock.due(ms(0)), Some(start.saturating_add(Duration::from_millis(60)))); assert!(video.set_target(Duration::from_millis(80))); assert!( !audio.set_target(Duration::from_millis(70)), @@ -878,19 +884,31 @@ mod tests { let reader = clock.consume(); let audio = clock.track(Kind::Audio); let video = clock.track(Kind::Video); - let now = Instant::ZERO + Duration::from_secs(1); + let now = Instant::ZERO.saturating_add(Duration::from_secs(1)); video.received(ms(0), now); let frames = [ms(0), ms(20), ms(40)]; assert_eq!(reader.present(frames, now), None); - assert_eq!(reader.present(frames, now + Duration::from_millis(60)), Some(1)); + assert_eq!( + reader.present(frames, now.saturating_add(Duration::from_millis(60))), + Some(1) + ); // Audio arrives 40ms ahead; stale video deadlines no longer apply. audio.received(ms(40), now); assert_eq!(reader.present(frames, now), Some(0)); - assert_eq!(reader.present(frames, now + Duration::from_millis(39)), Some(1)); - assert_eq!(reader.present(frames, now + Duration::from_millis(40)), Some(2)); + assert_eq!( + reader.present(frames, now.saturating_add(Duration::from_millis(39))), + Some(1) + ); + assert_eq!( + reader.present(frames, now.saturating_add(Duration::from_millis(40))), + Some(2) + ); // Neither a stall nor a future-only queue invents a new picture. - assert_eq!(reader.present([], now + Duration::from_secs(1)), None); - assert_eq!(reader.present([ms(200)], now + Duration::from_millis(100)), None); + assert_eq!(reader.present([], now.saturating_add(Duration::from_secs(1))), None); + assert_eq!( + reader.present([ms(200)], now.saturating_add(Duration::from_millis(100))), + None + ); } #[tokio::test] @@ -910,7 +928,7 @@ mod tests { // A JoinSet abort can leave these updates and drops until after the new track started. drop(old); previous.track(Kind::Audio).received(ms(10_000), now); - assert_eq!(reader.due(ms(0)), Some(now + DELAY)); + assert_eq!(reader.due(ms(0)), Some(now.saturating_add(DELAY))); let video = clock.track(Kind::Video); let transition = video.declare(); video.plan(transition, ms(0), None); @@ -945,7 +963,7 @@ mod tests { let waiter = kio::Waiter::new(Waker::from(wakes.clone())); let mut resume = video.resume(transition, ms(0), None); assert!(resume.poll_ready(&waiter).is_pending()); - let later = now + Duration::from_millis(20); + let later = now.saturating_add(Duration::from_millis(20)); video.received(ms(20), later); audio.received(ms(20), later); assert_eq!(wakes.0.load(Ordering::Relaxed), 0); @@ -1035,12 +1053,12 @@ mod tests { let mapping = audio.resume(transition, ms(0), Some(DELAY)).ready().await.unwrap(); audio.apply(transition, mapping); assert!( - kio::clock::now() >= start + DELAY * 2, + kio::clock::now() >= start.saturating_add(DELAY * 2), "the replacement waited for the tail" ); let unchanged = clock.state.lock().unwrap().due(ms(10_500)); for frame in 0..10 { - let at = start + Duration::from_millis(frame * 20); + let at = start.saturating_add(Duration::from_millis(frame * 20)); assert!( !audio.received(audio.map(ms(frame * 20)).unwrap(), at), "held media moved the schedule" @@ -1159,7 +1177,7 @@ mod tests { ); video.apply(next, video.resume(next, ms(5_000), None).ready().await.unwrap()); // The later replacement maps onto the running clock, not the audio restart's. - let resumed = kio::clock::now() + DELAY; + let resumed = kio::clock::now().saturating_add(DELAY); assert_eq!( clock.state.lock().unwrap().due(video.map(ms(5_000)).unwrap()), Some(resumed) @@ -1183,7 +1201,7 @@ mod tests { transition, video.resume(transition, ms(40), None).ready().await.unwrap(), ); - let resumed = kio::clock::now() + DELAY; + let resumed = kio::clock::now().saturating_add(DELAY); assert_eq!( clock.state.lock().unwrap().due(video.map(ms(40)).unwrap()), Some(resumed) @@ -1246,7 +1264,7 @@ mod tests { audio.declare(); audio.end(ms(10_200)).unwrap(); // The track closed, but its returned sink still plays the tail up to the end. - audio.retire(Some(now + Duration::from_millis(300))); + audio.retire(Some(now.saturating_add(Duration::from_millis(300)))); let transition = video.declare(); video.end(ms(10_000)).unwrap(); video.plan(transition, ms(0), None); @@ -1265,7 +1283,7 @@ mod tests { let (clock, audio, video) = anchored(now); audio.declare(); audio.end(ms(10_200)).unwrap(); - audio.retire(Some(now + Duration::from_millis(300))); + audio.retire(Some(now.saturating_add(Duration::from_millis(300)))); // A replacement rendition starts over at zero and anchors afresh. let successor = Track::new(clock.clone(), Kind::Audio); successor.received(ms(50), now); @@ -1286,7 +1304,7 @@ mod tests { let (clock, audio, video) = anchored(now); audio.declare(); audio.end(ms(10_200)).unwrap(); - audio.retire(Some(now + Duration::from_millis(300))); + audio.retire(Some(now.saturating_add(Duration::from_millis(300)))); // The next rendition fails while the retired sink still plays. let successor = Track::new(clock.clone(), Kind::Audio); successor.declare(); @@ -1331,7 +1349,7 @@ mod tests { ); assert_eq!( clock.state.lock().unwrap().due(audio.map(ms(0)).unwrap()), - Some(now + Duration::from_millis(200)) + Some(now.saturating_add(Duration::from_millis(200))) ); } } diff --git a/rs/moq-net/benches/memory.rs b/rs/moq-net/benches/memory.rs index 8150d8cf882..1f830dc3894 100644 --- a/rs/moq-net/benches/memory.rs +++ b/rs/moq-net/benches/memory.rs @@ -220,7 +220,7 @@ impl Link { // Advance the cache/model clock between rounds to expire read history. fn tick(&mut self) { - self.cache_now += cache::DEFAULT_EXPIRY; + self.cache_now = self.cache_now.saturating_add(cache::DEFAULT_EXPIRY); for pool in &self.pools { pool.poll(self.cache_now, &kio::Waiter::noop()); } diff --git a/rs/moq-net/benches/session/mod.rs b/rs/moq-net/benches/session/mod.rs index d76fc14937a..80b5b0327c4 100644 --- a/rs/moq-net/benches/session/mod.rs +++ b/rs/moq-net/benches/session/mod.rs @@ -966,11 +966,13 @@ impl Room { /// Each round completes its reads before this step; pending read deadlines /// share this clock too. fn tick(&mut self) { - self.cache_now += if std::env::var_os("SESSION_EXPIRY_ONLY").is_some() { - Duration::from_secs(1) - } else { - cache::DEFAULT_EXPIRY - }; + self.cache_now = self + .cache_now + .saturating_add(if std::env::var_os("SESSION_EXPIRY_ONLY").is_some() { + Duration::from_secs(1) + } else { + cache::DEFAULT_EXPIRY + }); for pool in self.pools() { pool.poll(self.cache_now, &kio::Waiter::noop()); } diff --git a/rs/moq-net/benches/track.rs b/rs/moq-net/benches/track.rs index b918cec4138..81fdd1e3793 100644 --- a/rs/moq-net/benches/track.rs +++ b/rs/moq-net/benches/track.rs @@ -511,7 +511,10 @@ fn bench_wall(c: &mut Criterion) { || Aged::new(tracks, groups), |aged| { // Past every deadline, which setup armed after `now`. - black_box(aged.pool.poll(aged.now + 2 * AGED_BUDGET, &kio::Waiter::noop())); + black_box( + aged.pool + .poll(aged.now.saturating_add(2 * AGED_BUDGET), &kio::Waiter::noop()), + ); aged }, BatchSize::PerIteration, @@ -538,7 +541,7 @@ fn bench_gc(c: &mut Criterion) { let mut now = swept.now; let waiter = kio::Waiter::noop(); b.iter(|| { - now += Duration::from_nanos(1); + now = now.saturating_add(Duration::from_nanos(1)); black_box(swept.pool.poll(now, &waiter)) }); }); @@ -550,7 +553,7 @@ fn bench_gc(c: &mut Criterion) { let mut now = swept.now; let waiter = kio::Waiter::noop(); b.iter(|| { - now += interval; + now = now.saturating_add(interval); black_box(swept.pool.poll(now, &waiter)) }); }); @@ -1392,12 +1395,12 @@ impl Expiring { let mut fixture = Self { sparse, pool, - now: Instant::now() + Duration::from_secs(3600), + now: Instant::now().saturating_add(Duration::from_secs(3600)), }; for gap in 0..gaps { fixture.pool.poll(fixture.now, &kio::Waiter::noop()); fixture.sparse.hand_out(gap * 2); - fixture.now += Duration::from_millis(1); + fixture.now = fixture.now.saturating_add(Duration::from_millis(1)); } fixture.sparse.next = gaps * 2; // The eviction queue trails arrivals by one entry: warm both capacities. @@ -1413,7 +1416,7 @@ impl Expiring { } fn step(&mut self) { - self.now += Duration::from_millis(1); + self.now = self.now.saturating_add(Duration::from_millis(1)); self.pool.poll(self.now, &kio::Waiter::noop()); self.sparse.hand_out(self.sparse.next); self.sparse.next += 2; diff --git a/rs/moq-net/src/discovery.rs b/rs/moq-net/src/discovery.rs index e19c479d29f..fa0440b157f 100644 --- a/rs/moq-net/src/discovery.rs +++ b/rs/moq-net/src/discovery.rs @@ -276,7 +276,7 @@ impl Discovery { if request.linger.is_some() { return; } - let at = self.runtime.now() + LINGER; + let at = self.runtime.now().saturating_add(LINGER); request.linger = Some(at); self.lingering.insert((at, prefix)); self.timer.set(self.lingering.first().map(|(at, _)| *at)); diff --git a/rs/moq-net/src/goaway.rs b/rs/moq-net/src/goaway.rs index a0816dbf146..87366390b98 100644 --- a/rs/moq-net/src/goaway.rs +++ b/rs/moq-net/src/goaway.rs @@ -396,12 +396,15 @@ mod tests { .producer() .send(Goaway::new().with_timeout(Duration::from_secs(1))) .unwrap(); - let sent = crate::time::Instant::ZERO + Duration::from_secs(5); + let sent = crate::time::Instant::ZERO.saturating_add(Duration::from_secs(5)); runtime.advance(sent); assert!(deadline.poll(&waiter).is_pending()); - runtime.advance(sent + Duration::from_secs(1) - Duration::from_nanos(1)); + runtime.advance( + sent.saturating_add(Duration::from_secs(1)) + .saturating_sub(Duration::from_nanos(1)), + ); assert!(deadline.poll(&waiter).is_pending()); - runtime.advance(sent + Duration::from_secs(1)); + runtime.advance(sent.saturating_add(Duration::from_secs(1))); assert_eq!(deadline.poll(&waiter), Poll::Ready(Some(Duration::from_secs(1)))); } diff --git a/rs/moq-net/src/ietf/publisher.rs b/rs/moq-net/src/ietf/publisher.rs index 4a006716cd8..5be484e23ce 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -599,7 +599,7 @@ impl Watched { fn lapsed(&mut self, now: crate::time::Instant) -> Refused { let wait = self.lapse; self.lapse = (wait * 2).min(RETRY_MAX); - Refused::Until(now + wait) + Refused::Until(now.saturating_add(wait)) } } @@ -1378,6 +1378,9 @@ impl SubscribeRequest { /// Mark the subscription for joining FETCHes from the boundary it serves from: the /// prefix ending right after `largest`. + /// + /// The end is exclusive, and End Object 0 reads the whole group, which is that prefix + /// when `largest` is the last Object ID a group can hold. fn save_join( &self, filter: Filter, @@ -1392,7 +1395,7 @@ impl SubscribeRequest { (Filter::NextObject, Some(largest)) => Joined::Group { end: Location { group: largest.group, - object: largest.object + 1, + object: largest.object.checked_add(1).unwrap_or(0), }, cache: cache.clone(), namespace: self.msg.track_namespace.clone(), @@ -3878,7 +3881,7 @@ impl Publisher { if matches!(&written, Poll::Ready(Ok(()))) && matches!(request.pending, Some(NamespacePending::Writing { .. })) { - let deadline = now + ADVERTISE_TIMEOUT; + let deadline = now.saturating_add(ADVERTISE_TIMEOUT); request.pending = Some(NamespacePending::Answer(deadline)); inflight.push_back((deadline, suffix.clone())); } @@ -4025,11 +4028,15 @@ impl Publisher { /// /// 0 is the peer asking not to be offered this again, which is what keeps a permanent /// refusal (unauthorized, uninterested) from becoming a request every few seconds for - /// the life of the session. + /// the life of the session. An interval past the clock's range reads the same way. fn refusal(&self, retry_interval: u64) -> Refused { match retry_interval { 0 => Refused::Never, - ms => Refused::Until(self.runtime.now() + Duration::from_millis(ms)), + ms => self + .runtime + .now() + .checked_add(Duration::from_millis(ms)) + .map_or(Refused::Never, Refused::Until), } } @@ -5810,7 +5817,7 @@ impl ForwardNamespaces { true => { self.retry_at = self .retry_at - .or_else(|| Some(publisher.runtime.now() + jitter(self.retry_delay))) + .or_else(|| Some(publisher.runtime.now().saturating_add(jitter(self.retry_delay)))) } false => { self.retry_at = None; @@ -10973,7 +10980,7 @@ mod serve_tests { let mut running: Running = Box::pin(h.publisher.clone().run_subscribe_namespace_stream(stream, msg)); let request = taken_token(&mut running, &mut requests).await; let issued = request.accept(crate::auth::Grant { - expires: expires.map(|after| h.publisher.runtime.now() + after), + expires: expires.map(|after| h.publisher.runtime.now().saturating_add(after)), ..crate::auth::Grant::all() }); assert!(futures::poll!(running.as_mut()).is_pending()); @@ -13024,6 +13031,32 @@ mod serve_tests { } } + /// An upstream's Largest Object can be the last Object ID a group holds, which no + /// exclusive end within the group follows: the join asks for that whole group, which + /// this cache holds only the head of. + #[kio::test] + async fn a_joining_fetch_through_the_last_object_id_reads_its_whole_group() { + const LATEST: u64 = 5; + + for version in JOINING_DRAFTS { + let mut h = serve(version); + publish_groups(&mut h, LATEST); + h.track.report_object(LATEST, u64::MAX); + settle().await; + + let stream = Stream::open(&crate::driver::Transport::new(h.session.clone()), version) + .await + .unwrap(); + let mut serve = std::pin::pin!( + h.publisher + .clone() + .run_subscribe_stream(stream, subscribe(Filter::NextObject, None)) + ); + registered(&h, serve.as_mut()).await; + assert_eq!(joining_refusal(&h, version).await, DOES_NOT_EXIST, "{version}"); + } + } + /// FETCH returns the saved multi-object prefix, including empty objects, and excludes /// later objects that belong to the subscription. Decode the wire fields independently. #[kio::test] @@ -18610,6 +18643,18 @@ mod tests { /// uninterested) into a request every few seconds for the life of the session. #[kio::test] async fn a_refusal_that_forbids_retrying_is_not_retried() { + refused_once(0).await; + } + + /// The largest retry interval a peer can encode is past the clock's range: it waits + /// forever rather than panicking the publisher. + #[kio::test] + async fn a_refusal_past_the_clock_s_range_is_not_retried() { + refused_once(crate::coding::varint::MAX_QUIC).await; + } + + /// Refuse the only advertisement with `retry_interval`, and assert it is never re-offered. + async fn refused_once(retry_interval: u64) { const VERSION: Version = Version::Draft18; let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); @@ -18618,7 +18663,7 @@ mod tests { // Every stream is answered with the same refusal, so a retry would show up as a // second occurrence on the wire. - let refusal = publish_namespace_error(VERSION, 0).await; + let refusal = publish_namespace_error(VERSION, retry_interval).await; let session = crate::lite::test_transport::ScriptedSession::per_stream(vec![refusal.clone(), refusal.clone(), refusal]); let log = session.log.clone(); diff --git a/rs/moq-net/src/ietf/subscriber.rs b/rs/moq-net/src/ietf/subscriber.rs index b8885d61bf7..08c13f00eb5 100644 --- a/rs/moq-net/src/ietf/subscriber.rs +++ b/rs/moq-net/src/ietf/subscriber.rs @@ -16996,7 +16996,10 @@ mod stitch_tests { .run_group_fetch(Path::from_static("broadcast"), "video".into(), fill, None) .await; // The peer may still deliver a late subgroup stream during the arrival grace. - run.track.broadcast().pool.poll(now + crate::ledger::GRACE, &waiter); + run.track + .broadcast() + .pool + .poll(now.saturating_add(crate::ledger::GRACE), &waiter); assert_eq!( reader.poll_drop(&waiter), Poll::Ready((1..3, crate::track::Hole::drop(crate::StreamError::NotFound))), diff --git a/rs/moq-net/src/ledger.rs b/rs/moq-net/src/ledger.rs index 8d8bbe2da34..f0f8bde21a7 100644 --- a/rs/moq-net/src/ledger.rs +++ b/rs/moq-net/src/ledger.rs @@ -364,11 +364,11 @@ mod tests { let revision = ledger.changes().revision(); ledger.account(1..4, now); assert_eq!(ledger.changes().since(revision).collect::>(), vec![0..5]); - ledger.expire(now + GRACE); + ledger.expire(now.saturating_add(GRACE)); assert_eq!(ledger.changes().since(0).collect::>(), vec![0..9]); assert_eq!(ledger.changes.changed.len(), ledger.runs.len()); let revision = ledger.changes().revision(); - ledger.account(2..7, now + GRACE); + ledger.account(2..7, now.saturating_add(GRACE)); assert_eq!(ledger.changes().revision(), revision, "already accounted is unchanged"); } @@ -412,7 +412,7 @@ mod tests { #[test] fn gaps_within_a_span() { let now = Instant::now(); - let later = now + GRACE; + let later = now.saturating_add(GRACE); let mut ledger = Ledger::default(); assert_eq!(ledger.gaps(2..5).collect::>(), vec![(2..5, None)]); arrive(&mut ledger, 2..3, now); @@ -433,19 +433,19 @@ mod tests { let mut ledger = Ledger::new(GRACE); arrive(&mut ledger, 0..1, start); arrive(&mut ledger, 2..3, start); - arrive(&mut ledger, 4..5, start + GRACE / 2); + arrive(&mut ledger, 4..5, start.saturating_add(GRACE / 2)); assert_eq!(groups(&ledger), vec![0..1, 2..3, 4..5]); // Splitting the younger gap keeps it as late as it was. - arrive(&mut ledger, 6..7, start + GRACE / 2); - arrive(&mut ledger, 8..9, start + GRACE); + arrive(&mut ledger, 6..7, start.saturating_add(GRACE / 2)); + arrive(&mut ledger, 8..9, start.saturating_add(GRACE)); assert_eq!( groups(&ledger), vec![0..3, 4..5, 6..7, 8..9], "only the oldest gap expired" ); - ledger.expire(start + GRACE * 2); + ledger.expire(start.saturating_add(GRACE * 2)); assert_eq!(groups(&ledger), vec![0..9]); assert!(ledger.covers(0..9)); } @@ -460,8 +460,11 @@ mod tests { assert_eq!(ledger.folds_at(0, GRACE), None, "accounted for"); assert_eq!(ledger.folds_at(1, GRACE), None, "nothing later arrived"); - arrive(&mut ledger, 2..3, start + GRACE / 2); - assert_eq!(ledger.folds_at(1, GRACE), Some(start + GRACE / 2 + GRACE)); + arrive(&mut ledger, 2..3, start.saturating_add(GRACE / 2)); + assert_eq!( + ledger.folds_at(1, GRACE), + Some(start.saturating_add(GRACE / 2).saturating_add(GRACE)) + ); assert_eq!(ledger.folds_at(3, GRACE), None); } @@ -472,10 +475,10 @@ mod tests { let mut ledger = Ledger::new(GRACE); arrive(&mut ledger, 0..1, start); arrive(&mut ledger, 9..10, start); - arrive(&mut ledger, 5..6, start + GRACE / 2); + arrive(&mut ledger, 5..6, start.saturating_add(GRACE / 2)); assert_eq!(groups(&ledger), vec![0..1, 5..6, 9..10]); - ledger.expire(start + GRACE); + ledger.expire(start.saturating_add(GRACE)); assert_eq!(groups(&ledger), vec![0..10], "both halves opened at the start"); } @@ -487,7 +490,7 @@ mod tests { arrive(&mut ledger, 3..4, start); arrive(&mut ledger, 9..10, start); - let lowered = start + GRACE * 2; + let lowered = start.saturating_add(GRACE * 2); ledger.demand(1..3, lowered); arrive(&mut ledger, 1..2, lowered); assert_eq!( @@ -497,7 +500,7 @@ mod tests { ); assert!(!ledger.covers(1..4)); - ledger.expire(lowered + GRACE); + ledger.expire(lowered.saturating_add(GRACE)); assert!(ledger.covers(1..10)); } /// Unaccounting reopens what a reversed verdict accounted for, as a gap waited for a fresh @@ -507,12 +510,12 @@ mod tests { let start = Instant::now(); let mut ledger = Ledger::new(GRACE); arrive(&mut ledger, 0..10, start); - ledger.unaccount(3..5, start + GRACE); + ledger.unaccount(3..5, start.saturating_add(GRACE)); assert!(ledger.covers(0..3) && ledger.covers(5..10)); assert!(!ledger.covers(3..5)); - ledger.expire(start + GRACE * 3 / 2); + ledger.expire(start.saturating_add(GRACE * 3 / 2)); assert!(!ledger.covers(3..5), "its grace runs from the reversal"); - ledger.expire(start + GRACE * 2); + ledger.expire(start.saturating_add(GRACE * 2)); assert!(ledger.covers(0..10)); } @@ -524,11 +527,11 @@ mod tests { let mut ledger = Ledger::new(GRACE); arrive(&mut ledger, 0..2, start); arrive(&mut ledger, 4..6, start); - let reversed = start + GRACE * 9 / 10; + let reversed = start.saturating_add(GRACE * 9 / 10); ledger.unaccount(1..2, reversed); - ledger.expire(start + GRACE); + ledger.expire(start.saturating_add(GRACE)); assert!(!ledger.covers(1..2), "its grace runs from the reversal"); - ledger.expire(reversed + GRACE); + ledger.expire(reversed.saturating_add(GRACE)); assert!(ledger.covers(0..6)); } @@ -538,13 +541,16 @@ mod tests { let mut ledger = Ledger::new(GRACE); arrive(&mut ledger, 0..1, start); arrive(&mut ledger, 4..5, start); - arrive(&mut ledger, 8..9, start + GRACE / 4); - ledger.demand(1..4, start + GRACE / 2); + arrive(&mut ledger, 8..9, start.saturating_add(GRACE / 4)); + ledger.demand(1..4, start.saturating_add(GRACE / 2)); - ledger.expire(start + GRACE + GRACE / 4); + ledger.expire(start.saturating_add(GRACE).saturating_add(GRACE / 4)); assert_eq!(groups(&ledger), vec![0..1, 4..9]); - assert_eq!(ledger.folds_at(1, GRACE), Some(start + GRACE + GRACE / 2)); - ledger.expire(start + GRACE + GRACE / 2); + assert_eq!( + ledger.folds_at(1, GRACE), + Some(start.saturating_add(GRACE).saturating_add(GRACE / 2)) + ); + ledger.expire(start.saturating_add(GRACE).saturating_add(GRACE / 2)); assert_eq!(groups(&ledger), vec![0..9]); } @@ -555,15 +561,15 @@ mod tests { arrive(&mut ledger, 0..1, start); arrive(&mut ledger, 2..3, start); ledger.set_grace(GRACE * 2); - ledger.expire(start + GRACE); + ledger.expire(start.saturating_add(GRACE)); assert_eq!(groups(&ledger), vec![0..1, 2..3]); ledger.set_grace(GRACE / 2); - ledger.expire(start + GRACE); + ledger.expire(start.saturating_add(GRACE)); assert_eq!(groups(&ledger), vec![0..3]); ledger.set_grace(GRACE * 2); - arrive(&mut ledger, 4..5, start + GRACE); - ledger.expire(start + GRACE * 2); + arrive(&mut ledger, 4..5, start.saturating_add(GRACE)); + ledger.expire(start.saturating_add(GRACE * 2)); assert_eq!(groups(&ledger), vec![0..3, 4..5]); } @@ -572,9 +578,9 @@ mod tests { let start = Instant::now(); let mut ledger = Ledger::new(GRACE); arrive(&mut ledger, 10..11, start); - ledger.expire(start + GRACE * 2); + ledger.expire(start.saturating_add(GRACE * 2)); assert_eq!(groups(&ledger), vec![10..11]); - arrive(&mut ledger, 0..1, start + GRACE * 2); + arrive(&mut ledger, 0..1, start.saturating_add(GRACE * 2)); assert_eq!(groups(&ledger), vec![0..11]); } #[test] @@ -586,7 +592,7 @@ mod tests { arrive( &mut ledger, arrival * 2..arrival * 2 + 1, - start + Duration::from_millis(arrival), + start.saturating_add(Duration::from_millis(arrival)), ); let runs = groups(&ledger); assert_eq!(runs.len() as u64, (arrival + 1).min(retained + 1)); diff --git a/rs/moq-net/src/lite/publisher.rs b/rs/moq-net/src/lite/publisher.rs index fbf5666ffa9..3091a658fc3 100644 --- a/rs/moq-net/src/lite/publisher.rs +++ b/rs/moq-net/src/lite/publisher.rs @@ -2641,8 +2641,9 @@ impl Request for SubscribeServe { let send = send.as_ref().expect("set above"); return match ready!(consumer.poll_recv(waiter))? { Some(datagram) => { - *end = (*end).max(datagram.sequence.saturating_add(1)); - send.send(datagram); + let next = datagram.sequence.saturating_add(1); + send.send(datagram)?; + *end = (*end).max(next); Poll::Ready(Ok(ControlFlow::Continue(()))) } None => { @@ -2888,7 +2889,8 @@ impl LegacyDatagrams { } /// Send the next datagram: `true` once one went, `false` once none will come, such as a - /// name with no datagram track. The subscription goes on either way. + /// name with no datagram track or a sequence the wire cannot carry. The subscription + /// goes on either way. fn poll_send(&mut self, shared: &Shared, waiter: &kio::Waiter) -> Poll { if self.send.is_none() { let Ok(info) = ready!(self.consumer.poll_info(waiter)) else { @@ -2899,10 +2901,7 @@ impl LegacyDatagrams { } let send = self.send.as_ref().expect("set above"); match ready!(self.consumer.poll_recv(waiter)) { - Ok(Some(datagram)) => { - send.send(datagram); - Poll::Ready(true) - } + Ok(Some(datagram)) => Poll::Ready(send.send(datagram).is_ok()), Ok(None) | Err(_) => Poll::Ready(false), } } @@ -2948,13 +2947,17 @@ impl DatagramSend { /// Send one datagram over a QUIC datagram, newest first within the subscription. It is /// dropped, as a datagram may be anywhere, if its body doesn't fit the transport's /// datagram size or the transport has no room for it now. - fn send(&self, datagram: crate::datagram::Datagram) { + /// + /// Fails on a sequence the version's varints cannot carry (2^62 and up before lite-07): + /// every datagram its source produces later is at least as far, so the subscription can + /// deliver no more. One the network reordered below it is lost, as any datagram may be. + fn send(&self, datagram: crate::datagram::Datagram) -> Result<(), Error> { let Ok(timestamp) = self .stamp .map(|stamp| stamp.wire(datagram.timestamp, &self.runtime)) .transpose() else { - return; + return Ok(()); }; let sequence = datagram.sequence; let body = lite::Datagram { @@ -2965,19 +2968,18 @@ impl DatagramSend { }; // The stamp is set wherever the version needs a timestamp, so this never hits a // version guard. - let Ok(body) = body.encode_bytes(self.version) else { - return; - }; + let body = body.encode_bytes(self.version)?; let max = self.session.max_datagram_size().min(lite::Datagram::MAX_SIZE); if body.len() > max { tracing::debug!(sequence, size = body.len(), max, "dropping oversized datagram"); - return; + return Ok(()); } let options = SendOptions { group: self.group.as_ref(), priority: crate::priority::in_group(sequence, 0, Order::Descending), }; let _ = self.session.send_datagram(body, options); + Ok(()) } } @@ -3061,7 +3063,7 @@ impl Request for DatagramServe { let send = self.send.as_ref().expect("set above"); match ready!(self.consumer.poll_recv(waiter))? { Some(datagram) => { - send.send(datagram); + send.send(datagram)?; Poll::Ready(Ok(ControlFlow::Continue(()))) } None => Poll::Ready(Ok(ControlFlow::Break(()))), @@ -5291,20 +5293,13 @@ impl TrackRun { // drop again is judged again too, since these terms may serve it, and so is a group // one re-offered that has not opened yet, since they may no longer admit it. for group in std::mem::take(&mut self.reoffered) { - if let Some(end) = group.sequence.checked_add(1) { - self.expired.insert(group.sequence..end); - } + self.expired.insert(group.sequence..group.sequence + 1); } let pending = std::mem::take(&mut self.redrop); self.expired.extend(pending.iter().cloned()); for run in std::mem::take(&mut self.expired).iter() { let (groups, gone) = self.track.reoffer_groups(run.clone()); - self.owe( - groups - .iter() - .filter_map(|group| Some(group.sequence..group.sequence.checked_add(1)?)) - .collect(), - ); + self.owe(groups.iter().map(|group| group.sequence..group.sequence + 1).collect()); self.reoffered.extend(groups); self.redrop.extend(gone.iter().cloned()); } @@ -5472,24 +5467,22 @@ impl TrackRun { // A stream expired under this subscription's budget is a stale verdict. let hole = match err { StreamError::Old => { - if self.ctx.version.has_skip() - && let Some(end) = sequence.checked_add(1) - { - self.expired.insert(sequence..end); - self.sent_stale(sequence..end); + if self.ctx.version.has_skip() { + self.expired.insert(sequence..sequence + 1); + self.sent_stale(sequence..sequence + 1); } Hole::stale(self.track.budget()) } err => Hole::drop(err), }; - writer.buffer(&self.hole(sequence..=sequence, &hole))?; + writer.buffer(&self.hole(sequence..sequence + 1, &hole))?; } return Poll::Ready(Ok(ControlFlow::Continue(()))); } if !self.redrop.is_empty() { let hole = Hole::stale(self.track.budget()); for run in std::mem::take(&mut self.redrop).iter() { - writer.buffer(&self.hole(run.start..=run.end - 1, &hole))?; + writer.buffer(&self.hole(run.clone(), &hole))?; self.expired.insert(run.clone()); self.sent_stale(run.clone()); // A re-offer an update owed again is given up now, so the end sweep never names it. @@ -5572,9 +5565,7 @@ impl TrackRun { match position_group(group, &self.frames) { Some(group) => self.serve(group), None => { - if let Some(end) = sequence.checked_add(1) { - self.drop_range(sequence..end, &Hole::drop(StreamError::NotFound), writer)?; - } + self.drop_range(sequence..sequence + 1, &Hole::drop(StreamError::NotFound), writer)?; } } return Poll::Ready(Ok(ControlFlow::Continue(()))); @@ -5595,10 +5586,8 @@ impl TrackRun { // group handed out after one is served, as one a route the front switched to // delivers: the update that reopens the drop would never re-offer it. let sequence = group.sequence; - if self.dropped_stale.contains(&sequence) - && let Some(end) = sequence.checked_add(1) - { - self.replace_stale(sequence..end); + if self.dropped_stale.contains(&sequence) { + self.replace_stale(sequence..sequence + 1); } else if self.served.as_ref().is_some_and(|served| served.contains(&sequence)) { return Poll::Ready(Ok(ControlFlow::Continue(()))); } @@ -5608,15 +5597,11 @@ impl TrackRun { // only be reset; the next servable group resolves the start. tracing::debug!(subscribe = self.ctx.id, track = %self.ctx.track_name, sequence, "skipping group with a missing head"); if self.emit_range && self.start.is_none() { - // At u64::MAX no later group can resolve a start past this one. - if let Some(end) = sequence.checked_add(1) { - self.skipped.insert(sequence..end, Hole::drop(StreamError::NotFound)); - } - } else if self.start.is_some() - && let Some(end) = sequence.checked_add(1) - { + self.skipped + .insert(sequence..sequence + 1, Hole::drop(StreamError::NotFound)); + } else if self.start.is_some() { // Lite-05+ names it now; a no-op on other versions. - self.drop_range(sequence..end, &Hole::drop(StreamError::NotFound), writer)?; + self.drop_range(sequence..sequence + 1, &Hole::drop(StreamError::NotFound), writer)?; } return Poll::Ready(Ok(ControlFlow::Continue(()))); }; @@ -5738,9 +5723,7 @@ impl TrackRun { let Some(served) = &mut self.served else { return; }; - if let Some(next) = sequence.checked_add(1) { - served.insert(sequence..next); - } + served.insert(sequence..sequence + 1); } /// Forward a verdict the cursor reached on `range`, as [`Self::drop_range`] does. On lite-07 @@ -5832,7 +5815,7 @@ impl TrackRun { } served.extend(gaps.iter().cloned()); for gap in gaps.iter() { - let msg = self.hole(gap.start..=gap.end - 1, hole); + let msg = self.hole(gap.clone(), hole); writer.buffer(&msg)?; } Ok(!gaps.is_empty()) @@ -5840,13 +5823,10 @@ impl TrackRun { /// The message naming `groups` given up as `hole`: lite-07 skips what was never /// produced, and earlier versions drop it as not found. - fn hole(&self, groups: std::ops::RangeInclusive, hole: &Hole) -> lite::SubscribeResponse { + fn hole(&self, groups: std::ops::Range, hole: &Hole) -> lite::SubscribeResponse { let version = self.ctx.version; match hole { - Hole::Skip if version.has_skip() => lite::SubscribeResponse::Skip(lite::SubscribeSkip { - start: *groups.start(), - end: *groups.end(), - }), + Hole::Skip if version.has_skip() => lite::SubscribeResponse::Skip(lite::SubscribeSkip { groups }), hole => { lite::SubscribeResponse::Drop(lite::SubscribeDrop::new(groups, &hole.error(), self.update, version)) } @@ -7511,11 +7491,13 @@ mod serve_group_test { let log = session.log.clone(); // Lite-07's type adds one byte to the three one-byte fields. let header = if version.has_padding() { 4 } else { 3 }; - datagram_send(version, session).send(crate::datagram::Datagram { - sequence: 1, - timestamp: Some(Timestamp::ZERO), - payload: bytes::Bytes::from(vec![0; size - header]), - }); + datagram_send(version, session) + .send(crate::datagram::Datagram { + sequence: 1, + timestamp: Some(Timestamp::ZERO), + payload: bytes::Bytes::from(vec![0; size - header]), + }) + .unwrap(); assert_eq!( log.datagrams.lock().unwrap().len(), usize::from(size <= transport.min(1200)), @@ -7526,6 +7508,23 @@ mod serve_group_test { } } + /// A sequence past QUIC's varints fails the send before lite-07, which carries any. + #[kio::test] + async fn a_datagram_past_the_wire_s_sequences_fails() { + for version in [Version::Lite05, Version::Lite06, Version::Lite07] { + let session = SinkSession::new(Log::default()).with_datagrams(1200); + let log = session.log.clone(); + let sent = datagram_send(version, session).send(crate::datagram::Datagram { + sequence: 1 << 62, + timestamp: Some(Timestamp::ZERO), + payload: bytes::Bytes::from_static(b"d"), + }); + let carried = version == Version::Lite07; + assert_eq!(sent.is_ok(), carried, "{version}"); + assert_eq!(log.datagrams.lock().unwrap().len(), usize::from(carried), "{version}"); + } + } + /// A datagram goes in its subscription's send group, newest first. #[kio::test] async fn datagrams_rank_within_their_subscription() { @@ -7537,7 +7536,8 @@ mod serve_group_test { sequence, timestamp: Some(Timestamp::ZERO), payload: bytes::Bytes::from_static(b"d"), - }); + }) + .unwrap(); } assert_eq!( log.datagram_ranks(), @@ -7547,11 +7547,13 @@ mod serve_group_test { // Without send groups, the rank goes alone. let session = SinkSession::new(Log::default()).with_datagrams(1200); let log = session.log.clone(); - datagram_send(Version::Lite07, session).send(crate::datagram::Datagram { - sequence: 4, - timestamp: Some(Timestamp::ZERO), - payload: bytes::Bytes::from_static(b"d"), - }); + datagram_send(Version::Lite07, session) + .send(crate::datagram::Datagram { + sequence: 4, + timestamp: Some(Timestamp::ZERO), + payload: bytes::Bytes::from_static(b"d"), + }) + .unwrap(); assert_eq!( log.datagram_ranks(), [(None, crate::priority::in_group(4, 0, Order::Descending))] @@ -8036,14 +8038,14 @@ mod serve_group_test { let (msg, size) = lite::SubscribeResponse::decode_slice(buf, version).unwrap(); buf = &buf[size..]; match msg { - lite::SubscribeResponse::Skip(skip) => holes.push(("skip", skip.start, skip.end)), - lite::SubscribeResponse::Drop(drop) => holes.push(("drop", drop.start, drop.end)), + lite::SubscribeResponse::Skip(skip) => holes.push(("skip", skip.groups)), + lite::SubscribeResponse::Drop(drop) => holes.push(("drop", drop.groups)), _ => {} } } let expected = match version.has_skip() { - true => vec![("drop", 1, 2), ("skip", 1, 2)], - false => vec![("drop", 1, 2)], + true => vec![("drop", 1..3), ("skip", 1..3)], + false => vec![("drop", 1..3)], }; assert_eq!(holes, expected, "{version}"); } @@ -8076,12 +8078,12 @@ mod serve_group_test { let (msg, size) = lite::SubscribeResponse::decode_slice(buf, Version::Lite07).unwrap(); buf = &buf[size..]; match msg { - lite::SubscribeResponse::Skip(skip) => skips.push((skip.start, skip.end)), + lite::SubscribeResponse::Skip(skip) => skips.push((skip.groups.start, skip.groups.end)), lite::SubscribeResponse::Drop(_) => drops += 1, _ => {} } } - assert_eq!((skips, drops), (vec![(1, FAR - 1)], 0)); + assert_eq!((skips, drops), (vec![(1, FAR)], 0)); } /// A relay that holds only the first group of a backlog answers with the largest its @@ -8115,7 +8117,8 @@ mod serve_group_test { ); } - /// The SUBSCRIBE_DROP ranges a run loop's subscribe stream carried, once flushed. + /// The SUBSCRIBE_DROP ranges a run loop's subscribe stream carried, once flushed, each as + /// its first and last group. async fn drops( writer: &mut Writer, log: &Log, @@ -8130,14 +8133,14 @@ mod serve_group_test { let (msg, size) = lite::SubscribeResponse::decode_slice(buf, version).unwrap(); buf = &buf[size..]; if let lite::SubscribeResponse::Drop(drop) = msg { - drops.push((drop.start, drop.end)); + drops.push((drop.groups.start, drop.groups.end - 1)); } } drops } - /// The SUBSCRIBE_DROP ranges a run loop's subscribe stream carried, once flushed, with the - /// update each names. + /// The SUBSCRIBE_DROP ranges a run loop's subscribe stream carried, once flushed, each as + /// its first and last group with the update it names. async fn drop_updates( writer: &mut Writer, log: &Log, @@ -8151,7 +8154,7 @@ mod serve_group_test { let (msg, size) = lite::SubscribeResponse::decode_slice(buf, version).unwrap(); buf = &buf[size..]; if let lite::SubscribeResponse::Drop(drop) = msg { - drops.push((drop.start, drop.end, drop.update)); + drops.push((drop.groups.start, drop.groups.end - 1, drop.update)); } } drops @@ -8927,29 +8930,6 @@ mod serve_group_test { assert_eq!(drops(&mut writer, &log, version).await, [(1, 1)]); } - /// A missing head at the model's largest sequence has no successor to name. - #[kio::test] - async fn a_missing_head_at_the_maximum_sequence_does_not_panic() { - let track = track::Producer::new( - Arc::new(broadcast::Info::default()), - "test", - crate::track::Info::timed(), - ); - let subscriber = track.subscribe( - track::Subscription::default().with_delay(track::Delay::default().with_max(Duration::from_secs(60))), - ); - let mut group = track.create_group(group::Info { sequence: u64::MAX }).unwrap(); - group.start_at(1).unwrap(); - group.write_frame(Timestamp::ZERO, b"x".as_slice()).unwrap(); - group.finish().unwrap(); - let (mut run, mut writer, _) = lite_run(Version::Lite07, SinkSession::new(Log::default()), subscriber); - assert!( - kio::wait(|waiter| run.poll(&mut writer, waiter)) - .now_or_never() - .is_none() - ); - } - /// A long-budget reader warms the relay without changing a live reader's resolved start. #[kio::test] async fn cold_and_warm_relays_resolve_the_same_start() { @@ -9759,8 +9739,9 @@ mod serve_group_test { assert!(futures::poll!(run.as_mut()).is_pending(), "group 1 is still opening"); assert_eq!( *log.writes.lock().unwrap(), - // The DROP carries OLD (0x34) and the SUBSCRIBE's update, 0. - [0, 4, 1, 0, 1, 1, 2, 4, 0, 0, 0x34, 0, 1, 2, 2, 0], + // The DROP names group 0 as a start and count, with OLD (0x34) and the SUBSCRIBE's + // update, 0. + [0, 4, 1, 0, 1, 1, 2, 4, 0, 1, 0x34, 0, 1, 2, 2, 0], "the expired group is dropped and the end precedes stream credit" ); @@ -9772,7 +9753,7 @@ mod serve_group_test { assert!(futures::poll!(run.as_mut()).is_pending(), "the stream stays open"); assert_eq!( *log.writes.lock().unwrap(), - [0, 4, 1, 0, 1, 1, 2, 4, 0, 0, 0x34, 0, 1, 2, 2, 0] + [0, 4, 1, 0, 1, 1, 2, 4, 0, 1, 0x34, 0, 1, 2, 2, 0] ); } } diff --git a/rs/moq-net/src/lite/subscribe.rs b/rs/moq-net/src/lite/subscribe.rs index 94916399a23..5c4c5f5857d 100644 --- a/rs/moq-net/src/lite/subscribe.rs +++ b/rs/moq-net/src/lite/subscribe.rs @@ -1038,18 +1038,12 @@ impl<'a> Message<'a> for SubscribeStarted { /// Names groups that existed but will not be delivered: aborted or reset, evicted or /// expired with no copy left, or stale. /// -/// The range `[start, end]` is inclusive on both ends. For example, -/// `start = 5, end = 7` means groups 5, 6, and 7 were dropped. -/// /// Lite03+; publishers send it on Lite05 and later. Before lite-07 it also names sequences /// declared skipped, which lite-07 names in [`SubscribeSkip`]. #[derive(Clone, Debug, PartialEq, Eq)] pub struct SubscribeDrop { - /// The first absolute group sequence in the dropped range. - pub start: u64, - - /// The last absolute group sequence in the dropped range (inclusive). - pub end: u64, + /// The dropped group sequences. + pub groups: std::ops::Range, /// Why the groups were given up: a stream error code on lite-07 and later, or an /// application-specific code before, where 0 means simply unavailable. @@ -1065,10 +1059,9 @@ pub struct SubscribeDrop { impl SubscribeDrop { /// Name `groups` given up with `err` under the terms numbered `update`, as `version` /// carries it. - pub fn new(groups: std::ops::RangeInclusive, err: &StreamError, update: u64, version: Version) -> Self { + pub fn new(groups: std::ops::Range, err: &StreamError, update: u64, version: Version) -> Self { Self { - start: *groups.start(), - end: *groups.end(), + groups, // Before lite-07 the code is the application's, so it says nothing of why. error: match version.has_drop_code() { true => version.encode_stream_code(err).into(), @@ -1091,6 +1084,30 @@ impl SubscribeDrop { } } +/// A SUBSCRIBE_DROP or SUBSCRIBE_SKIP range: `Group Start` and `Group Count` on lite-07, an +/// inclusive `Group Start` and `Group End` before. Either way it ends by the reserved +/// sequence `u64::MAX`, so it never names that group. +fn decode_groups(r: &mut Decoder<'_>, version: Version) -> Result, DecodeError> { + let start = r.varint()?; + let end = match version.has_group_count() { + true => start.checked_add(r.varint()?), + false => r.varint()?.checked_add(1).filter(|end| *end >= start), + }; + Ok(start..end.ok_or(DecodeError::InvalidValue)?) +} + +fn encode_groups(w: &mut Encoder<'_>, groups: &std::ops::Range, version: Version) -> Result<(), EncodeError> { + if groups.start > groups.end { + return Err(EncodeError::InvalidState); + } + w.varint(groups.start)?; + match version.has_group_count() { + true => w.varint(groups.end - groups.start), + // An empty range at 0 has no inclusive end to spell. + false => w.varint(groups.end.checked_sub(1).ok_or(EncodeError::InvalidState)?), + } +} + impl<'a> Message<'a> for SubscribeDrop { const CONTROL: Option = Some(crate::stats::Message::Subscribe); fn decode_msg(r: &mut Decoder<'a>, version: Version) -> Result { @@ -1101,18 +1118,10 @@ impl<'a> Message<'a> for SubscribeDrop { _ => {} } - let (start, end) = (r.varint()?, r.varint()?); - if start.saturating_sub(end) > 1 { - return Err(DecodeError::InvalidValue); - } + let groups = decode_groups(r, version)?; let error = r.varint()?; let update = decode_update(r, version)?; - Ok(Self { - start, - end, - error, - update, - }) + Ok(Self { groups, error, update }) } fn encode_msg(&self, w: &mut Encoder<'_>, version: Version) -> Result<(), EncodeError> { @@ -1123,12 +1132,7 @@ impl<'a> Message<'a> for SubscribeDrop { _ => {} } - if self.start.saturating_sub(self.end) > 1 { - return Err(EncodeError::InvalidState); - } - - w.varint(self.start)?; - w.varint(self.end)?; + encode_groups(w, &self.groups, version)?; w.varint(self.error)?; encode_update(w, version, self.update)?; @@ -1139,15 +1143,11 @@ impl<'a> Message<'a> for SubscribeDrop { /// Names sequences the publisher declared it will never produce (see /// `track::Producer::skip_groups`): final, with no error, ending no reader. /// -/// The range `[start, end]` is inclusive on both ends. Lite07+ only; earlier versions name -/// them in a [`SubscribeDrop`]. +/// Lite07+ only; earlier versions name them in a [`SubscribeDrop`]. #[derive(Clone, Debug, PartialEq, Eq)] pub struct SubscribeSkip { - /// The first absolute group sequence in the skipped range. - pub start: u64, - - /// The last absolute group sequence in the skipped range (inclusive). - pub end: u64, + /// The skipped group sequences. + pub groups: std::ops::Range, } impl<'a> Message<'a> for SubscribeSkip { @@ -1156,26 +1156,16 @@ impl<'a> Message<'a> for SubscribeSkip { if !version.has_skip() { return Err(DecodeError::Version); } - let msg = Self { - start: r.varint()?, - end: r.varint()?, - }; - if msg.start.saturating_sub(msg.end) > 1 { - return Err(DecodeError::InvalidValue); - } - Ok(msg) + Ok(Self { + groups: decode_groups(r, version)?, + }) } fn encode_msg(&self, w: &mut Encoder<'_>, version: Version) -> Result<(), EncodeError> { if !version.has_skip() { return Err(EncodeError::Version); } - if self.start.saturating_sub(self.end) > 1 { - return Err(EncodeError::InvalidState); - } - w.varint(self.start)?; - w.varint(self.end)?; - Ok(()) + encode_groups(w, &self.groups, version) } } @@ -1267,42 +1257,65 @@ impl<'a> Decode<'a, Version> for SubscribeResponse { mod test { use super::*; + /// Before lite-07 a range is an inclusive Group Start and Group End, refused reversed. #[test] - fn drop_ranges_refuse_reversed_and_allow_empty_or_maximum_ends() { - for version in [Version::Lite05, Version::Lite06, Version::Lite07] { + fn drop_ranges_before_lite07_are_inclusive() { + for version in [Version::Lite05, Version::Lite06] { + // Group Start 3, Group End 1. assert!(matches!( SubscribeDrop::decode_slice(&[3, 3, 1, 0], version), Err(DecodeError::InvalidValue) )); - assert!( - SubscribeDrop { - start: 3, - end: 1, - error: 0, - update: 0, - } - .encode_bytes(version) - .is_err() - ); - let max = if version == Version::Lite07 { - u64::MAX - } else { - (1 << 62) - 1 - }; - for (start, end) in [(2, 1), (max, max)] { + // Group Start 3, Group End 2: empty. + let (decoded, _) = SubscribeDrop::decode_slice(&[3, 3, 2, 0], version).unwrap(); + assert_eq!(decoded.groups, 3..3); + let max = (1 << 62) - 1; + for groups in [2..2, 1..4, max..max + 1] { let msg = SubscribeDrop { - start, - end, + groups: groups.clone(), error: 0, update: 0, }; let data = msg.encode_bytes(version).unwrap(); - let (decoded, _) = SubscribeDrop::decode_slice(&data, version).unwrap(); - assert_eq!((decoded.start, decoded.end), (start, end)); + assert_eq!(SubscribeDrop::decode_slice(&data, version).unwrap().0.groups, groups); } } } + /// Lite-07 carries Group Start and Group Count, which reach but never pass the reserved + /// group `u64::MAX`. + #[test] + fn skip_ranges_on_lite07_count_up_to_the_reserved_group() { + for groups in [0..0, 3..4, 0..u64::MAX, u64::MAX..u64::MAX] { + let msg = SubscribeSkip { groups: groups.clone() }; + let data = msg.encode_bytes(Version::Lite07).unwrap(); + assert_eq!( + SubscribeSkip::decode_slice(&data, Version::Lite07).unwrap().0.groups, + groups + ); + } + // Group Start 2^64-1, Group Count 1. + let mut data = SubscribeSkip { + groups: u64::MAX..u64::MAX, + } + .encode_bytes(Version::Lite07) + .unwrap() + .to_vec(); + *data.last_mut().unwrap() = 1; + assert!(matches!( + SubscribeSkip::decode_slice(&data, Version::Lite07), + Err(DecodeError::InvalidValue) + )); + for version in [Version::Lite06, Version::Lite07] { + let reversed = SubscribeDrop { + groups: std::ops::Range { start: 3, end: 1 }, + error: 0, + update: 0, + }; + assert!(reversed.encode_bytes(version).is_err()); + } + } + #[test] fn subscribe_start_roundtrips_on_lite05() { let resp = SubscribeResponse::Start(SubscribeStart { @@ -1412,22 +1425,21 @@ mod test { #[test] fn subscribe_drop_is_restored_on_lite07() { let resp = SubscribeResponse::Drop(SubscribeDrop { - start: 1, - end: 3, + groups: 1..4, error: 7, update: 0, }); let mut buf = Vec::new(); resp.encode(&mut Encoder::new(&mut buf, Version::Lite07.into()), Version::Lite07) .unwrap(); - // The drop names the SUBSCRIBE's update, 0. + // Groups 1 to 3 as a start and count; the drop names the SUBSCRIBE's update, 0. assert_eq!(buf, [2, 4, 1, 3, 7, 0]); match crate::coding::decode_buf(&mut buf.as_slice(), Version::Lite07, |r, v| { SubscribeResponse::decode(r, v) }) .unwrap() { - SubscribeResponse::Drop(drop) => assert_eq!((drop.start, drop.end, drop.error), (1, 3, 7)), + SubscribeResponse::Drop(drop) => assert_eq!((drop.groups, drop.error), (1..4, 7)), other => panic!("expected Drop, got {other:?}"), } } @@ -1436,13 +1448,12 @@ mod test { #[test] fn a_drop_names_its_update_on_lite07() { let msg = SubscribeDrop { - start: 4, - end: 4, + groups: 4..5, error: 0x34, update: 2, }; let buf = msg.encode_bytes(Version::Lite07).unwrap(); - assert_eq!(buf.as_ref(), [4, 4, 4, 0x34, 2]); + assert_eq!(buf.as_ref(), [4, 4, 1, 0x34, 2]); let (decoded, _) = SubscribeDrop::decode_slice(&buf, Version::Lite07).unwrap(); assert_eq!(decoded, msg); let msg = SubscribeDrop { error: 0, ..msg }; @@ -1455,17 +1466,13 @@ mod test { /// SUBSCRIBE_SKIP is type 3 on lite-07 and unknown before it. #[test] fn subscribe_skip_is_lite07_only() { - let resp = SubscribeResponse::Skip(SubscribeSkip { start: 1, end: 3 }); + let resp = SubscribeResponse::Skip(SubscribeSkip { groups: 1..4 }); let buf = resp.encode_bytes(Version::Lite07).unwrap(); assert_eq!(buf.as_ref(), [3, 2, 1, 3]); match SubscribeResponse::decode_slice(&buf, Version::Lite07).unwrap().0 { - SubscribeResponse::Skip(skip) => assert_eq!(skip, SubscribeSkip { start: 1, end: 3 }), + SubscribeResponse::Skip(skip) => assert_eq!(skip, SubscribeSkip { groups: 1..4 }), other => panic!("expected Skip, got {other:?}"), } - assert!(matches!( - SubscribeSkip::decode_slice(&[2, 3, 1], Version::Lite07), - Err(DecodeError::InvalidValue) - )); assert!(resp.encode_bytes(Version::Lite06).is_err()); assert!(matches!( SubscribeResponse::decode_slice(&buf, Version::Lite06), @@ -1488,8 +1495,7 @@ mod test { #[test] fn subscribe_drop_is_type_2_on_lite05() { let resp = SubscribeResponse::Drop(SubscribeDrop { - start: 1, - end: 3, + groups: 1..4, error: 0, update: 0, }); @@ -1501,7 +1507,7 @@ mod test { let mut slice = buf.as_slice(); match crate::coding::decode_buf(&mut slice, Version::Lite05, |r, v| SubscribeResponse::decode(r, v)).unwrap() { - SubscribeResponse::Drop(drop) => assert_eq!((drop.start, drop.end), (1, 3)), + SubscribeResponse::Drop(drop) => assert_eq!(drop.groups, 1..4), other => panic!("expected Drop, got {other:?}"), } } @@ -1509,8 +1515,7 @@ mod test { #[test] fn subscribe_drop_is_type_1_on_lite04() { let resp = SubscribeResponse::Drop(SubscribeDrop { - start: 1, - end: 3, + groups: 1..4, error: 0, update: 0, }); diff --git a/rs/moq-net/src/lite/subscriber.rs b/rs/moq-net/src/lite/subscriber.rs index 2b261ec5b32..3ee1fe86406 100644 --- a/rs/moq-net/src/lite/subscriber.rs +++ b/rs/moq-net/src/lite/subscriber.rs @@ -3248,10 +3248,10 @@ mod tests { let mut fetches = FeedFetches::new(&clock); fetches.push(req, &track.consume()); arrive(&track, &tail, 2, start); - let late = start + crate::tail::GRACE / 2; + let late = start.saturating_add(crate::tail::GRACE / 2); fetches.poll(&sub, late, &kio::Waiter::noop()); assert_eq!(fetches.held.len(), 1, "group 2 alone does not give up on group 1"); - assert_eq!(fetches.fold.deadline(), Some(start + crate::tail::GRACE)); + assert_eq!(fetches.fold.deadline(), Some(start.saturating_add(crate::tail::GRACE))); arrive(&track, &tail, 1, late); fetches.poll(&sub, late, &kio::Waiter::noop()); @@ -3276,7 +3276,7 @@ mod tests { let mut fetches = FeedFetches::new(&clock); fetches.push(req, &track.consume()); - fetches.poll(&sub, start + crate::tail::GRACE, &kio::Waiter::noop()); + fetches.poll(&sub, start.saturating_add(crate::tail::GRACE), &kio::Waiter::noop()); assert!(fetches.held.is_empty()); assert!(matches!(fetching.now_or_never(), Some(Err(Error::NotFound)))); } @@ -3407,9 +3407,9 @@ mod tests { fetches.poll(&sub, start, &waiter); assert!(fetches.held.is_empty()); arrive(&track, &tail, 200, start); - fetches.poll(&sub, start + crate::tail::GRACE, &waiter); + fetches.poll(&sub, start.saturating_add(crate::tail::GRACE), &waiter); wakes.0.store(0, atomic::Ordering::Relaxed); - fetches.poll(&sub, start + crate::tail::GRACE, &waiter); + fetches.poll(&sub, start.saturating_add(crate::tail::GRACE), &waiter); assert_eq!( wakes.0.load(atomic::Ordering::Relaxed), 0, @@ -3443,7 +3443,7 @@ mod tests { fetches.poll(&sub, start, &waiter); assert_eq!(fetches.polled - polled, 1, "an arrival touches its group alone"); assert_eq!(fetches.held.len(), 31); - assert_eq!(fetches.fold.deadline(), Some(start + crate::tail::GRACE)); + assert_eq!(fetches.fold.deadline(), Some(start.saturating_add(crate::tail::GRACE))); } #[kio::test] @@ -3460,17 +3460,21 @@ mod tests { arrive(&track, &tail, 0, start); arrive(&track, &tail, 2, start); kio::clock::sleep(crate::tail::GRACE / 2).await; - arrive(&track, &tail, 4, start + crate::tail::GRACE / 2); + arrive(&track, &tail, 4, start.saturating_add(crate::tail::GRACE / 2)); let waiter = kio::Waiter::noop(); fetches.poll(&sub, start, &waiter); let polled = fetches.polled; - fetches.poll(&sub, start + crate::tail::GRACE, &waiter); + fetches.poll(&sub, start.saturating_add(crate::tail::GRACE), &waiter); assert_eq!(fetches.polled - polled, 1); assert!(!fetches.held.contains_key(&1)); assert_eq!(fetches.held.len(), 3); assert_eq!( fetches.fold.deadline(), - Some(start + crate::tail::GRACE + crate::tail::GRACE / 2) + Some( + start + .saturating_add(crate::tail::GRACE) + .saturating_add(crate::tail::GRACE / 2) + ) ); } @@ -4391,61 +4395,65 @@ mod tests { } } + /// Serve one Group Stream for `sequence` on subscription 7, accepted into `track`. + async fn serve_group(version: Version, sequence: u64, track: &track::Producer) -> Result<(), Error> { + use crate::transport::poll::Session as _; + + let mut script = Vec::new(); + lite::Group { + subscribe: 7, + sequence, + frame_start: 0, + } + .encode(&mut crate::coding::Encoder::new(&mut script, version.into()), version) + .unwrap(); + let session = crate::lite::test_transport::ScriptedSession::eof(script); + let subscriber = Subscriber::new(SubscriberConfig { + runtime: crate::time::sim(), + session: crate::driver::Transport::new(session.clone()), + origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), + recv_bandwidth: None, + version, + peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Address::Setup), + peer_hop: None, + cost: None, + going_away: Default::default(), + auth: crate::auth::Link::new(false), + }); + subscriber.subscribes.lock().insert( + 7, + TrackEntry::accepted( + track.clone(), + lite::Framing { + timescale: Some(Timescale::MILLI), + ietf: None, + compressed: false, + }, + Default::default(), + ), + ); + + let (_, recv) = session.open_bi(Default::default()).await.unwrap(); + let mut group = GroupRecv::new( + subscriber, + Reader::new(crate::transport::boxed::RecvStream::new(recv), version), + ); + kio::wait(|waiter| group.poll_serve(waiter)).await + } + /// A group at or past the end the publisher declared contradicts that end, which no later /// stream can repair, so the whole track fails rather than ending clean without it. lite-05 /// specified an inclusive end, so there it costs only that group's stream. #[kio::test] async fn a_group_past_the_declared_end_aborts_the_track() { - use crate::transport::poll::Session as _; - for version in [Version::Lite05, Version::Lite06, Version::Lite07] { - let mut script = Vec::new(); - lite::Group { - subscribe: 7, - sequence: 3, - frame_start: 0, - } - .encode(&mut crate::coding::Encoder::new(&mut script, version.into()), version) - .unwrap(); - let session = crate::lite::test_transport::ScriptedSession::eof(script); - let subscriber = Subscriber::new(SubscriberConfig { - runtime: crate::time::sim(), - session: crate::driver::Transport::new(session.clone()), - origin: origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(), - recv_bandwidth: None, - version, - peer_setup: crate::lite::PeerSetup::new(false, crate::transport::Address::Setup), - peer_hop: None, - cost: None, - going_away: Default::default(), - auth: crate::auth::Link::new(false), - }); - let mut track = track::Producer::new( std::sync::Arc::new(crate::broadcast::Info::default()), "video", crate::track::Info::timed(), ); track.finish_at(Position::group(3), None).unwrap(); - subscriber.subscribes.lock().insert( - 7, - TrackEntry::accepted( - track.clone(), - lite::Framing { - timescale: Some(Timescale::MILLI), - ietf: None, - compressed: false, - }, - Default::default(), - ), - ); - - let (_, recv) = session.open_bi(Default::default()).await.unwrap(); - let mut group = GroupRecv::new( - subscriber, - Reader::new(crate::transport::boxed::RecvStream::new(recv), version), - ); - let res = kio::wait(|waiter| group.poll_serve(waiter)).await; + let res = serve_group(version, 3, &track).await; match version { Version::Lite05 => { assert!(matches!(res, Err(Error::Closed)), "{version:?}: {res:?}"); @@ -4465,6 +4473,20 @@ mod tests { } } + /// Group `u64::MAX` is reserved, so a stream naming it is refused, and the track lives on. + #[kio::test] + async fn a_group_at_the_reserved_sequence_is_refused() { + let track = track::Producer::new( + std::sync::Arc::new(crate::broadcast::Info::default()), + "video", + crate::track::Info::timed(), + ); + let res = serve_group(Version::Lite07, u64::MAX, &track).await; + assert!(matches!(res, Err(Error::BoundsExceeded(_))), "{res:?}"); + assert!(track.closed().now_or_never().is_none()); + assert_eq!(track.latest_sequence(), None); + } + /// A track in `timescale` that a draft-18 moq-transport publisher published. fn draft18(timescale: Option) -> lite::Framing { lite::Framing { @@ -5304,8 +5326,7 @@ mod tests { async fn a_drop_naming_an_unsent_update_is_a_protocol_violation() { let (serve, mut serving, tail, _broadcast) = lite07_serving(Duration::from_millis(500)).await; let drop = lite::SubscribeResponse::Drop(lite::SubscribeDrop { - start: 1, - end: 2, + groups: 1..3, error: u64::from(crate::coding::StreamCodes::encode_stream_code( &Version::Lite07, &crate::StreamError::Old, @@ -5336,10 +5357,9 @@ mod tests { ); let waiter = kio::Waiter::noop(); let code = |err: &crate::StreamError| u64::from(crate::coding::StreamCodes::encode_stream_code(&version, err)); - let drop = |start, end, err: &crate::StreamError, update| { + let drop = |first, last: u64, err: &crate::StreamError, update| { lite::SubscribeResponse::Drop(lite::SubscribeDrop { - start, - end, + groups: first..last + 1, error: code(err), update, }) @@ -5409,10 +5429,9 @@ mod tests { &version, &crate::StreamError::Old, )); - let old = |sequence| { + let old = |sequence: u64| { lite::SubscribeResponse::Drop(lite::SubscribeDrop { - start: sequence, - end: sequence, + groups: sequence..sequence + 1, error: code, update: 0, }) @@ -5466,10 +5485,9 @@ mod tests { &version, &crate::StreamError::Old, )); - let old = |sequence, update| { + let old = |sequence: u64, update| { lite::SubscribeResponse::Drop(lite::SubscribeDrop { - start: sequence, - end: sequence, + groups: sequence..sequence + 1, error: code, update, }) @@ -5548,10 +5566,9 @@ mod tests { &version, &crate::StreamError::Old, )); - let old = |start, end| { + let old = |first, last: u64| { lite::SubscribeResponse::Drop(lite::SubscribeDrop { - start, - end, + groups: first..last + 1, error: code, update: 0, }) @@ -5563,13 +5580,13 @@ mod tests { serving .apply_response( &serve, - lite::SubscribeResponse::Skip(lite::SubscribeSkip { start: 1, end: 2 }), + lite::SubscribeResponse::Skip(lite::SubscribeSkip { groups: 1..3 }), ) .unwrap(); serving .apply_response( &serve, - lite::SubscribeResponse::Drop(lite::SubscribeDrop::new(4..=4, &crate::StreamError::App(5), 0, version)), + lite::SubscribeResponse::Drop(lite::SubscribeDrop::new(4..5, &crate::StreamError::App(5), 0, version)), ) .unwrap(); // Empty ranges. @@ -5577,7 +5594,7 @@ mod tests { serving .apply_response( &serve, - lite::SubscribeResponse::Skip(lite::SubscribeSkip { start: 6, end: 5 }), + lite::SubscribeResponse::Skip(lite::SubscribeSkip { groups: 6..6 }), ) .unwrap(); @@ -5606,10 +5623,14 @@ mod tests { async fn a_skip_replaces_a_final_drop_but_not_a_cached_group() { let version = Version::Lite07; let (serve, mut serving, tail, _broadcast) = lite07_serving(Duration::from_millis(500)).await; - let drop = |start, end, error: &crate::StreamError| { - lite::SubscribeResponse::Drop(lite::SubscribeDrop::new(start..=end, error, 0, version)) + let drop = |first, last: u64, error: &crate::StreamError| { + lite::SubscribeResponse::Drop(lite::SubscribeDrop::new(first..last + 1, error, 0, version)) + }; + let skip = |first, last: u64| { + lite::SubscribeResponse::Skip(lite::SubscribeSkip { + groups: first..last + 1, + }) }; - let skip = |start, end| lite::SubscribeResponse::Skip(lite::SubscribeSkip { start, end }); let mut group = serving .serving .create_group(crate::group::Info { sequence: 5 }) @@ -5670,8 +5691,7 @@ mod tests { starts: vec![Some(0)], }), lite::SubscribeResponse::Drop(lite::SubscribeDrop { - start: 2, - end: 2, + groups: 2..3, error: code.into(), update: 0, }), @@ -11774,8 +11794,7 @@ impl ServeLoop { if dropped.update > active.update { return Err(Error::ProtocolViolation); } - let groups = dropped.start..dropped.end.saturating_add(1); - // An empty range (Group Start = Group End + 1) names nothing. + let groups = dropped.groups.clone(); if groups.is_empty() { return Ok(()); } @@ -11826,8 +11845,7 @@ impl ServeLoop { // replaces any drop of the same groups, stale or final, so no update reopens them; // a reader a drop already ended stays ended. lite::SubscribeResponse::Skip(skipped) => { - let groups = skipped.start..skipped.end.saturating_add(1); - // An empty range (Group Start = Group End + 1) names nothing. + let groups = skipped.groups.clone(); if groups.is_empty() { return Ok(()); } @@ -11843,8 +11861,7 @@ impl ServeLoop { if let Some(first) = cached.iter().next() { tracing::warn!( track = %serve.name, - start = skipped.start, - end = skipped.end, + groups = ?skipped.groups, cached = first.start, "protocol error: SUBSCRIBE_SKIP names a group that arrived; keeping the group" ); diff --git a/rs/moq-net/src/lite/subscriber/fills.rs b/rs/moq-net/src/lite/subscriber/fills.rs index b02b06a6724..b904ec0b7b1 100644 --- a/rs/moq-net/src/lite/subscriber/fills.rs +++ b/rs/moq-net/src/lite/subscriber/fills.rs @@ -560,10 +560,7 @@ impl Recovery { ); } Ok(Some(lite::SubscribeResponse::Drop(dropped))) => { - given_up( - dropped.start..dropped.end.saturating_add(1), - Refusal::dropped(dropped.error(version)), - ); + given_up(dropped.groups.clone(), Refusal::dropped(dropped.error(version))); } // Nothing at or past the track's end will be produced. Ok(Some(lite::SubscribeResponse::Finish(finish))) if !self.ended => { diff --git a/rs/moq-net/src/lite/version.rs b/rs/moq-net/src/lite/version.rs index 30b4c961be5..471f194f7a5 100644 --- a/rs/moq-net/src/lite/version.rs +++ b/rs/moq-net/src/lite/version.rs @@ -298,6 +298,15 @@ impl Version { ) } + /// Whether SUBSCRIBE_DROP and SUBSCRIBE_SKIP carry `Group Start` and `Group Count`. + /// Added in lite-07; earlier versions carry an inclusive `Group Start` and `Group End`. + pub(crate) fn has_group_count(self) -> bool { + !matches!( + self, + Self::Lite01 | Self::Lite02 | Self::Lite03 | Self::Lite04 | Self::Lite05 | Self::Lite06 + ) + } + /// Whether holes split into SUBSCRIBE_SKIP, for sequences declared never produced, and /// SUBSCRIBE_DROP, for groups that existed, which names the `Update` in effect when it was /// given up; SUBSCRIBE and SUBSCRIBE_UPDATE carry that `Update` number. Added in lite-07; diff --git a/rs/moq-net/src/model/cache.rs b/rs/moq-net/src/model/cache.rs index 2269c660bfa..926d81f1080 100644 --- a/rs/moq-net/src/model/cache.rs +++ b/rs/moq-net/src/model/cache.rs @@ -459,7 +459,8 @@ impl Pool { let wall = super::clock::wall(); match self.inner.wall_epoch.get() { Some(epoch) => { - let driven = *epoch + Duration::from_micros(self.inner.wall_micros.load(Ordering::Relaxed)); + let driven = + epoch.saturating_add(Duration::from_micros(self.inner.wall_micros.load(Ordering::Relaxed))); wall.max(driven) } None => wall, @@ -508,7 +509,7 @@ impl Pool { .map(|clock| clock.now); let now = now.unwrap_or_else(super::clock::wall); self.date(now); - self.date(now + duration); + self.date(now.saturating_add(duration)); } #[cfg(test)] @@ -1450,7 +1451,7 @@ mod test { let pool = Pool::unbounded(); let track = Track::new(pool.clone(), Default::default(), kio::Weak::new()); let now = super::super::clock::wall(); - let at = now + Duration::from_secs(1); + let at = now.saturating_add(Duration::from_secs(1)); let (read, reading) = flag(); track.watch_wall(at, &reading); @@ -1468,7 +1469,7 @@ mod test { ); assert_eq!(pool.poll(now, &driving), Some(at)); - pool.poll(at - Duration::from_millis(1), &driving); + pool.poll(at.saturating_sub(Duration::from_millis(1)), &driving); assert!(!read.0.load(Ordering::SeqCst), "released early"); assert_eq!(pool.poll(at, &driving), None); assert!(read.0.load(Ordering::SeqCst), "the read was never released"); @@ -1485,12 +1486,12 @@ mod test { let (read, reading) = flag(); let (driver, driving) = flag(); assert_eq!(pool.poll(now, &driving), None); - let at = now + Duration::from_secs(1); + let at = now.saturating_add(Duration::from_secs(1)); track.watch_wall(at, &reading); assert!(driver.0.swap(false, Ordering::SeqCst)); assert_eq!(pool.poll(at, &driving), None); assert!(read.0.swap(false, Ordering::SeqCst)); - track.watch_wall(at + Duration::from_secs(1), &reading); + track.watch_wall(at.saturating_add(Duration::from_secs(1)), &reading); assert!(driver.0.load(Ordering::SeqCst), "the drained list was never rearmed"); } @@ -1504,13 +1505,13 @@ mod test { pool.poll(now, &waiter); let track = Track::new(pool.clone(), Default::default(), kio::Weak::new()); let (read, reading) = flag(); - let at = now + Duration::from_secs(1); + let at = now.saturating_add(Duration::from_secs(1)); track.watch_wall(at, &reading); kio::clock::sleep(Duration::from_secs(1)).await; assert_eq!(pool.poll(now, &waiter), None); assert!(read.0.swap(false, Ordering::SeqCst), "ambient time was ignored"); - let future = at + Duration::from_secs(1); + let future = at.saturating_add(Duration::from_secs(1)); track.watch_wall(future, &reading); assert_eq!(pool.poll(future, &waiter), None); assert!(read.0.swap(false, Ordering::SeqCst), "driven time was ignored"); @@ -1528,8 +1529,8 @@ mod test { pool.poll(now, &kio::Waiter::noop()); let track = Track::new(pool.clone(), Default::default(), kio::Weak::new()); let (_read, reading) = flag(); - track.watch_wall(now + Duration::from_secs(2), &reading); - track.watch_wall(now + Duration::from_secs(1), &reading); + track.watch_wall(now.saturating_add(Duration::from_secs(2)), &reading); + track.watch_wall(now.saturating_add(Duration::from_secs(1)), &reading); assert_eq!(pool.inner.wall.lock().due.len(), 1, "the later deadline lingers"); drop(track); @@ -1775,7 +1776,7 @@ mod test { let now = crate::time::Instant::now(); let deadline = pool.poll(now, &kio::Waiter::noop()); assert_eq!( - pool.poll(now + Duration::from_millis(500), &kio::Waiter::noop()), + pool.poll(now.saturating_add(Duration::from_millis(500)), &kio::Waiter::noop()), deadline ); } @@ -1786,11 +1787,17 @@ mod test { let now = crate::time::Instant::now(); assert_eq!(pool.poll(now, &kio::Waiter::noop()), None); pool.resize(1024); - assert_eq!(pool.poll(now, &kio::Waiter::noop()), Some(now + DEFAULT_EXPIRY / 2)); - pool.poll(now + DEFAULT_EXPIRY, &kio::Waiter::noop()); + assert_eq!( + pool.poll(now, &kio::Waiter::noop()), + Some(now.saturating_add(DEFAULT_EXPIRY / 2)) + ); + pool.poll(now.saturating_add(DEFAULT_EXPIRY), &kio::Waiter::noop()); assert!(pool.now() > 0); pool.resize(None); - assert_eq!(pool.poll(now + DEFAULT_EXPIRY, &kio::Waiter::noop()), None); + assert_eq!( + pool.poll(now.saturating_add(DEFAULT_EXPIRY), &kio::Waiter::noop()), + None + ); } #[test] diff --git a/rs/moq-net/src/model/delivered.rs b/rs/moq-net/src/model/delivered.rs index dd1f1ce79a3..d652550051c 100644 --- a/rs/moq-net/src/model/delivered.rs +++ b/rs/moq-net/src/model/delivered.rs @@ -6,7 +6,8 @@ use std::collections::BTreeMap; /// /// A reader stops expecting a group once it is past its budget, and counts everything /// below it as handed out (see [`Self::forget_below`]). The run starting at 0 is that -/// floor, so only the gaps above it cost memory. +/// floor, so only the gaps above it cost memory. It never holds the reserved group +/// sequence `u64::MAX`, so one past any run fits. #[derive(Default)] pub(super) struct Delivered { /// First to last sequence, inclusive, never adjacent to each other. @@ -22,9 +23,9 @@ impl Delivered { .is_some_and(|(_, last)| sequence <= *last) } - /// The first sequence above the handed-out prefix, or none once every sequence is past. - pub fn floor(&self) -> Option { - self.runs.get(&0).map_or(Some(0), |last| last.checked_add(1)) + /// The first sequence above the handed-out prefix. + pub fn floor(&self) -> u64 { + self.runs.get(&0).map_or(0, |last| last + 1) } /// Whether every sequence in `groups` was handed out, or is below the floor. @@ -47,10 +48,7 @@ impl Delivered { .and_then(|below| self.runs.range(..=below).next_back()) .filter(|(_, last)| **last + 1 == sequence) .map_or(sequence, |(first, _)| *first); - let last = sequence - .checked_add(1) - .and_then(|above| self.runs.remove(&above)) - .unwrap_or(sequence); + let last = self.runs.remove(&(sequence + 1)).unwrap_or(sequence); self.runs.insert(first, last); true } @@ -63,17 +61,13 @@ impl Delivered { let mut first = groups.start; // A run ending at or just below the first sequence joins it. if let Some((&start, &end)) = self.runs.range(..=first).next_back() - && end.checked_add(1).is_none_or(|after| after >= first) + && end + 1 >= first { first = start; last = last.max(end); } // So does every run starting inside it or just past it. - let joined: Vec = self - .runs - .range(first..=last.saturating_add(1)) - .map(|(&start, _)| start) - .collect(); + let joined: Vec = self.runs.range(first..=last + 1).map(|(&start, _)| start).collect(); for start in joined { if let Some(end) = self.runs.remove(&start) { last = last.max(end); @@ -98,10 +92,7 @@ impl Delivered { if *first > next { gaps.push(next..(*first).min(groups.end)); } - match last.checked_add(1) { - Some(after) => next = next.max(after), - None => return gaps, - } + next = next.max(last + 1); } if next < groups.end { gaps.push(next..groups.end); @@ -124,10 +115,8 @@ impl Delivered { return; }; // Every run starting at or below the floor joins it, including one starting right at it. - let above = match floor.checked_add(1) { - Some(above) => self.runs.split_off(&above), - None => BTreeMap::new(), - }; + // No run starts at the reserved `u64::MAX`, so a floor there splits nothing off. + let above = self.runs.split_off(&floor.saturating_add(1)); let last = self.runs.last_key_value().map_or(below, |(_, last)| below.max(*last)); self.runs = above; self.runs.insert(0, last); @@ -191,7 +180,7 @@ mod test { assert_eq!(runs(&delivered), [(4, 8)]); assert!(delivered.contains(4) && delivered.contains(8)); assert!(!delivered.contains(3) && !delivered.contains(9)); - assert_eq!(delivered.floor(), Some(0), "a run above a gap is not the prefix"); + assert_eq!(delivered.floor(), 0, "a run above a gap is not the prefix"); assert!(delivered.covers(4..9) && delivered.covers(9..9)); assert!(!delivered.covers(3..5) && !delivered.covers(8..10)); } @@ -218,12 +207,12 @@ mod test { fn the_extremes_are_sequences_too() { let mut delivered = Delivered::default(); assert!(delivered.insert(0)); - assert!(delivered.insert(u64::MAX)); - assert!(!delivered.insert(u64::MAX)); - assert_eq!(runs(&delivered), [(0, 0), (u64::MAX, u64::MAX)]); + assert!(delivered.insert(u64::MAX - 1)); + assert!(!delivered.insert(u64::MAX - 1)); + assert_eq!(runs(&delivered), [(0, 0), (u64::MAX - 1, u64::MAX - 1)]); delivered.forget_below(u64::MAX); - assert_eq!(runs(&delivered), [(0, u64::MAX)]); - assert_eq!(delivered.floor(), None); + assert_eq!(runs(&delivered), [(0, u64::MAX - 1)]); + assert_eq!(delivered.floor(), u64::MAX); } #[test] @@ -246,7 +235,7 @@ mod test { assert_eq!(runs(&delivered), [(0, 6), (9, 9), (12, 12)]); assert_eq!(delivered.above_gap(), Some(9)); assert!(delivered.contains(4), "below the floor counts as handed out"); - assert_eq!(delivered.floor(), Some(7)); + assert_eq!(delivered.floor(), 7); // A floor inside a gap keeps the run above it. delivered.forget_below(11); diff --git a/rs/moq-net/src/model/expiry.rs b/rs/moq-net/src/model/expiry.rs index 6a1d0b4966f..42259592cd5 100644 --- a/rs/moq-net/src/model/expiry.rs +++ b/rs/moq-net/src/model/expiry.rs @@ -454,7 +454,7 @@ mod test { let waiter = parked(); let budget = Duration::from_secs(1) + Duration::from_micros(i); wakes.watch_deadline(Timestamp::from_secs(10).unwrap(), budget, &waiter); - wakes.watch_wall(now + budget, &waiter); + wakes.watch_wall(now.saturating_add(budget), &waiter); live.push(waiter); } assert!( @@ -473,7 +473,7 @@ mod test { let waiter = parked(); let budget = Duration::from_secs(1) + Duration::from_micros(i); wakes.watch_deadline(Timestamp::from_secs(10).unwrap(), budget, &waiter); - wakes.watch_wall(now + budget, &waiter); + wakes.watch_wall(now.saturating_add(budget), &waiter); } let (media, wall) = wakes.deadlines_indexed(); assert!( diff --git a/rs/moq-net/src/model/front.rs b/rs/moq-net/src/model/front.rs index a8d67cc73de..37611b052a8 100644 --- a/rs/moq-net/src/model/front.rs +++ b/rs/moq-net/src/model/front.rs @@ -730,7 +730,7 @@ impl Front { fn parked_at(&self, name: &str) -> Option { match self.tracks.get(name)?.state { - TrackState::Parked { since } => Some(since + self.linger), + TrackState::Parked { since } => Some(since.saturating_add(self.linger)), _ => None, } } @@ -794,7 +794,7 @@ mod tests { .tracks .iter() .filter_map(|(name, track)| match track.state { - TrackState::Parked { since } => Some((since + front.linger, name.clone())), + TrackState::Parked { since } => Some((since.saturating_add(front.linger), name.clone())), _ => None, }) .collect(); @@ -825,7 +825,9 @@ mod tests { track: name("video"), now: t0, }), - &[Action::Arm { at: Some(t0 + LINGER) }], + &[Action::Arm { + at: Some(t0.saturating_add(LINGER)), + }], ); assert_actions( front.step(Event::Wanted { track: name("video") }), @@ -1379,19 +1381,27 @@ mod tests { }), &[ Action::Park { track: name("video") }, - Action::Arm { at: Some(t0 + LINGER) }, + Action::Arm { + at: Some(t0.saturating_add(LINGER)), + }, ], ); // Too early: nothing released, but the deadline is armed again since the // driver clears it on firing. assert_actions( - front.step(Event::Deadline { now: t0 + LINGER / 2 }), - &[Action::Arm { at: Some(t0 + LINGER) }], + front.step(Event::Deadline { + now: t0.saturating_add(LINGER / 2), + }), + &[Action::Arm { + at: Some(t0.saturating_add(LINGER)), + }], ); // The driver cleared the fired deadline itself; nothing is parked, so // nothing re-arms. assert_actions( - front.step(Event::Deadline { now: t0 + LINGER }), + front.step(Event::Deadline { + now: t0.saturating_add(LINGER), + }), &[Action::Forget { track: name("video") }], ); assert_actions(front.step(Event::Forgotten { track: name("video") }), &[]); @@ -1409,7 +1419,9 @@ mod tests { now: t0, }); assert_actions( - front.step(Event::Deadline { now: t0 + LINGER }), + front.step(Event::Deadline { + now: t0.saturating_add(LINGER), + }), &[Action::Forget { track: name("video") }], ); assert_actions( @@ -1433,7 +1445,9 @@ mod tests { }); assert_actions(front.step(Event::Unheld), &[]); assert_actions( - front.step(Event::Deadline { now: t0 + LINGER }), + front.step(Event::Deadline { + now: t0.saturating_add(LINGER), + }), &[Action::Forget { track: name("video") }], ); assert_actions(front.step(Event::Forgotten { track: name("video") }), &[Action::Retire]); @@ -1545,7 +1559,9 @@ mod tests { track: name("video"), now: t0, }), - &[Action::Arm { at: Some(t0 + LINGER) }], + &[Action::Arm { + at: Some(t0.saturating_add(LINGER)), + }], ); // A returning reader reads what it holds: no query, and the linger waits. assert_actions( @@ -1567,13 +1583,15 @@ mod tests { drain: false, }], ); - let t1 = t0 + LINGER; + let t1 = t0.saturating_add(LINGER); front.step(Event::Unwanted { track: name("video"), now: t1, }); assert_actions( - front.step(Event::Deadline { now: t1 + LINGER }), + front.step(Event::Deadline { + now: t1.saturating_add(LINGER), + }), &[Action::Forget { track: name("video") }], ); front.step(Event::Forgotten { track: name("video") }); @@ -1598,10 +1616,14 @@ mod tests { track: name("video"), now: t0, }), - &[Action::Arm { at: Some(t0 + LINGER) }], + &[Action::Arm { + at: Some(t0.saturating_add(LINGER)), + }], ); assert_actions( - front.step(Event::Deadline { now: t0 + LINGER }), + front.step(Event::Deadline { + now: t0.saturating_add(LINGER), + }), &[Action::Forget { track: name("video") }], ); front.step(Event::Forgotten { track: name("video") }); @@ -1651,7 +1673,7 @@ mod tests { }); front.step(Event::TrackAssigned { track: name("audio"), - now: now + LINGER / 2, + now: now.saturating_add(LINGER / 2), }); assert_actions( front.step(Event::Wanted { track: name("video") }), @@ -1661,13 +1683,13 @@ mod tests { source: 100, }, Action::Arm { - at: Some(now + LINGER + LINGER / 2), + at: Some(now.saturating_add(LINGER).saturating_add(LINGER / 2)), }, ], ); assert_actions( front.step(Event::Deadline { - now: now + LINGER + LINGER / 2, + now: now.saturating_add(LINGER).saturating_add(LINGER / 2), }), &[Action::Forget { track: name("audio") }], ); @@ -1687,7 +1709,9 @@ mod tests { }); assert_eq!(front.tracks[&name("audio")].state, TrackState::Parked { since: t0 }); assert_actions( - front.step(Event::Deadline { now: t0 + LINGER }), + front.step(Event::Deadline { + now: t0.saturating_add(LINGER), + }), &[Action::Forget { track: name("audio") }], ); } @@ -1753,7 +1777,7 @@ mod tests { 0 => Event::Wanted { track }, 1 => Event::Unwanted { track, now }, 2 => { - now += LINGER / 4; + now = now.saturating_add(LINGER / 4); Event::Deadline { now } } _ => Event::TrackInfo { @@ -1838,7 +1862,9 @@ mod tests { result: Err(Error::Dropped), delivered: false, }, - Event::Deadline { now: t0 + LINGER }, + Event::Deadline { + now: t0.saturating_add(LINGER), + }, Event::Forgotten { track: name("v") }, Event::Unheld, Event::Held, @@ -1999,7 +2025,9 @@ mod tests { }), &[ Action::Park { track: name("video") }, - Action::Arm { at: Some(t0 + LINGER) }, + Action::Arm { + at: Some(t0.saturating_add(LINGER)), + }, ], ); front.step(Event::Selected { @@ -2046,7 +2074,9 @@ mod tests { }), &[ Action::Park { track: name("video") }, - Action::Arm { at: Some(t0 + LINGER) }, + Action::Arm { + at: Some(t0.saturating_add(LINGER)), + }, ], ); } diff --git a/rs/moq-net/src/model/group.rs b/rs/moq-net/src/model/group.rs index 22b4c0bd4f8..2a28ef5afe6 100644 --- a/rs/moq-net/src/model/group.rs +++ b/rs/moq-net/src/model/group.rs @@ -3468,7 +3468,7 @@ impl Prefetch { self.reset(compressed); let mut read = log.read(); let mut end = 0; - for index in (index as u64..).take(budget.min(Self::CAP)) { + for index in (index as u64..=u64::MAX).take(budget.min(Self::CAP)) { // Evicted or not yet committed: the guard resolves which. let Ok(Some(entry)) = read.get(index) else { break; diff --git a/rs/moq-net/src/model/origin.rs b/rs/moq-net/src/model/origin.rs index 9ce09c600c0..fb9aad2a3d7 100644 --- a/rs/moq-net/src/model/origin.rs +++ b/rs/moq-net/src/model/origin.rs @@ -1124,12 +1124,14 @@ impl OriginConsumerState { match pending.held { None => { pending.held = Some(Held::Anchoring(now)); - Some(now + Duration::from_nanos(1)) + Some(now.saturating_add(Duration::from_nanos(1))) + } + Some(Held::Anchoring(seen)) if now <= seen => { + Some(seen.saturating_add(Duration::from_nanos(1))) } - Some(Held::Anchoring(seen)) if now <= seen => Some(seen + Duration::from_nanos(1)), Some(Held::Anchoring(_)) => { - pending.held = Some(Held::Until(now + hold)); - Some(now + hold) + pending.held = Some(Held::Until(now.saturating_add(hold))); + Some(now.saturating_add(hold)) } Some(Held::Until(until)) => Some(until).filter(|until| *until > now), } @@ -1138,7 +1140,7 @@ impl OriginConsumerState { Some(Quarantine { held: Held::Anchoring(seen), .. - }) => Some(*seen + Duration::from_nanos(1)), + }) => Some(seen.saturating_add(Duration::from_nanos(1))), Some(Quarantine { held: Held::Until(until), .. @@ -8119,8 +8121,9 @@ impl Routes { if let Some(quarantine) = self.retracted.get_mut(prefix) && quarantine.held == Held::Anchoring(*seen) { - quarantine.held = Held::Until(now + RETRACT_QUARANTINE); - self.expiring.push_back((now + RETRACT_QUARANTINE, prefix.clone())); + quarantine.held = Held::Until(now.saturating_add(RETRACT_QUARANTINE)); + self.expiring + .push_back((now.saturating_add(RETRACT_QUARANTINE), prefix.clone())); } self.anchoring.pop_front(); } @@ -8137,7 +8140,10 @@ impl Routes { } self.expiring.pop_front(); } - let anchoring = self.anchoring.front().map(|(seen, _)| *seen + Duration::from_nanos(1)); + let anchoring = self + .anchoring + .front() + .map(|(seen, _)| seen.saturating_add(Duration::from_nanos(1))); earliest(anchoring, self.expiring.front().map(|(until, _)| *until)) } @@ -12006,7 +12012,10 @@ mod tests { for k in [64usize, 256, 1024] { let (producer, mut driver) = Producer::new(Config::from(origin(1))); driver - .poll(Instant::ZERO + Duration::from_secs(1), &kio::Waiter::noop()) + .poll( + Instant::ZERO.saturating_add(Duration::from_secs(1)), + &kio::Waiter::noop(), + ) .unwrap(); let peer = producer.clone().with_link(Link::Peer); // One instance, so the winner moving between routes is an update, not a restart. diff --git a/rs/moq-net/src/model/resume.rs b/rs/moq-net/src/model/resume.rs index be6602d6845..120b565bace 100644 --- a/rs/moq-net/src/model/resume.rs +++ b/rs/moq-net/src/model/resume.rs @@ -1478,7 +1478,7 @@ impl Reader { self.backfill_gaps(delivered); let groups = self.groups; let budget = self.mirrored.budget(); - let floor = if ordered { delivered.floor() } else { Some(0) }; + let floor = if ordered { delivered.floor() } else { 0 }; let mut lowest: Option = None; for index in 0..self.copies.len() { let copy = &mut self.copies[index]; @@ -1524,7 +1524,7 @@ impl Reader { unreachable!() }; if ordered { - sub.skip_ordered(sequence.checked_add(1)); + sub.skip_ordered(sequence + 1); } else { let _ = sub.take(reserved); } @@ -4954,7 +4954,7 @@ mod test { write(&a, 2); assert_eq!(drain(&mut sub, false), [0, 2]); - pool.poll(opened + budget / 2, &noop); + pool.poll(opened.saturating_add(budget / 2), &noop); let b = copy(); write(&b, if first_group { 3 } else { 2 }); routes.serve(b.consume()); @@ -4974,8 +4974,11 @@ mod test { assert!(poll().is_pending()); assert!(!wake.0.load(std::sync::atomic::Ordering::Relaxed)); - let deadline = opened + budget; - assert_eq!(pool.poll(deadline - Duration::from_micros(1), &noop), Some(deadline)); + let deadline = opened.saturating_add(budget); + assert_eq!( + pool.poll(deadline.saturating_sub(Duration::from_micros(1)), &noop), + Some(deadline) + ); assert!( !wake.0.load(std::sync::atomic::Ordering::Relaxed), "not before the grace" diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index c7efeda59b0..b0b045fefc9 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -2407,12 +2407,16 @@ impl TrackState { Deferred(std::mem::take(&mut self.deferred)) } - /// The sequence the next append takes: one past this track's own writes. + /// The sequence the next append takes: one past this track's own writes, short of the + /// reserved `u64::MAX`. fn next_sequence(&self) -> Result { - Ok(match self.max_sequence { - Some(max) => max.checked_add(1).ok_or(coding::BoundsExceeded)?, - None => 0, - }) + match self.max_sequence { + Some(max) => max + .checked_add(1) + .filter(|next| *next != u64::MAX) + .ok_or(coding::BoundsExceeded.into()), + None => Ok(0), + } } /// Reject a sequence that is still cached; a dead (aborted or evicted) @@ -3003,7 +3007,7 @@ impl TrackState { /// One past the highest sequence produced: where the live edge stands against the end. fn edge(&self) -> u64 { - self.max_sequence.map_or(0, |max| max.saturating_add(1)) + self.max_sequence.map_or(0, |max| max + 1) } /// Whether a group below `fin` the wire subscription still owes has yet to arrive. @@ -3841,7 +3845,8 @@ impl Producer { /// It says nothing about the sequences around it: groups may be created out of order, and /// an aborted or evicted sequence created again. A gap it leaves is skipped only once the /// producer says it will not fill it, with [`Self::skip_groups`] or [`Self::append_group`]. - /// A sequence already skipped is refused with [`Error::Skipped`]. + /// A sequence already skipped is refused with [`Error::Skipped`], and the reserved + /// sequence `u64::MAX` with [`Error::BoundsExceeded`]. /// /// Readers and group demand reach it at once, but the track counts it as content (its /// live edge, or the successor that ages the group before it) only once its first frame @@ -3863,6 +3868,10 @@ impl Producer { } fn create_group_inner(&self, info: group::Info, received: Option) -> Result { + // Reserved, so every group fits an exclusive range. + if info.sequence == u64::MAX { + return Err(coding::BoundsExceeded.into()); + } let mut state = self.modify()?; if matches!(state.outcome, Outcome::Sealed(_)) || state.final_sequence().is_some_and(|fin| info.sequence >= fin) { @@ -3972,8 +3981,7 @@ impl Producer { /// /// Other clones of this producer stay open handles, and refuse a group at or past the end /// with [`Error::Closed`]. Fails with [`Error::Closed`] if the track already declared an - /// end, or with the abort error. A track whose highest group is `u64::MAX` has no end to - /// declare: it is aborted with [`Error::BoundsExceeded`], which the call also returns. + /// end, or with the abort error. pub fn finish(self) -> Result { self.finish_shared()?; Ok(Finished { producer: self }) @@ -3983,20 +3991,7 @@ impl Producer { /// groups still in flight. pub(crate) fn finish_shared(&self) -> Result<()> { let mut state = self.modify()?; - let final_sequence = match state.max_sequence { - None => 0, - Some(max) => match max.checked_add(1) { - Some(end) => end, - None => { - // Left open, readers would wait for an end that never comes and then see - // `Dropped`; abort so they get the cause. - drop(state); - let err = Error::from(coding::BoundsExceeded); - let _ = self.clone().abort(err.clone()); - return Err(err); - } - }, - }; + let final_sequence = state.max_sequence.map_or(0, |max| max + 1); state.set_end(Position::group(final_sequence), None) } @@ -6259,7 +6254,7 @@ impl kio::Task for Resolving { } /// Join the fill covering `sequence`, or queue a one-group fill; `None` when no handler -/// exists to take one, or for the last sequence, which a fill's exclusive end can't name. +/// exists to take one, or for the reserved sequence `u64::MAX`, which no group holds. fn queue(fills: &kio::Shared, sequence: u64, request: &FetchOptions) -> Option> { let options = &request.options; let end = sequence.checked_add(1)?; @@ -6474,8 +6469,7 @@ impl Fetching { // Handler side. let Some(result) = result else { - // A fill's end is exclusive, so no handler can be asked for the last sequence: - // only a local write, already looked for above, can hold it. + // No group is ever created at the reserved sequence, so no handler is asked for it. if sequence == u64::MAX { return Poll::Ready(Err(Error::NotFound)); } @@ -7371,10 +7365,9 @@ struct Cursor { min_sequence: u64, /// This subscriber's own ranges, resolved. Boxed: every reader embeds a cursor. filter: Box, - /// One past the highest sequence returned by `next_group`, or `None` once it returned - /// `u64::MAX` and no group can follow. + /// One past the highest sequence returned by `next_group`. /// Used only by that method to skip late arrivals; does not affect `recv_group`. - next_sequence: Option, + next_sequence: u64, /// Exclusive upper sequence bound for `next_group` and `recv_group`. `None` means no /// cap. Set by `set_range`; /// can be raised, lowered, or unset at any time. Groups at or past the cap stay in @@ -7754,7 +7747,7 @@ impl Cursor { min_sequence: 0, filter: Box::new(filter), index: 0, - next_sequence: Some(0), + next_sequence: 0, end_sequence: None, // Uncapped, the servable groups are the window's. servable: published.servable.clone(), @@ -7789,7 +7782,7 @@ impl Cursor { && let Poll::Ready(Ok(drift)) = self.poll_drift(&self.servable, waiter) { // From where the reader reads next: an ordered one asks nothing below what it took. - let from = self.next_sequence.unwrap_or(u64::MAX).max(self.floor()); + let from = self.next_sequence.max(self.floor()); self.probe(from, &drift, taken, waiter); judged = Some(drift); } @@ -8863,25 +8856,23 @@ impl Cursor { } /// Pass groups another copy already handed out, without delivering or metering them. - fn skip_ordered(&mut self, floor: Option) { - let next = self.next_sequence.zip(floor).map(|(next, floor)| next.max(floor)); - if next == self.next_sequence { + fn skip_ordered(&mut self, floor: u64) { + if floor <= self.next_sequence { return; } idle::Idle::disarm(&mut self.idle); - self.next_sequence = next; + self.next_sequence = floor; // A group delivered on another copy is not a stale skip on this one. if !self.seek_pending.is_empty() { - self.seek_pending = next.map_or_else(BTreeMap::new, |next| self.seek_pending.split_off(&next)); + self.seek_pending = self.seek_pending.split_off(&floor); } - self.forget_heads_below(next); + self.forget_heads_below(floor); } /// Let go of the heads asked below `next`, which an ordered read never goes back for: /// one still out would keep the read waiting on a fill it no longer polls. - fn forget_heads_below(&mut self, next: Option) { + fn forget_heads_below(&mut self, next: u64) { if let Some(heads) = &mut self.heads { - let next = next.unwrap_or(u64::MAX); heads.fetching = heads.fetching.split_off(&next); heads.filled = heads.filled.split_off(&next); } @@ -8890,9 +8881,7 @@ impl Cursor { /// The lowest servable group past the last one returned, walking off everything the /// drift budget has convicted on the way. fn poll_peek_next(&mut self, taken: &Delivered, waiter: &kio::Waiter) -> Poll>> { - let Some(next) = self.next_sequence else { - return Poll::Ready(Ok(None)); - }; + let next = self.next_sequence; self.sync(); if let Some(err) = &self.filter.refused { return Poll::Ready(Err(err.clone())); @@ -9020,14 +9009,14 @@ impl Cursor { } fn advance_sequence(&mut self, group: group::Consumer) -> group::Consumer { - self.next_sequence = group.sequence.checked_add(1); + self.next_sequence = group.sequence + 1; // The reader holds the group itself now, as on the arrival path. if let Some(misses) = &mut self.misses { misses.take_filled(group.sequence); } self.forget_heads_below(self.next_sequence); // The delivery commits everything the seek stepped over to reach this group. - self.commit_seek_stale(self.next_sequence.unwrap_or(u64::MAX)); + self.commit_seek_stale(self.next_sequence); group.cache_refresh(); self.deliver(group) } @@ -9415,21 +9404,17 @@ impl Subscriber { } /// Pass groups another route copy handed out, preserving the arrival cursor and bounds. - pub(super) fn skip_ordered(&mut self, floor: Option) { + pub(super) fn skip_ordered(&mut self, floor: u64) { match &mut self.inner { Inner::Plain(cursor) => cursor.skip_ordered(floor), Inner::Resume(resume, _) => { // What it handed out moves, which nothing it parked on notifies. - let end = floor.unwrap_or(u64::MAX); - if !self.delivered.covers(0..end) || (floor.is_none() && !self.delivered.contains(u64::MAX)) { + if !self.delivered.covers(0..floor) { resume.disarm(); } // Its retention decisions also need the containing reader's past prefix. // This records what is no longer owed, without handing a group out. - self.delivered.forget_below(floor.unwrap_or(u64::MAX)); - if floor.is_none() { - self.delivered.insert(u64::MAX); - } + self.delivered.forget_below(floor); } } } @@ -11507,11 +11492,11 @@ mod test { assert_eq!(consumer.resume_position(), Some(Position { group: 3, frame: 1 })); } - /// A fill's end is exclusive, so the last sequence can't be asked of a handler: its fetch - /// fails at once rather than parking until every handler goes. + /// No group holds the reserved sequence, so its fetch fails at once rather than parking + /// until every handler goes. #[test] #[cfg(feature = "async")] - fn the_last_sequence_misses_with_a_handler() { + fn the_reserved_sequence_misses_with_a_handler() { let producer = track_producer("test", None); let dynamic = producer.requests(); let consumer = producer.consume(); @@ -11868,17 +11853,17 @@ mod test { let now = crate::model::clock::now(); assert_eq!( pool.poll(now, &kio::Waiter::noop()), - Some(now + Duration::from_millis(500)) + Some(now.saturating_add(Duration::from_millis(500))) ); let producer = track_producer_pooled("test", pool.clone()); let mut group = producer.append_group().unwrap(); group.write_frame(Timestamp::ZERO, b"first".as_slice()).unwrap(); let _open = producer.append_group().unwrap(); // Activity written while cleanup was idle gets the new supplied time. - let later = now + Duration::from_secs(60); + let later = now.saturating_add(Duration::from_secs(60)); pool.poll(later, &kio::Waiter::noop()); assert!(producer.state.read().lookup.contains_key(&0)); - pool.poll(later + Duration::from_secs(2), &kio::Waiter::noop()); + pool.poll(later.saturating_add(Duration::from_secs(2)), &kio::Waiter::noop()); assert!(!producer.state.read().lookup.contains_key(&0)); } @@ -11895,7 +11880,7 @@ mod test { for group in &groups[..EVICT_SCAN * 2] { group.handle().cache_refresh(); } - pool.poll(now + expiry * 2, &kio::Waiter::noop()); + pool.poll(now.saturating_add(expiry * 2), &kio::Waiter::noop()); let state = producer.state.read(); for sequence in 0..EVICT_SCAN * 2 { assert!(state.lookup.contains_key(&(sequence as u64)), "fresh front survives"); @@ -15606,31 +15591,6 @@ mod test { assert!(finished.closed().now_or_never().expect("settled").is_ok()); } - /// No end follows group `u64::MAX`, so finishing aborts the track with that cause: the - /// consumed handle leaves the caller nothing to abort it with. - #[test] - #[cfg(feature = "async")] - fn finish_past_the_last_sequence_aborts_with_the_cause() { - let producer = track_producer("test", Info::timed()); - let mut subscriber = producer.subscribe(replay()); - let mut group = producer.create_group(group::Info { sequence: u64::MAX }).unwrap(); - group.write_frame(Timestamp::ZERO, &b"x"[..]).unwrap(); - let mut reader = group.consume(); - assert!(matches!(producer.finish(), Err(Error::BoundsExceeded(_)))); - // The subscriber may hand out the open group before the error. - let ended = loop { - match subscriber.recv_group().now_or_never().expect("settled") { - Ok(Some(_)) => continue, - ended => break ended.map(|group| group.map(|group| group.sequence)), - } - }; - assert!(matches!(ended, Err(Error::BoundsExceeded(_))), "{ended:?}"); - // The open group is cut with the same cause. - let cut = reader.read_frame().now_or_never().expect("settled"); - assert!(matches!(cut, Err(Error::BoundsExceeded(_))), "{cut:?}"); - assert!(matches!(group.finish(), Err(Error::BoundsExceeded(_)))); - } - #[test] fn finish_at_rejects_a_boundary_at_or_below_the_live_edge() { let mut producer = track_producer("test", Info::timed()); @@ -17060,18 +17020,19 @@ mod test { fn skipping_another_copys_groups_preserves_arrival_bounds_and_the_last_sequence() { let producer = track_producer("test", Info::timed()); let mut subscriber = producer.subscribe(replay()); - for sequence in [u64::MAX - 1, u64::MAX] { + for sequence in [u64::MAX - 2, u64::MAX - 1] { producer .create_group(group::Info { sequence }) .unwrap() .finish() .unwrap(); } + let _finished = producer.finish().unwrap(); + assert_eq!(peek(&mut subscriber, true), Poll::Ready(Some(u64::MAX - 2))); + subscriber.skip_ordered(u64::MAX - 1); assert_eq!(peek(&mut subscriber, true), Poll::Ready(Some(u64::MAX - 1))); - subscriber.skip_ordered(Some(u64::MAX)); - assert_eq!(peek(&mut subscriber, true), Poll::Ready(Some(u64::MAX))); - subscriber.skip_ordered(None); - subscriber.skip_ordered(Some(0)); + subscriber.skip_ordered(u64::MAX); + subscriber.skip_ordered(0); assert_eq!(peek(&mut subscriber, true), Poll::Ready(None)); assert_eq!(subscriber.delivered.runs(), 0, "skips are not deliveries"); assert_eq!(subscriber.take_stale().groups, 0, "duplicates are not stale skips"); @@ -17081,7 +17042,7 @@ mod test { assert_eq!(cursor.min_sequence, 0); assert_eq!(cursor.end_sequence, None); assert_eq!(cursor.index, 0); - assert_eq!(peek(&mut subscriber, false), Poll::Ready(Some(u64::MAX - 1))); + assert_eq!(peek(&mut subscriber, false), Poll::Ready(Some(u64::MAX - 2))); } #[test] @@ -17095,7 +17056,7 @@ mod test { panic!("group 3 is servable"); }; assert_eq!(reserved.sequence(), 3); - subscriber.skip_ordered(Some(2)); + subscriber.skip_ordered(2); assert_eq!(subscriber.take(reserved).unwrap().sequence, 3); assert_eq!(subscriber.take_stale().groups, 1, "only group 2 was skipped for age"); assert_eq!(subscriber.take_stale().groups, 0, "counted once"); @@ -17766,34 +17727,31 @@ mod test { ); } - /// An inclusive bound at the last group withholds nothing. + /// Group `u64::MAX` is reserved, so every group fits an exclusive range: neither a create + /// nor an append reaches it, and an inclusive bound there withholds nothing. #[test] #[cfg(feature = "async")] - fn end_at_maximum_group_is_unbounded() { + fn the_reserved_sequence_is_refused() { let producer = track_producer("test", Info::timed()); let mut consumer = producer.subscribe(replay()).ordered(); consumer.set_range(..=u64::MAX); + assert!(matches!( + producer.create_group(group::Info { sequence: u64::MAX }), + Err(Error::BoundsExceeded(_)) + )); producer - .create_group(group::Info { sequence: 0 }) - .unwrap() - .finish() - .unwrap(); - producer - .create_group(group::Info { sequence: u64::MAX }) + .create_group(group::Info { sequence: u64::MAX - 1 }) .unwrap() .finish() .unwrap(); - - assert_eq!( - consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence, - 0 - ); + assert!(matches!(producer.append_group(), Err(Error::BoundsExceeded(_)))); assert_eq!( consumer.next_group().now_or_never().unwrap().unwrap().unwrap().sequence, - u64::MAX + u64::MAX - 1 ); - // Nothing can follow the maximum sequence. + // The track's end lands on the reserved sequence. + let _finished = producer.finish().unwrap(); assert!(consumer.next_group().now_or_never().unwrap().unwrap().is_none()); } @@ -17832,17 +17790,6 @@ mod test { ); } - #[test] - fn append_group_returns_bounds_exceeded_on_sequence_overflow() { - let producer = track_producer("test", Info::timed()); - { - let mut state = producer.state.write().ok().unwrap(); - state.max_sequence = Some(u64::MAX); - } - - assert!(matches!(producer.append_group(), Err(Error::BoundsExceeded(_)))); - } - #[kio::test] #[cfg(feature = "async")] async fn fetch_cache_hit() { diff --git a/rs/moq-net/src/model/track/miss.rs b/rs/moq-net/src/model/track/miss.rs index 7ea1df30178..289dd04c068 100644 --- a/rs/moq-net/src/model/track/miss.rs +++ b/rs/moq-net/src/model/track/miss.rs @@ -698,7 +698,7 @@ impl Misses { || self.grace != Some(grace) || self.ended != ended; let low = key.0; - let top = newest.min(u64::MAX - 1); + let top = newest; let mut candidates = RangeSet::new(); if terms { let mut span = RangeSet::new(); @@ -1041,7 +1041,7 @@ impl Misses { // The reader's floor, as the whole judgement takes it: a resumed copy's live floor // can sit above history the reader still reads. let low = key.0; - let top = newest.min(u64::MAX - 1); + let top = newest; let first = judged_to.saturating_add(1).max(low); let mut fresh = RangeSet::new(); if first <= top { @@ -1474,7 +1474,7 @@ impl TrackState { /// reads by arrival never raises its floor, so without this every old group the cache /// evicts would land with it and count as an eviction to judge again. fn inbox_floor(low: u64, taken: &Delivered) -> u64 { - low.max(taken.floor().unwrap_or(u64::MAX)) + low.max(taken.floor()) } fn backfill(state: &TrackState, run: ops::Range) -> RangeSet { @@ -1583,7 +1583,7 @@ mod tests { let waiter = kio::Waiter::new(flag.clone().into()); assert!(misses.resolve(&state, Some(budget), &mut given_up, &waiter).is_empty()); if let Some(requests) = requests { - pool.poll(opened + budget / 2, &noop); + pool.poll(opened.saturating_add(budget / 2), &noop); let Poll::Ready(Ok(fill)) = requests.poll_requested_fill_group(&noop) else { panic!("the queued fill"); }; @@ -1593,8 +1593,11 @@ mod tests { assert!(misses.refused.contains(&1)); assert!(given_up.is_empty(), "the live feed may still deliver the group"); flag.0.store(false, Ordering::Relaxed); - let deadline = opened + budget; - assert_eq!(pool.poll(deadline - Duration::from_micros(1), &noop), Some(deadline)); + let deadline = opened.saturating_add(budget); + assert_eq!( + pool.poll(deadline.saturating_sub(Duration::from_micros(1)), &noop), + Some(deadline) + ); assert!(!flag.0.load(Ordering::Relaxed)); pool.poll(deadline, &noop); assert!( @@ -2058,7 +2061,7 @@ mod tests { assert_eq!(misses.deferred.overlapping(0..5).collect::>(), vec![3..4]); assert_eq!( misses.deferred.deadline(), - Some(opened + wider), + Some(opened.saturating_add(wider)), "timed by the new grace" ); } @@ -2464,8 +2467,8 @@ mod tests { #[test] fn deferred_splits_and_replacements_retire_the_old_age_entries() { let mut deferred = Deferred::default(); - let early = crate::time::Instant::ZERO + Duration::from_secs(1); - let late = early + Duration::from_secs(1); + let early = crate::time::Instant::ZERO.saturating_add(Duration::from_secs(1)); + let late = early.saturating_add(Duration::from_secs(1)); deferred.insert(0..u64::MAX, Some(early)); deferred.insert(10..20, Some(late)); deferred.remove(5..25); diff --git a/rs/moq-net/src/reconnect.rs b/rs/moq-net/src/reconnect.rs index 34afa90e516..ac94e7e68a6 100644 --- a/rs/moq-net/src/reconnect.rs +++ b/rs/moq-net/src/reconnect.rs @@ -436,7 +436,7 @@ impl Probe { fn new(now: Instant) -> Self { Self { delay: PROBE_INITIAL, - state: Probing::Due(now + jitter(PROBE_INITIAL)), + state: Probing::Due(now.saturating_add(jitter(PROBE_INITIAL))), } } @@ -456,7 +456,7 @@ impl Probe { /// Schedule the next probe after a failed one, doubling the wait up to the cap. fn failed(&mut self, now: Instant) { self.delay = self.delay.saturating_mul(2).min(PROBE_MAX); - self.state = Probing::Due(now + jitter(self.delay)); + self.state = Probing::Due(now.saturating_add(jitter(self.delay))); } } @@ -708,7 +708,7 @@ impl + From> Reco &mut self.phase, Phase::Dialing(Dialing { index, - deadline: connect.map(|connect| (now + connect, Failure::Timeout(connect))), + deadline: connect.map(|connect| (now.saturating_add(connect), Failure::Timeout(connect))), presented, }), ) else { @@ -729,7 +729,7 @@ impl + From> Reco older.retire(); } self.predecessor = Some(Predecessor { - deadline: now + self.config.goaway.handover, + deadline: now.saturating_add(self.config.goaway.handover), session: old.session, closing: false, }); @@ -792,7 +792,7 @@ impl + From> Reco }; let (attempt, presented) = self.attempt(live.index); tracing::debug!(peer = %Shown(attempt.target.url()), "probing the preferred transport"); - let deadline = self.config.timeout.map(|timeout| now + timeout); + let deadline = self.config.timeout.map(|timeout| now.saturating_add(timeout)); if let Phase::Live(live) = &mut self.phase && let Some(probe) = live.probe.as_mut() { @@ -812,9 +812,14 @@ impl + From> Reco let connect = self.config.timeout; let attempt = (index + 1 < self.targets.len()).then_some(ATTEMPT); let deadline = match (attempt, connect) { - (Some(attempt), Some(connect)) if connect <= attempt => Some((now + connect, Failure::Timeout(connect))), - (Some(attempt), _) => Some((now + attempt, Failure::Attempt(Shown(target.url()).to_string()))), - (None, Some(connect)) => Some((now + connect, Failure::Timeout(connect))), + (Some(attempt), Some(connect)) if connect <= attempt => { + Some((now.saturating_add(connect), Failure::Timeout(connect))) + } + (Some(attempt), _) => Some(( + now.saturating_add(attempt), + Failure::Attempt(Shown(target.url()).to_string()), + )), + (None, Some(connect)) => Some((now.saturating_add(connect), Failure::Timeout(connect))), (None, None) => None, }; @@ -953,7 +958,7 @@ impl + From> Reco old.retire(); } self.predecessor = Some(Predecessor { - deadline: now + self.config.goaway.handover(msg.timeout()), + deadline: now.saturating_add(self.config.goaway.handover(msg.timeout())), session: live.session, closing: false, }); @@ -1029,7 +1034,7 @@ impl + From> Reco }; tracing::warn!(?wait, "{reason}"); self.phase = Phase::Backoff { - until: now + wait, + until: now.saturating_add(wait), restart, }; } diff --git a/rs/moq-net/src/reconnect/tests.rs b/rs/moq-net/src/reconnect/tests.rs index 9d0f27af55a..64198d58423 100644 --- a/rs/moq-net/src/reconnect/tests.rs +++ b/rs/moq-net/src/reconnect/tests.rs @@ -351,9 +351,11 @@ fn a_late_poll_past_the_window_gives_up() { assert!(matches!(machine.poll(started, &waiter), Action::Dial(_))); machine.failed(started, TestError::Dial, Verdict::Retry); assert!(matches!(machine.poll(started, &waiter), Action::Retrying(_))); - assert!(matches!(machine.poll(started, &waiter), Action::Wait(Some(until)) if until <= started + INITIAL)); + assert!( + matches!(machine.poll(started, &waiter), Action::Wait(Some(until)) if until <= started.saturating_add(INITIAL)) + ); - let action = machine.poll(started + Duration::from_secs(2), &waiter); + let action = machine.poll(started.saturating_add(Duration::from_secs(2)), &waiter); assert!( matches!(action, Action::Done(Err(TestError::Policy(Failure::Exhausted { .. })))), "{action:?}" @@ -925,11 +927,17 @@ fn dialing_never_logs_the_credential() { let events = crate::test_tracing::capture(tracing::Level::DEBUG, || { assert!(matches!(machine.poll(started, &waiter), Action::Dial(_))); // The first address has a fallback, so it times out with an error naming it. - assert!(matches!(machine.poll(started + ATTEMPT, &waiter), Action::Abandon)); - assert!(matches!(machine.poll(started + ATTEMPT, &waiter), Action::Dial(_))); - machine.failed(started + ATTEMPT, TestError::Dial, Verdict::Retry); + assert!(matches!( + machine.poll(started.saturating_add(ATTEMPT), &waiter), + Action::Abandon + )); + assert!(matches!( + machine.poll(started.saturating_add(ATTEMPT), &waiter), + Action::Dial(_) + )); + machine.failed(started.saturating_add(ATTEMPT), TestError::Dial, Verdict::Retry); loop { - match machine.poll(started + ATTEMPT, &waiter) { + match machine.poll(started.saturating_add(ATTEMPT), &waiter) { Action::Retrying(err) => reported.push(err.to_string()), Action::Wait(_) => break, action => panic!("unexpected {action:?}"), diff --git a/rs/moq-net/src/route/mod.rs b/rs/moq-net/src/route/mod.rs index 0037f100cdc..6a74dacea35 100644 --- a/rs/moq-net/src/route/mod.rs +++ b/rs/moq-net/src/route/mod.rs @@ -1733,8 +1733,9 @@ impl Router { } let route = self.selected(id); let starved = route.is_none() && self.infeasible(id).next().is_some(); - if starved { - let want = self.fd[&id].0 + 1; + // Nothing follows the last seqno: its origin rotates to a new identity instead, so + // there is nothing to ask for. + if starved && let Some(want) = self.fd[&id].0.checked_add(1) { let pending = self.pending.entry(id).or_insert(Pending { seqno: want, from: BTreeSet::new(), diff --git a/rs/moq-net/src/route/tests/routing.rs b/rs/moq-net/src/route/tests/routing.rs index e1c22b76552..4f948014415 100644 --- a/rs/moq-net/src/route/tests/routing.rs +++ b/rs/moq-net/src/route/tests/routing.rs @@ -808,6 +808,27 @@ fn a_newer_request_raises_the_pending_one() { assert_eq!(requests(&mut relay), [], "older than the pending one"); } +/// A route starved at the last seqno asks for nothing newer, since its origin rotates +/// to a new identity rather than advance past it. +#[test] +fn a_route_starved_at_the_last_seqno_requests_nothing() { + let (origin, a, b) = (0, 1, 2); + let mut sim = Sim::new(3); + sim.join(origin, a, 1); + sim.join(a, b, 1); + originate(&mut sim, origin, 7, MAX); + assert!(sim.run()); + assert!(sim.route(b, 7).is_some()); + + sim.kill(origin); + originate(&mut sim, origin, 7, 0); + sim.reconnect(origin); + let requests = sim.stats.requests; + assert!(sim.run()); + assert!(sim.starved(a, 7), "seqno 0 is older than the last one a remembers"); + assert_eq!(sim.stats.requests, requests, "nothing follows the last seqno"); +} + /// Each message recomputes only the identity it names, so the work a message /// costs does not grow with how many other origins a node routes to. #[test] diff --git a/rs/moq-net/src/server.rs b/rs/moq-net/src/server.rs index ecbbe1c7c9c..483a1efb6e0 100644 --- a/rs/moq-net/src/server.rs +++ b/rs/moq-net/src/server.rs @@ -1822,7 +1822,7 @@ mod tests { .with_bi(moql_setup()) .withholding_credit(); let start = kio::clock::now(); - let deadline = start + DEFAULT_TIMEOUT; + let deadline = start.saturating_add(DEFAULT_TIMEOUT); let request = Server::new() .accept_request(start, session.clone()) .await @@ -1852,7 +1852,7 @@ mod tests { FakeSession::new(ALPN_LITE_05, []), FakeSession::new(ALPN_LITE, []), ] { - let deadline = kio::clock::now() + std::time::Duration::from_secs(3); + let deadline = kio::clock::now().saturating_add(std::time::Duration::from_secs(3)); let accept = Server::new() .accept_request(kio::clock::now(), session.clone()) .with_deadline(Some(deadline)); @@ -1883,7 +1883,10 @@ mod tests { .session(crate::stats::SessionInfo::new(crate::Path::from_static("room"))), ); request.expired().await; - assert_eq!(kio::clock::now(), start + std::time::Duration::from_secs(5)); + assert_eq!( + kio::clock::now(), + start.saturating_add(std::time::Duration::from_secs(5)) + ); let version = Version::Lite(lite::Version::Lite05); assert_eq!(session.close_code(), Some(version.session_code(&SessionError::Timeout))); let failed = registry.snapshot().sessions()[0].1.sessions_failed; diff --git a/rs/moq-net/src/stats.rs b/rs/moq-net/src/stats.rs index 544f115b4ae..95ea379d967 100644 --- a/rs/moq-net/src/stats.rs +++ b/rs/moq-net/src/stats.rs @@ -3107,7 +3107,7 @@ mod tests { fn activity_follows_recent_payload() { let stats = test_stats(); let tier = Tier::default(); - let at = |secs| Instant::ZERO + std::time::Duration::from_secs(secs); + let at = |secs| Instant::ZERO.saturating_add(std::time::Duration::from_secs(secs)); let activity = |secs| stats.snapshot_at(at(secs)).activity[&tier]; let both = |idle, active| Activity { idle, active }; diff --git a/rs/moq-net/src/transport/memory.rs b/rs/moq-net/src/transport/memory.rs index dce4d9afd3d..fe0847fd133 100644 --- a/rs/moq-net/src/transport/memory.rs +++ b/rs/moq-net/src/transport/memory.rs @@ -462,7 +462,7 @@ struct Message { /// When something a writer sent `latency` ago reaches the reader: `None` at once. fn landing(latency: Duration) -> Option { - (!latency.is_zero()).then(|| kio::clock::now() + latency) + (!latency.is_zero()).then(|| kio::clock::now().saturating_add(latency)) } #[derive(Clone, Copy)] diff --git a/rs/moq-net/tests/integration/support/mock.rs b/rs/moq-net/tests/integration/support/mock.rs index bbe57dfe8d2..e01a01939d2 100644 --- a/rs/moq-net/tests/integration/support/mock.rs +++ b/rs/moq-net/tests/integration/support/mock.rs @@ -62,7 +62,7 @@ impl Conn { } fn arrival(&self) -> Instant { - now() + self.latency() + now().saturating_add(self.latency()) } } diff --git a/rs/moq-quic/benches/common/mod.rs b/rs/moq-quic/benches/common/mod.rs index 2b2b351ea7c..82954b66b8a 100644 --- a/rs/moq-quic/benches/common/mod.rs +++ b/rs/moq-quic/benches/common/mod.rs @@ -447,7 +447,7 @@ impl Pair { let server = Peer::new(server, SocketAddr::new(Ipv6Addr::LOCALHOST.into(), 4433)); let mut pair = Self { - now: Instant::ZERO + Duration::from_secs(3600), + now: Instant::ZERO.saturating_add(Duration::from_secs(3600)), server, clients: Vec::new(), server_cids, @@ -553,7 +553,7 @@ impl Pair { let received = self.server.received; let next = next.unwrap_or_else(|| panic!("stalled with no timer: {received:?}")); assert!( - next <= self.now + STALL, + next <= self.now.saturating_add(STALL), "stalled with no timer due within {STALL:?}: {received:?}" ); self.now = self.now.max(next); @@ -568,7 +568,7 @@ impl Pair { continue; } match self.next_timeout() { - Some(next) if next <= self.now + SETTLE => self.now = self.now.max(next), + Some(next) if next <= self.now.saturating_add(SETTLE) => self.now = self.now.max(next), _ => return, } } @@ -706,7 +706,7 @@ pub(crate) fn deliver(pair: &mut Pair, datagram: BytesMut) { /// A forged exchange never waits on a timer, so without this, state that expires with time, such /// as packets remembered as lost, would pile up across iterations. pub(crate) fn tick(pair: &mut Pair) { - pair.now += TICK; + pair.now = pair.now.saturating_add(TICK); let conn = pair.server.conn(); if conn.poll_timeout().is_some_and(|at| at <= pair.now) { conn.handle_timeout(pair.now); diff --git a/rs/moq-quic/src/connection/bandwidth_probe.rs b/rs/moq-quic/src/connection/bandwidth_probe.rs index f091e43a601..60c0111df7d 100644 --- a/rs/moq-quic/src/connection/bandwidth_probe.rs +++ b/rs/moq-quic/src/connection/bandwidth_probe.rs @@ -163,7 +163,7 @@ impl BandwidthProbe { self.attempt = None; self.misses = self.misses.saturating_add(1); let backoff = BACKOFF.saturating_mul(2u32.saturating_pow(self.misses - 1)); - self.resume = Some(now + backoff.min(MAX_BACKOFF)); + self.resume = Some(now.saturating_add(backoff.min(MAX_BACKOFF))); } } probing && self.resume.is_none_or(|resume| now >= resume) @@ -339,7 +339,7 @@ impl Bucket { } // Rounded up, so the wait earns the whole shortfall rather than re-arming at `now` let nanos = (u128::from(needed - self.tokens) * 1_000_000_000).div_ceil(u128::from(rate)); - Some(now + Duration::from_nanos(u64::try_from(nanos).unwrap_or(u64::MAX))) + Some(now.saturating_add(Duration::from_nanos(u64::try_from(nanos).unwrap_or(u64::MAX)))) } } @@ -400,10 +400,10 @@ mod tests { fn stall(probe: &mut BandwidthProbe, now: Instant) -> Instant { attempt(probe, 0, now, PATH); assert!( - probe.judge(true, Some(PATH), round(1), now + RTT), + probe.judge(true, Some(PATH), round(1), now.saturating_add(RTT)), "stopped before a round of duplicates came back" ); - let missed = now + 2 * RTT; + let missed = now.saturating_add(2 * RTT); assert!( !probe.judge(true, Some(PATH), round(2), missed), "kept filling a stalled attempt" @@ -418,8 +418,13 @@ mod tests { let mut probe = probe(now); for backoff in [BACKOFF, MAX_BACKOFF, MAX_BACKOFF] { now = stall(&mut probe, now); - assert!(!probe.judge(true, Some(PATH), round(2), now + backoff - MS)); - now += backoff; + assert!(!probe.judge( + true, + Some(PATH), + round(2), + now.saturating_add(backoff).saturating_sub(MS) + )); + now = now.saturating_add(backoff); } } @@ -430,14 +435,14 @@ mod tests { let now = Instant::now(); let mut probe = probe(now); attempt(&mut probe, 0, now, PATH); - let late = now + 10 * RTT; + let late = now.saturating_add(10 * RTT); assert!(probe.judge(true, Some(PATH), round(0), late)); assert!(probe.judge(true, Some(PATH), round(1), late)); assert!( - probe.judge(true, Some(PATH + 1), round(1), late + RTT), + probe.judge(true, Some(PATH + 1), round(1), late.saturating_add(RTT)), "a raise in the second round" ); - assert!(probe.judge(true, Some(PATH + 1), round(2), late + RTT)); + assert!(probe.judge(true, Some(PATH + 1), round(2), late.saturating_add(RTT))); } /// An attempt that raises the estimate goes on until the controller's probe ends, which misses @@ -447,11 +452,16 @@ mod tests { let now = Instant::now(); let mut probe = probe(now); attempt(&mut probe, 0, now, PATH); - let later = now + 4 * RTT; + let later = now.saturating_add(4 * RTT); assert!(probe.judge(true, Some(PATH + 1), round(4), later)); assert!(!probe.judge(false, Some(PATH + 1), round(4), later)); - assert!(!probe.judge(true, Some(PATH + 1), round(5), later + BACKOFF - MS)); - assert!(probe.judge(true, Some(PATH + 1), round(5), later + BACKOFF)); + assert!(!probe.judge( + true, + Some(PATH + 1), + round(5), + later.saturating_add(BACKOFF).saturating_sub(MS) + )); + assert!(probe.judge(true, Some(PATH + 1), round(5), later.saturating_add(BACKOFF))); } /// An attempt that begins below the plateau stalls two rounds after it climbs back, rather @@ -462,13 +472,13 @@ mod tests { let now = Instant::now(); let mut probe = probe(now); attempt(&mut probe, 0, now, PATH / 2); - assert!(probe.judge(true, Some(PATH), round(1), now + RTT)); + assert!(probe.judge(true, Some(PATH), round(1), now.saturating_add(RTT))); assert!( - probe.judge(true, Some(PATH * 3 / 4), round(2), now + 2 * RTT), + probe.judge(true, Some(PATH * 3 / 4), round(2), now.saturating_add(2 * RTT)), "stalled before a round of duplicates came back" ); assert!( - !probe.judge(true, Some(PATH), round(3), now + 3 * RTT), + !probe.judge(true, Some(PATH), round(3), now.saturating_add(3 * RTT)), "kept filling once the estimate stopped rising" ); } @@ -479,17 +489,17 @@ mod tests { let mut now = Instant::now(); let mut probe = probe(now); now = stall(&mut probe, now); - now = stall(&mut probe, now + BACKOFF); + now = stall(&mut probe, now.saturating_add(BACKOFF)); // The estimate reached the target, then aged below it assert!(!probe.judge(true, Some(TARGET), round(2), now)); now = stall(&mut probe, now); assert!( - probe.judge(true, Some(PATH), round(2), now + BACKOFF), + probe.judge(true, Some(PATH), round(2), now.saturating_add(BACKOFF)), "the misses before still count" ); - now = stall(&mut probe, now + BACKOFF); + now = stall(&mut probe, now.saturating_add(BACKOFF)); probe.set_target(TARGET); assert!( !probe.judge(true, Some(PATH), round(2), now), diff --git a/rs/moq-quic/src/connection/mod.rs b/rs/moq-quic/src/connection/mod.rs index 8d40a70edca..fba1f2093fb 100644 --- a/rs/moq-quic/src/connection/mod.rs +++ b/rs/moq-quic/src/connection/mod.rs @@ -1105,7 +1105,7 @@ impl Connection { if sent.largest_acked.is_some() { self.spaces[space_id].pending_acks.acks_sent(); self.timers.stop(Timer::MaxAckDelay); - self.next_bundled_ack_time = Some(now + self.next_bundled_ack_delay()); + self.next_bundled_ack_time = Some(now.saturating_add(self.next_bundled_ack_delay())); } // Keep information about the packet around until it gets finalized @@ -1993,7 +1993,8 @@ impl Connection { .as_ref() .expect("update not acknowledged yet") .1; - self.timers.set(Timer::KeyDiscard, start + self.pto(space) * 3); + self.timers + .set(Timer::KeyDiscard, start.saturating_add(self.pto(space) * 3)); } fn on_loss_detection_timeout(&mut self, now: Instant) { @@ -2111,7 +2112,7 @@ impl Connection { } } } else { - let next_loss_time = info.time_sent + loss_delay; + let next_loss_time = info.time_sent.saturating_add(loss_delay); space.loss_time = Some(space.loss_time.map_or(next_loss_time, |x| cmp::min(x, next_loss_time))); persistent_congestion_start = None; } @@ -2209,7 +2210,7 @@ impl Connection { SpaceId::Handshake => SpaceId::Handshake, _ => SpaceId::Initial, }; - return Some((now + duration, space)); + return Some((now.saturating_add(duration), space)); } let mut result = None; @@ -2228,7 +2229,7 @@ impl Connection { let Some(last_ack_eliciting) = self.spaces[space].time_of_last_ack_eliciting_packet else { continue; }; - let pto = last_ack_eliciting + duration; + let pto = last_ack_eliciting.saturating_add(duration); if result.is_none_or(|(earliest_pto, _)| pto < earliest_pto) { result = Some((pto, space)); } @@ -3356,7 +3357,7 @@ impl Connection { .packet_received(now, number, ack_eliciting, &space.dedup) { self.timers - .set(Timer::MaxAckDelay, now + self.ack_frequency.max_ack_delay); + .set(Timer::MaxAckDelay, now.saturating_add(self.ack_frequency.max_ack_delay)); self.next_bundled_ack_time = Some(now); } @@ -3428,7 +3429,7 @@ impl Connection { self.timers.set( Timer::PathValidation, - now + 3 * cmp::max(self.pto(SpaceId::Data), prev_pto), + now.saturating_add(3 * cmp::max(self.pto(SpaceId::Data), prev_pto)), ); } @@ -3812,7 +3813,8 @@ impl Connection { } fn set_close_timer(&mut self, now: Instant) { - self.timers.set(Timer::Close, now + 3 * self.pto(self.highest_space)); + self.timers + .set(Timer::Close, now.saturating_add(3 * self.pto(self.highest_space))); } /// Handle transport parameters received from the peer diff --git a/rs/moq-quic/src/connection/mtud.rs b/rs/moq-quic/src/connection/mtud.rs index 350e9ee3363..93cc5fac498 100644 --- a/rs/moq-quic/src/connection/mtud.rs +++ b/rs/moq-quic/src/connection/mtud.rs @@ -210,7 +210,7 @@ impl EnabledMtuDiscovery { state.last_probed_mtu = probe_udp_payload_size; return Some(probe_udp_payload_size); } else { - let next_mtud_activation = now + self.config.interval; + let next_mtud_activation = now.saturating_add(self.config.interval); self.phase = Phase::Complete(next_mtud_activation); return None; } @@ -245,7 +245,7 @@ impl EnabledMtuDiscovery { /// Called when a black hole is detected fn on_black_hole_detected(&mut self, now: Instant) { // Stop searching, if applicable, and reset the timer - let next_mtud_activation = now + self.config.black_hole_cooldown; + let next_mtud_activation = now.saturating_add(self.config.black_hole_cooldown); self.phase = Phase::Complete(next_mtud_activation); } } @@ -620,7 +620,7 @@ mod tests { assert!(mtud.black_hole_detected(now)); assert_eq!(mtud.current_mtu, 1200); if let Phase::Complete(next_mtud_activation) = mtud.state.unwrap().phase { - assert_eq!(next_mtud_activation, now + Duration::from_secs(60)); + assert_eq!(next_mtud_activation, now.saturating_add(Duration::from_secs(60))); } else { panic!("Unexpected MTUD phase!"); } @@ -642,7 +642,10 @@ mod tests { assert_eq!(mtud.current_mtu, 1_471); // Polling after the interval has passed does (taking the current mtu as lower bound) - assert_eq!(mtud.poll_transmit(now + Duration::from_secs(600), 43), Some(5235)); + assert_eq!( + mtud.poll_transmit(now.saturating_add(Duration::from_secs(600)), 43), + Some(5235) + ); match mtud.state.unwrap().phase { Phase::Searching(state) => { diff --git a/rs/moq-quic/src/connection/mux/tests.rs b/rs/moq-quic/src/connection/mux/tests.rs index 1dcc4f31479..be763f68920 100644 --- a/rs/moq-quic/src/connection/mux/tests.rs +++ b/rs/moq-quic/src/connection/mux/tests.rs @@ -47,7 +47,7 @@ impl Pair { } fn advance(&mut self, by: Duration) { - self.now += by; + self.now = self.now.saturating_add(by); self.client.handle_timeout(self.now); self.server.handle_timeout(self.now); } diff --git a/rs/moq-quic/src/connection/mux/timer.rs b/rs/moq-quic/src/connection/mux/timer.rs index 18f0a456e98..a998a34272b 100644 --- a/rs/moq-quic/src/connection/mux/timer.rs +++ b/rs/moq-quic/src/connection/mux/timer.rs @@ -55,7 +55,7 @@ pub(super) struct Due { impl Timer { pub(super) fn new(handshake: Option, now: Instant) -> Self { Self { - handshake: handshake.map(|timeout| now + timeout), + handshake: handshake.map(|timeout| now.saturating_add(timeout)), idle: None, rtt_interval: None, last_recv: now, @@ -110,11 +110,13 @@ impl Timer { /// The next instant [`Self::poll`] has something to do pub(super) fn next(&self) -> Option { let idle = self.idle.map(|idle| match self.deferred { - Some(since) => since + idle, - None => self.last_activity() + idle, + Some(since) => since.saturating_add(idle), + None => self.last_activity().saturating_add(idle), }); - let keepalive = self.keepalive().map(|every| self.last_send.max(self.last_ping) + every); - let rtt = self.rtt_interval.map(|every| self.last_ping + every); + let keepalive = self + .keepalive() + .map(|every| self.last_send.max(self.last_ping).saturating_add(every)); + let rtt = self.rtt_interval.map(|every| self.last_ping.saturating_add(every)); [self.handshake, idle, keepalive, rtt].into_iter().flatten().min() } @@ -126,8 +128,10 @@ impl Timer { let keepalive = self .keepalive() - .is_some_and(|every| now >= self.last_send.max(self.last_ping) + every); - let rtt = self.rtt_interval.is_some_and(|every| now >= self.last_ping + every); + .is_some_and(|every| now >= self.last_send.max(self.last_ping).saturating_add(every)); + let rtt = self + .rtt_interval + .is_some_and(|every| now >= self.last_ping.saturating_add(every)); if keepalive || rtt { // A ping cannot get past a stalled transport, and must not pile up behind it due.ping = !self.backpressured; @@ -135,11 +139,11 @@ impl Timer { } if let Some(idle) = self.idle - && now >= self.last_activity() + idle + && now >= self.last_activity().saturating_add(idle) { match self.deferred { // A peer that died with our buffers full must not hang here forever - Some(since) => due.idle = now >= since + idle, + Some(since) => due.idle = now >= since.saturating_add(idle), None if self.backpressured => self.deferred = Some(now), None => due.idle = true, } diff --git a/rs/moq-quic/src/connection/rate.rs b/rs/moq-quic/src/connection/rate.rs index 144a9d6dc0c..87c666e9bb3 100644 --- a/rs/moq-quic/src/connection/rate.rs +++ b/rs/moq-quic/src/connection/rate.rs @@ -75,7 +75,7 @@ impl Bucket { self.earned = self.earned.saturating_add(earned).min(full); self.refilled = match self.earned < full { // Advance by exactly the time the whole bytes took, keeping the remainder. - true => Some(prev + nanos(u128::from(earned) * NANOS_PER_SEC / u128::from(self.rate.get()))), + true => Some(prev.saturating_add(nanos(u128::from(earned) * NANOS_PER_SEC / u128::from(self.rate.get())))), false => Some(now), }; } @@ -101,7 +101,9 @@ impl Bucket { // Not refilled yet means full, which holds every `want` up to the burst. let refilled = self.refilled?; // Round up, so the wait always earns the whole shortfall. - Some(refilled + nanos((u128::from(short) * NANOS_PER_SEC).div_ceil(u128::from(self.rate.get())))) + Some(refilled.saturating_add(nanos( + (u128::from(short) * NANOS_PER_SEC).div_ceil(u128::from(self.rate.get())), + ))) } /// When `bytes` may be sent at `now`: `None` for now, or the instant to ask again. @@ -139,9 +141,12 @@ mod tests { bucket.refill(start); bucket.charge(1000); assert_eq!(bucket.available(), 0); - assert_eq!(bucket.ready_at(250), Some(start + Duration::from_millis(250))); + assert_eq!( + bucket.ready_at(250), + Some(start.saturating_add(Duration::from_millis(250))) + ); - bucket.refill(start + Duration::from_millis(250)); + bucket.refill(start.saturating_add(Duration::from_millis(250))); assert_eq!(bucket.available(), 250); assert_eq!(bucket.ready_at(250), None); } @@ -151,10 +156,10 @@ mod tests { let start = Instant::now(); let mut bucket = Bucket::new(rate(1000)); bucket.refill(start); - bucket.refill(start + Duration::from_secs(60)); + bucket.refill(start.saturating_add(Duration::from_secs(60))); assert_eq!(bucket.available(), 1000); bucket.charge(1000); - bucket.refill(start + Duration::from_secs(60)); + bucket.refill(start.saturating_add(Duration::from_secs(60))); assert_eq!(bucket.available(), 0, "time spent full earns nothing after the charge"); } @@ -165,10 +170,13 @@ mod tests { bucket.refill(start); bucket.charge(1500); assert_eq!(bucket.available(), 0); - assert_eq!(bucket.ready_at(1), Some(start + Duration::from_millis(501))); - bucket.refill(start + Duration::from_millis(500)); + assert_eq!( + bucket.ready_at(1), + Some(start.saturating_add(Duration::from_millis(501))) + ); + bucket.refill(start.saturating_add(Duration::from_millis(500))); assert_eq!(bucket.available(), 0); - bucket.refill(start + Duration::from_millis(600)); + bucket.refill(start.saturating_add(Duration::from_millis(600))); assert_eq!(bucket.available(), 100); } @@ -179,7 +187,7 @@ mod tests { bucket.refill(start); bucket.charge(3); for ms in (100..=1000).step_by(100) { - bucket.refill(start + Duration::from_millis(ms)); + bucket.refill(start.saturating_add(Duration::from_millis(ms))); } assert_eq!(bucket.available(), 3); } @@ -201,7 +209,7 @@ mod tests { assert_eq!(bucket.delay(start, 5000), None); bucket.charge(5000); let ready = bucket.delay(start, 5000).unwrap(); - assert_eq!(ready, start + Duration::from_secs(5)); + assert_eq!(ready, start.saturating_add(Duration::from_secs(5))); assert_eq!(bucket.delay(ready, 5000), None); } } diff --git a/rs/moq-quic/src/connection/spaces.rs b/rs/moq-quic/src/connection/spaces.rs index 61ed210cfad..f3bd8efee07 100644 --- a/rs/moq-quic/src/connection/spaces.rs +++ b/rs/moq-quic/src/connection/spaces.rs @@ -646,7 +646,7 @@ impl PendingAcks { pub(super) fn max_ack_delay_timeout(&self, max_ack_delay: Duration) -> Option { self.earliest_ack_eliciting_since_last_ack_sent - .map(|earliest_unacked| earliest_unacked + max_ack_delay) + .map(|earliest_unacked| earliest_unacked.saturating_add(max_ack_delay)) } /// Whether any ACK frames can be sent even if doing so requires a dedicated packet @@ -1042,8 +1042,8 @@ mod test { let mut dedup = Dedup::new(); let t1 = Instant::now(); - let t2 = t1 + Duration::from_millis(2); - let t3 = t2 + Duration::from_millis(5); + let t2 = t1.saturating_add(Duration::from_millis(2)); + let t3 = t2.saturating_add(Duration::from_millis(5)); assert_eq!(acks.ack_delay(t1), Duration::from_millis(0)); assert_eq!(acks.ack_delay(t2), Duration::from_millis(0)); assert_eq!(acks.ack_delay(t3), Duration::from_millis(0)); diff --git a/rs/moq-quic/src/endpoint.rs b/rs/moq-quic/src/endpoint.rs index 105007295d5..0cdb0dc0198 100644 --- a/rs/moq-quic/src/endpoint.rs +++ b/rs/moq-quic/src/endpoint.rs @@ -276,7 +276,7 @@ impl Endpoint { ) -> Option { if self .last_stateless_reset - .is_some_and(|last| last + self.config.min_reset_interval > now) + .is_some_and(|last| last.saturating_add(self.config.min_reset_interval) > now) { debug!("ignoring unexpected packet within minimum stateless reset interval"); return None; diff --git a/rs/moq-quic/src/fuzz/connection.rs b/rs/moq-quic/src/fuzz/connection.rs index 62efbfd2dbc..5c59106ec97 100644 --- a/rs/moq-quic/src/fuzz/connection.rs +++ b/rs/moq-quic/src/fuzz/connection.rs @@ -317,7 +317,7 @@ impl Pair { /// A client and server with a connection mid-handshake. fn new() -> Self { let mut pair = Self { - now: Instant::ZERO + Duration::from_secs(1), + now: Instant::ZERO.saturating_add(Duration::from_secs(1)), client: Peer::new(Side::Client, 4433), server: Peer::new(Side::Server, 4434), sent: HashMap::new(), @@ -729,7 +729,7 @@ impl Pair { } Op::Tick => self.tick(), Op::Advance { millis } => { - self.now += Duration::from_millis(millis.into()); + self.now = self.now.saturating_add(Duration::from_millis(millis.into())); self.poll(Side::Client); self.poll(Side::Server); } diff --git a/rs/moq-quic/src/sim.rs b/rs/moq-quic/src/sim.rs index 41cd82fec15..1d0a37d9680 100644 --- a/rs/moq-quic/src/sim.rs +++ b/rs/moq-quic/src/sim.rs @@ -86,9 +86,9 @@ impl Bottleneck { self.stats.congested += service; } - let done = busy_until + service; + let done = busy_until.saturating_add(service); self.busy_until = Some(done); - let marked = self.marks_ce && done > now + self.max_queue / 2; + let marked = self.marks_ce && done > now.saturating_add(self.max_queue / 2); self.stats.marked += marked as u64; Some((done, marked)) } @@ -144,9 +144,11 @@ impl Link { let copies = 1 + rng.random_bool(self.duplicate) as usize; let arrivals = (0..copies) .map(|_| { - let arrival = sent + latency + rng.random_range(Duration::ZERO..=self.jitter); + let arrival = sent + .saturating_add(latency) + .saturating_add(rng.random_range(Duration::ZERO..=self.jitter)); if rng.random_bool(self.reorder) { - return arrival + rng.random_range(Duration::ZERO..=self.reorder_delay); + return arrival.saturating_add(rng.random_range(Duration::ZERO..=self.reorder_delay)); } let arrival = self.last_arrival.map_or(arrival, |last| last.max(arrival)); let arrival = self.granted(arrival); @@ -164,7 +166,7 @@ impl Link { }; let epoch = *self.grant_epoch.get_or_insert(arrival); let intervals = (arrival - epoch).as_nanos().div_ceil(grant.as_nanos()); - epoch + Duration::from_nanos((intervals * grant.as_nanos()) as u64) + epoch.saturating_add(Duration::from_nanos((intervals * grant.as_nanos()) as u64)) } } diff --git a/rs/moq-quic/src/tests/characterize/endpoint.rs b/rs/moq-quic/src/tests/characterize/endpoint.rs index 85c0cdeaf7a..ecf0aa314f5 100644 --- a/rs/moq-quic/src/tests/characterize/endpoint.rs +++ b/rs/moq-quic/src/tests/characterize/endpoint.rs @@ -117,7 +117,7 @@ fn unknown_cid_gets_stateless_reset() { assert!(reset.len() < packet.len()); assert_eq!(answer(&mut server, now, &packet), Answer::Nothing); - let later = now + server.min_reset_interval(); + let later = now.saturating_add(server.min_reset_interval()); assert!(matches!(answer(&mut server, later, &packet), Answer::Response(_))); } diff --git a/rs/moq-quic/src/tests/mod.rs b/rs/moq-quic/src/tests/mod.rs index 2b8315d060f..5d8b55e97bc 100644 --- a/rs/moq-quic/src/tests/mod.rs +++ b/rs/moq-quic/src/tests/mod.rs @@ -657,7 +657,7 @@ fn reset_secret_resets_connections_each_millisecond() { packet.extend_from_slice(&cids.generate_cid()); packet.resize(100, 0); - let now = start + interval * u32::from(i); + let now = start.saturating_add(interval * u32::from(i)); let event = endpoint.handle( now, Received { @@ -674,7 +674,7 @@ fn reset_secret_resets_connections_each_millisecond() { "connection {i} was not reset" ); let event = endpoint.handle( - now + interval / 2, + now.saturating_add(interval / 2), Received { remote, local_ip: None, @@ -776,7 +776,7 @@ fn stateless_reset_after_draining_keeps_close_reason() { pair.drive_server(); unread.append(&mut pair.client.inbound); // The server sends at most one stateless reset per interval. - pair.time += pair.server.min_reset_interval(); + pair.time = pair.time.saturating_add(pair.server.min_reset_interval()); } assert_eq!(unread.len(), 3, "server should have sent two stateless resets"); @@ -864,7 +864,8 @@ fn stateless_reset_limit() { ); assert!(event.is_none()); let event = endpoint.handle( - time + endpoint.min_reset_interval() - Duration::from_nanos(1), + time.saturating_add(endpoint.min_reset_interval()) + .saturating_sub(Duration::from_nanos(1)), Received { remote, local_ip: None, @@ -876,7 +877,7 @@ fn stateless_reset_limit() { ); assert!(event.is_none()); let event = endpoint.handle( - time + endpoint.min_reset_interval(), + time.saturating_add(endpoint.min_reset_interval()), Received { remote, local_ip: None, @@ -1190,10 +1191,10 @@ fn deferred_accept_uses_handshake_idle_timeout() { let delayed = pair.server.waiting_incoming.pop().unwrap(); // Past the idle timeout, but within the handshake idle timeout. - pair.time = start + Duration::from_secs(3); + pair.time = start.saturating_add(Duration::from_secs(3)); assert!(pair.server.try_accept(delayed, pair.time).is_ok()); - pair.time = start + Duration::from_secs(10); + pair.time = start.saturating_add(Duration::from_secs(10)); assert_matches!(pair.server.try_accept(late, pair.time), Err(ConnectionError::TimedOut)); } @@ -2596,7 +2597,7 @@ fn keep_alive() { let mut pair = Pair::new(Default::default(), server); let (client_ch, server_ch) = pair.connect(); // Run a good while longer than the idle timeout - let end = pair.time + Duration::from_millis(20 * IDLE_TIMEOUT); + let end = pair.time.saturating_add(Duration::from_millis(20 * IDLE_TIMEOUT)); while pair.time < end { if !pair.step() && let Some(time) = min_opt(pair.client.next_wakeup(), pair.server.next_wakeup()) @@ -2616,7 +2617,7 @@ fn idle_keep_alive_gaps( server_ch: ConnectionHandle, idle_timeout: Duration, ) -> Vec { - let end = pair.time + 20 * idle_timeout; + let end = pair.time.saturating_add(20 * idle_timeout); let mut sent = pair.client_conn_mut(client_ch).stats().path.sent_packets; let mut last = pair.time; let mut gaps = Vec::new(); @@ -2758,7 +2759,7 @@ fn cid_rotation() { let mut round: u64 = 1; let mut stop = pair.time; - let end = pair.time + 5 * CID_TIMEOUT; + let end = pair.time.saturating_add(5 * CID_TIMEOUT); use crate::LOC_CID_COUNT; use crate::cid_queue::CidQueue; @@ -2768,7 +2769,7 @@ fn cid_rotation() { let mut right_bound = active_cid_num - 1; while pair.time < end { - stop += CID_TIMEOUT; + stop = stop.saturating_add(CID_TIMEOUT); // Run a while until PushNewCID timer fires while pair.time < stop { if !pair.step() @@ -3699,7 +3700,7 @@ fn probe_through_outage( pair.to_server.loss = 1.0; pair.to_client.loss = if one_way { 0.0 } else { 1.0 }; let start = pair.time; - let end = start + outage; + let end = start.saturating_add(outage); let mut next_ping = ping.map(|_| start); let mut sent = client_probes(pair, client_ch); let mut probes = Vec::new(); @@ -3708,7 +3709,7 @@ fn probe_through_outage( && at <= pair.time { pair.server_conn_mut(server_ch).ping(); - next_ping = Some(at + every); + next_ping = Some(at.saturating_add(every)); } pair.drive_client(); pair.drive_server(); @@ -3737,7 +3738,7 @@ fn probe_through_outage( fn settled_pair(mut pair: Pair) -> (Pair, ConnectionHandle, ConnectionHandle) { pair.latency = Duration::from_millis(10); let (client_ch, server_ch) = pair.connect(); - pair.time += Duration::from_millis(100); + pair.time = pair.time.saturating_add(Duration::from_millis(100)); pair.drive(); pair.client_conn_mut(client_ch).ping(); pair.drive(); @@ -3839,7 +3840,7 @@ fn a_peer_heard_as_the_data_left_still_brings_the_probe_forward() { let rtt = pair.latency * 2; pair.server_conn_mut(server_ch).ping(); pair.drive_server(); - pair.time += pair.latency; + pair.time = pair.time.saturating_add(pair.latency); let s = pair .client_streams(client_ch) .open(Dir::Uni, Default::default()) @@ -4117,7 +4118,11 @@ fn handshake_outlasts_short_idle_timeout() { // The first flight is lost, and so is the first probe, which goes out 2ms late. pair.drive_client(); pair.server.inbound.clear(); - pair.time = pair.client.next_wakeup().unwrap() + Duration::from_millis(2); + pair.time = pair + .client + .next_wakeup() + .unwrap() + .saturating_add(Duration::from_millis(2)); loop { pair.drive_client(); pair.server.inbound.clear(); @@ -4618,7 +4623,7 @@ fn connect_runs_mtud_again_after_600_seconds() { assert_eq!(pair.server_conn_mut(server_ch).path_mtu(), 1389); // The MTU changes after 600 seconds, because now MTUD runs for the second time - pair.time += Duration::from_secs(600); + pair.time = pair.time.saturating_add(Duration::from_secs(600)); pair.drive(); assert!(!pair.client_conn_mut(client_ch).is_closed()); assert!(!pair.server_conn_mut(client_ch).is_closed()); @@ -4761,7 +4766,10 @@ fn single_ack_eliciting_packet_triggers_ack_after_delay() { // The time is start + max_ack_delay let default_max_ack_delay_ms = TransportParameters::default().max_ack_delay.into_inner(); - assert_eq!(pair.time, start + Duration::from_millis(default_max_ack_delay_ms)); + assert_eq!( + pair.time, + start.saturating_add(Duration::from_millis(default_max_ack_delay_ms)) + ); // The ACK delay is properly calculated assert_eq!(pair.client.captured_packets.len(), 1); @@ -4925,13 +4933,13 @@ fn ack_frequency_ack_delayed_from_first_of_flight() { pair.client_conn_mut(client_ch).ping(); pair.drive_client(); - pair.time += Duration::from_millis(5); + pair.time = pair.time.saturating_add(Duration::from_millis(5)); for _ in 0..2 { pair.client_conn_mut(client_ch).ping(); pair.drive_client(); } - pair.time += Duration::from_millis(5); + pair.time = pair.time.saturating_add(Duration::from_millis(5)); // Server: receive the first ping and send no ACK let server_stats_before = pair.server_conn_mut(server_ch).stats(); pair.drive_server(); @@ -4940,7 +4948,7 @@ fn ack_frequency_ack_delayed_from_first_of_flight() { assert_eq!(server_stats_after.frame_tx.acks - server_stats_before.frame_tx.acks, 0); // Server: receive the second and third pings and send no ACK - pair.time += Duration::from_millis(10); + pair.time = pair.time.saturating_add(Duration::from_millis(10)); let server_stats_before = pair.server_conn_mut(server_ch).stats(); pair.drive_server(); let server_stats_after = pair.server_conn_mut(server_ch).stats(); @@ -4948,7 +4956,7 @@ fn ack_frequency_ack_delayed_from_first_of_flight() { assert_eq!(server_stats_after.frame_tx.acks - server_stats_before.frame_tx.acks, 0); // Server: Send an ACK after ACK delay expires - pair.time += Duration::from_millis(20); + pair.time = pair.time.saturating_add(Duration::from_millis(20)); let server_stats_before = pair.server_conn_mut(server_ch).stats(); pair.drive_server(); let server_stats_after = pair.server_conn_mut(server_ch).stats(); @@ -4966,7 +4974,7 @@ fn ack_frequency_ack_sent_after_max_ack_delay() { pair.drive_client(); // Server: receive the ping, send no ACK - pair.time += pair.latency; + pair.time = pair.time.saturating_add(pair.latency); let server_stats_before = pair.server_conn_mut(server_ch).stats(); pair.drive_server(); let server_stats_after = pair.server_conn_mut(server_ch).stats(); @@ -4974,7 +4982,7 @@ fn ack_frequency_ack_sent_after_max_ack_delay() { assert_eq!(server_stats_after.frame_tx.acks - server_stats_before.frame_tx.acks, 0); // Server: send an ack after max_ack_delay has elapsed - pair.time += max_ack_delay; + pair.time = pair.time.saturating_add(max_ack_delay); let server_stats_before = pair.server_conn_mut(server_ch).stats(); pair.drive_server(); let server_stats_after = pair.server_conn_mut(server_ch).stats(); @@ -4995,14 +5003,14 @@ fn ack_frequency_ack_sent_after_packets_above_threshold() { pair.client_conn_mut(client_ch).ping(); pair.drive_client(); - pair.time += Duration::from_millis(5); + pair.time = pair.time.saturating_add(Duration::from_millis(5)); for _ in 0..11 { pair.client_conn_mut(client_ch).ping(); pair.drive_client(); } // Server: receive the first ping, send no ACK - pair.time += Duration::from_millis(5); + pair.time = pair.time.saturating_add(Duration::from_millis(5)); let server_stats_before = pair.server_conn_mut(server_ch).stats(); pair.drive_server(); let server_stats_after = pair.server_conn_mut(server_ch).stats(); @@ -5010,7 +5018,7 @@ fn ack_frequency_ack_sent_after_packets_above_threshold() { assert_eq!(server_stats_after.frame_tx.acks - server_stats_before.frame_tx.acks, 0); // Server: receive the remaining pings, send ACK - pair.time += Duration::from_millis(5); + pair.time = pair.time.saturating_add(Duration::from_millis(5)); let server_stats_before = pair.server_conn_mut(server_ch).stats(); pair.drive_server(); let server_stats_after = pair.server_conn_mut(server_ch).stats(); @@ -5032,7 +5040,7 @@ fn ack_frequency_ack_sent_after_reordered_packets_below_threshold() { pair.client_conn_mut(client_ch).ping(); pair.drive_client(); - pair.time += Duration::from_millis(5); + pair.time = pair.time.saturating_add(Duration::from_millis(5)); // Send and lose an ack-eliciting packet pair.mtu = 0; @@ -5045,7 +5053,7 @@ fn ack_frequency_ack_sent_after_reordered_packets_below_threshold() { pair.drive_client(); // Server: receive first ping, send no ACK - pair.time += Duration::from_millis(5); + pair.time = pair.time.saturating_add(Duration::from_millis(5)); let server_stats_before = pair.server_conn_mut(server_ch).stats(); pair.drive_server(); let server_stats_after = pair.server_conn_mut(server_ch).stats(); @@ -5053,7 +5061,7 @@ fn ack_frequency_ack_sent_after_reordered_packets_below_threshold() { assert_eq!(server_stats_after.frame_tx.acks - server_stats_before.frame_tx.acks, 0); // Server: receive second ping, send no ACK - pair.time += Duration::from_millis(5); + pair.time = pair.time.saturating_add(Duration::from_millis(5)); let server_stats_before = pair.server_conn_mut(server_ch).stats(); pair.drive_server(); let server_stats_after = pair.server_conn_mut(server_ch).stats(); @@ -5072,7 +5080,7 @@ fn ack_frequency_ack_sent_after_reordered_packets_above_threshold() { pair.drive_client(); // Send and lose as many ack-eliciting packets as the default reordering threshold - pair.time += Duration::from_millis(5); + pair.time = pair.time.saturating_add(Duration::from_millis(5)); pair.mtu = 0; for _ in 0..3 { pair.client_conn_mut(client_ch).ping(); @@ -5085,7 +5093,7 @@ fn ack_frequency_ack_sent_after_reordered_packets_above_threshold() { pair.drive_client(); // Server: receive first ping, send no ACK - pair.time += Duration::from_millis(5); + pair.time = pair.time.saturating_add(Duration::from_millis(5)); let server_stats_before = pair.server_conn_mut(server_ch).stats(); pair.drive_server(); let server_stats_after = pair.server_conn_mut(server_ch).stats(); @@ -5093,7 +5101,7 @@ fn ack_frequency_ack_sent_after_reordered_packets_above_threshold() { assert_eq!(server_stats_after.frame_tx.acks - server_stats_before.frame_tx.acks, 0); // Server: receive remaining ping, send ACK - pair.time += Duration::from_millis(5); + pair.time = pair.time.saturating_add(Duration::from_millis(5)); let server_stats_before = pair.server_conn_mut(server_ch).stats(); pair.drive_server(); let server_stats_after = pair.server_conn_mut(server_ch).stats(); @@ -5178,7 +5186,7 @@ fn silently_drop_rejected_initials() { pair.server.assert_no_accept(); // `drive()` stops once the client's only remaining timer is its idle timeout; advance // past it so the unanswered attempt gives up. - pair.time += Duration::from_secs(60); + pair.time = pair.time.saturating_add(Duration::from_secs(60)); pair.drive(); assert_matches!( pair.client_conn_mut(client_ch).error(), @@ -6220,7 +6228,7 @@ struct TestPacer { impl TestPacer { fn on_sent(&mut self, now: Instant, bytes: u16, rate: u64) { let start = self.next.map_or(now, |next| next.max(now)); - self.next = Some(start + Duration::from_secs_f64(f64::from(bytes) / rate as f64)); + self.next = Some(start.saturating_add(Duration::from_secs_f64(f64::from(bytes) / rate as f64))); } fn pace(&self, now: Instant) -> Option { @@ -6814,7 +6822,7 @@ fn untracked_largest_acked_skips_rtt_sample() { let rtt = pair.client_conn_mut(client_ch).rtt(); // Long after the last sample, so timing from that packet's send would stand out. - pair.time += Duration::from_secs(1); + pair.time = pair.time.saturating_add(Duration::from_secs(1)); pair.client_conn_mut(client_ch).ping(); pair.drive_client(); pair.client_conn_mut(client_ch).ping(); @@ -6833,7 +6841,7 @@ fn check_starvation_reported_before_resumed_send(send: impl Fn(&mut Pair, Connec send(&mut pair, client_ch); pair.drive(); - pair.time += Duration::from_millis(20); + pair.time = pair.time.saturating_add(Duration::from_millis(20)); let resumed_at = pair.time; send(&mut pair, client_ch); pair.drive_client(); @@ -6873,7 +6881,7 @@ fn check_blocked_backlog_is_not_app_limited(factory: PacketRecorderFactory) { let (mut pair, client_ch, log) = recorded_pair(factory); // The handshake can drain the pacer, and how far depends on its random sizes. Refill it so // the backlog always starts sending before it is held back. - pair.time += Duration::from_millis(100); + pair.time = pair.time.saturating_add(Duration::from_millis(100)); pair.drive(); let before = log.lock().unwrap().len(); @@ -7200,7 +7208,7 @@ fn bbr_burst_after_long_idle_keeps_learned_bandwidth() { upload(&mut pair, client_ch, server_ch, 4_000_000, |_| {}); let learned = metrics(&mut pair).bandwidth_estimate.unwrap(); - let idle_end = pair.time + Duration::from_secs(300); + let idle_end = pair.time.saturating_add(Duration::from_secs(300)); while pair.time < idle_end { if !pair.step() { pair.time = min_opt(pair.client.next_wakeup(), pair.server.next_wakeup()) diff --git a/rs/moq-quic/src/tests/probe.rs b/rs/moq-quic/src/tests/probe.rs index 74e595094aa..388d48dc76f 100644 --- a/rs/moq-quic/src/tests/probe.rs +++ b/rs/moq-quic/src/tests/probe.rs @@ -321,8 +321,8 @@ fn run(scenario: &Scenario) -> Outcome { // The seed delays the media up to a frame interval past the handshake, any warmup, and the // competing upload's start. Its own generator leaves the run's other draws as they were. let offset = Pcg32::seed_from_u64(scenario.seed).random_range(Duration::ZERO..Duration::from_secs(1) / FPS as u32); - let start = pair.time + offset; - let end = start + scenario.duration; + let start = pair.time.saturating_add(offset); + let end = start.saturating_add(scenario.duration); let mut outcome = Outcome::default(); let mut groups: Vec = Vec::new(); let mut readings: HashMap = HashMap::new(); @@ -336,14 +336,14 @@ fn run(scenario: &Scenario) -> Outcome { loop { let now = pair.time; - if next_rate < scenario.rates.len() && now >= start + scenario.rates[next_rate].0 { + if next_rate < scenario.rates.len() && now >= start.saturating_add(scenario.rates[next_rate].0) { let rate = scenario.rates[next_rate].1; pair.to_server.bottleneck.as_mut().unwrap().set_rate(rate); next_rate += 1; } // Write every frame that is due - let frame_at = |n: u64| start + Duration::from_nanos(n * 1_000_000_000 / FPS); + let frame_at = |n: u64| start.saturating_add(Duration::from_nanos(n * 1_000_000_000 / FPS)); while frame_at(next_frame) <= now && frame_at(next_frame) < end { let at = frame_at(next_frame) - start; let paused = scenario.idle.is_some_and(|(from, until)| at >= from && at < until); @@ -408,7 +408,7 @@ fn run(scenario: &Scenario) -> Outcome { estimate, redundant: conn.stats().path.sent_bandwidth_probe_bytes, }); - next_sample += Duration::from_millis(100); + next_sample = next_sample.saturating_add(Duration::from_millis(100)); } if now >= end { break; @@ -419,7 +419,7 @@ fn run(scenario: &Scenario) -> Outcome { pair.server.next_wakeup(), Some(frame_at(next_frame)), Some(next_sample), - scenario.rates.get(next_rate).map(|&(at, _)| start + at), + scenario.rates.get(next_rate).map(|&(at, _)| start.saturating_add(at)), ]; let next = wakeups.into_iter().flatten().min().unwrap(); pair.time = pair.time.max(next); @@ -503,7 +503,7 @@ fn flush(pair: &mut Pair, ch: ConnectionHandle, groups: &mut [Group]) { fn expire(pair: &mut Pair, ch: ConnectionHandle, groups: &mut [Group], now: Instant, outcome: &mut Outcome) { for group in groups.iter_mut() { let Some(ended) = group.ended else { continue }; - if group.reset.is_some() || now < ended + EXPIRY { + if group.reset.is_some() || now < ended.saturating_add(EXPIRY) { continue; } let mut stream = pair.client_send(ch, group.id); @@ -879,12 +879,12 @@ fn single_packet_writes() { .open(Dir::Uni, Default::default()) .unwrap(); - let end = pair.time + Duration::from_secs(1); + let end = pair.time.saturating_add(Duration::from_secs(1)); let mut next_write = pair.time; while pair.time < end { if pair.time >= next_write { pair.client_send(client_ch, id).write(&mut &[0; 100][..]).unwrap(); - next_write += Duration::from_millis(200); + next_write = next_write.saturating_add(Duration::from_millis(200)); } pair.drive_client(); pair.drive_server(); @@ -953,7 +953,7 @@ fn probe_inflight_limits_only_an_attempt() { // Past the pacer's bursts, short of the first ACK for _ in 0..10 { pair.drive_client(); - pair.time += Duration::from_millis(1); + pair.time = pair.time.saturating_add(Duration::from_millis(1)); } let conn = pair.client_conn_mut(client_ch); assert!(conn.bytes_in_flight() > inflight); diff --git a/rs/moq-quic/src/tests/rate.rs b/rs/moq-quic/src/tests/rate.rs index b4fdca85eaa..53630b2822d 100644 --- a/rs/moq-quic/src/tests/rate.rs +++ b/rs/moq-quic/src/tests/rate.rs @@ -39,7 +39,7 @@ fn cap_receive(rate: u64) -> Limits { /// Drive the pair for `duration`, calling `app` at least every millisecond of simulated time fn run(pair: &mut Pair, duration: Duration, mut app: impl FnMut(&mut Pair)) { - let end = pair.time + duration; + let end = pair.time.saturating_add(duration); while pair.time < end { app(pair); pair.drive_client(); @@ -47,7 +47,7 @@ fn run(pair: &mut Pair, duration: Duration, mut app: impl FnMut(&mut Pair)) { let next = [pair.client.next_wakeup(), pair.server.next_wakeup()] .into_iter() .flatten() - .chain([pair.time + Duration::from_millis(1), end]) + .chain([pair.time.saturating_add(Duration::from_millis(1)), end]) .min() .unwrap(); pair.time = pair.time.max(next); @@ -174,7 +174,7 @@ fn mixed_traffic_under_the_cap_loses_no_datagrams() { let (mut next, mut sent, mut received, mut read) = (pair.time, 0, 0, 0); run(&mut pair, Duration::from_secs(5), |pair| { if pair.time >= next { - next += Duration::from_millis(10); + next = next.saturating_add(Duration::from_millis(10)); pair.client_send(client_ch, s) .write(&mut &vec![0; per_tick][..]) .unwrap(); @@ -474,7 +474,7 @@ fn a_packet_past_the_credit_deadline_grants_it() { pair.time = deadline; pair.client_conn_mut(client_ch).ping(); pair.drive_client(); - pair.time = deadline + LATENCY; + pair.time = deadline.saturating_add(LATENCY); pair.server.timeouts.remove(&server_ch); pair.drive_server(); pair.server.timeouts.insert(server_ch, deadline); diff --git a/rs/moq-quic/src/tests/realtime.rs b/rs/moq-quic/src/tests/realtime.rs index e823cafcb74..1fad1f6329a 100644 --- a/rs/moq-quic/src/tests/realtime.rs +++ b/rs/moq-quic/src/tests/realtime.rs @@ -193,7 +193,7 @@ fn run(preset: &Preset, candidate: &Candidate, seed: u64, competing: bool) -> Ou loop { let now = pair.time; if let Some(&(at, rate)) = steps.last() - && now >= start + at + && now >= start.saturating_add(at) { pair.to_server.bottleneck.as_mut().unwrap().set_rate(rate); steps.pop(); @@ -230,13 +230,13 @@ fn run(preset: &Preset, candidate: &Candidate, seed: u64, competing: bool) -> Ou chunks.finalize(); } - if now >= start + END { + if now >= start.saturating_add(END) { break; } let wakeups = [ pair.client.next_wakeup(), pair.server.next_wakeup(), - steps.last().map(|&(at, _)| start + at), + steps.last().map(|&(at, _)| start.saturating_add(at)), ]; pair.time = pair.time.max(wakeups.into_iter().flatten().min().unwrap()); } diff --git a/rs/moq-quic/src/tests/receive_ts.rs b/rs/moq-quic/src/tests/receive_ts.rs index a3822b0f61c..79b4b073fa8 100644 --- a/rs/moq-quic/src/tests/receive_ts.rs +++ b/rs/moq-quic/src/tests/receive_ts.rs @@ -147,7 +147,7 @@ fn send( loop { let now = pair.time; if let Some((at, rate)) = step - && now >= start + at + && now >= start.saturating_add(at) { pair.to_server.bottleneck.as_mut().unwrap().set_rate(rate); step = None; @@ -167,13 +167,13 @@ fn send( chunks.finalize(); } - if now >= start + end { + if now >= start.saturating_add(end) { return start; } let wakeups = [ pair.client.next_wakeup(), pair.server.next_wakeup(), - step.map(|(at, _)| start + at), + step.map(|(at, _)| start.saturating_add(at)), ]; pair.time = pair.time.max(wakeups.into_iter().flatten().min().unwrap()); } diff --git a/rs/moq-quic/src/tests/scream.rs b/rs/moq-quic/src/tests/scream.rs index a5bdf0c8823..8c7ec9d444d 100644 --- a/rs/moq-quic/src/tests/scream.rs +++ b/rs/moq-quic/src/tests/scream.rs @@ -183,8 +183,8 @@ fn run(scenario: &Scenario) -> Outcome { pair.client_conn_mut(client_ch).set_probe_target(scenario.probe_target); let start = pair.time; - let end = start + path.duration; - let frame_at = |n: u64| start + Duration::from_nanos(n * 1_000_000_000 / FPS); + let end = start.saturating_add(path.duration); + let frame_at = |n: u64| start.saturating_add(Duration::from_nanos(n * 1_000_000_000 / FPS)); let mut outcome = Outcome::default(); let mut groups: Vec = Vec::new(); let mut reading: HashMap = HashMap::new(); @@ -195,7 +195,7 @@ fn run(scenario: &Scenario) -> Outcome { loop { let now = pair.time; if let Some(&(at, rate)) = path.rates.get(next_rate) - && now >= start + at + && now >= start.saturating_add(at) { pair.to_server.bottleneck.as_mut().unwrap().set_rate(rate); next_rate += 1; @@ -278,7 +278,7 @@ fn run(scenario: &Scenario) -> Outcome { estimate: estimate.unwrap_or(0), }); outcome.read.push((now - start, read)); - next_sample += SAMPLE; + next_sample = next_sample.saturating_add(SAMPLE); } if now >= end { break; @@ -289,7 +289,7 @@ fn run(scenario: &Scenario) -> Outcome { pair.server.next_wakeup(), Some(frame_at(next_frame)), Some(next_sample), - path.rates.get(next_rate).map(|&(at, _)| start + at), + path.rates.get(next_rate).map(|&(at, _)| start.saturating_add(at)), ]; pair.time = pair.time.max(wakeups.into_iter().flatten().min().unwrap()); } diff --git a/rs/moq-quic/src/tests/sim.rs b/rs/moq-quic/src/tests/sim.rs index 81108f442c7..c7bc9df6879 100644 --- a/rs/moq-quic/src/tests/sim.rs +++ b/rs/moq-quic/src/tests/sim.rs @@ -465,7 +465,7 @@ fn run(case: &Case) -> Result { if let Some(extra) = &mut extra { extra.receive(&mut pair)?; } - next_read = pair.time + case.read_interval; + next_read = pair.time.saturating_add(case.read_interval); } client.check_alive(&mut pair)?; server.check_alive(&mut pair)?; diff --git a/rs/moq-quic/src/tests/token.rs b/rs/moq-quic/src/tests/token.rs index 89d95790ad4..36d6ce13f21 100644 --- a/rs/moq-quic/src/tests/token.rs +++ b/rs/moq-quic/src/tests/token.rs @@ -114,7 +114,7 @@ fn oversized_retry_token() { panic!("Retry must be routed to the client connection") }; conn.handle_event(event); - let now = now + Duration::from_secs(1); + let now = now.saturating_add(Duration::from_secs(1)); let crypto_before = conn.stats().frame_tx.crypto; buf.clear(); assert_eq!(conn.transmit(now, 1, &mut buf).is_some(), fits); diff --git a/rs/moq-relay/src/auth.rs b/rs/moq-relay/src/auth.rs index a9502dab417..1fb03818983 100644 --- a/rs/moq-relay/src/auth.rs +++ b/rs/moq-relay/src/auth.rs @@ -1900,7 +1900,7 @@ mod tests { assert_eq!(lease.ended().await, lease::Reason::Expired); assert_eq!( kio::clock::now(), - start + Duration::from_secs(10), + start.saturating_add(Duration::from_secs(10)), "expired at the deadline despite re-polling" ); } diff --git a/rs/moq-relay/src/auth/refresh.rs b/rs/moq-relay/src/auth/refresh.rs index 7f6691c31fa..9958157fed5 100644 --- a/rs/moq-relay/src/auth/refresh.rs +++ b/rs/moq-relay/src/auth/refresh.rs @@ -270,7 +270,7 @@ impl Refresh { self.waiting.push_back(Waiting { request, facts, - deadline: kio::clock::now() + super::ATTACH_TIMEOUT, + deadline: kio::clock::now().saturating_add(super::ATTACH_TIMEOUT), }); self.dispatch(); } diff --git a/rs/moq-relay/src/shutdown.rs b/rs/moq-relay/src/shutdown.rs index b0ed440acec..0853065ec37 100644 --- a/rs/moq-relay/src/shutdown.rs +++ b/rs/moq-relay/src/shutdown.rs @@ -32,7 +32,7 @@ impl Trigger { /// Calling it again keeps the first deadline. pub fn start(&self) { let now = Instant::now(); - let deadline = now + self.drain_timeout; + let deadline = now.saturating_add(self.drain_timeout); let first = self.tx.send_if_modified(|started| { let first = started.is_none(); if first { @@ -380,7 +380,7 @@ impl Observer { async fn drain(&self, session: &moq_net::Session, counted: bool) { let now = Instant::now(); - let deadline = self.deadline().unwrap_or(now + self.drain_timeout); + let deadline = self.deadline().unwrap_or(now.saturating_add(self.drain_timeout)); let remaining = deadline.saturating_duration_since(now); // Dropped when this returns or is cancelled (a WebSocket driver ending // first), so the count holds whichever way the session goes. @@ -811,7 +811,7 @@ mod tests { let window = Duration::from_secs(10); let (trigger, shutdown) = Observer::new(window); let mut established = shutdown.serve(); - let draining = shutdown.draining(kio::clock::now() + window); + let draining = shutdown.draining(kio::clock::now().saturating_add(window)); trigger.start(); kio::clock::sleep(window / 2).await; established.closed(); diff --git a/rs/moq-relay/src/stun.rs b/rs/moq-relay/src/stun.rs index fbc05ff9806..6ffa8fa7a86 100644 --- a/rs/moq-relay/src/stun.rs +++ b/rs/moq-relay/src/stun.rs @@ -515,7 +515,7 @@ mod tests { } let started = std::time::Instant::now(); for request in 0..requests { - let now = now + Duration::from_millis(100 * u64::from(request + 1)); + let now = now.saturating_add(Duration::from_millis(100 * u64::from(request + 1))); for ip in 0..sources { limits.source(std::hint::black_box(IpAddr::V4(ip.into())), now).unwrap(); } diff --git a/rs/moq-relay/src/web.rs b/rs/moq-relay/src/web.rs index 6c929248b58..b641392a4c3 100644 --- a/rs/moq-relay/src/web.rs +++ b/rs/moq-relay/src/web.rs @@ -1067,7 +1067,7 @@ async fn serve_fetch( tracing::info!(%broadcast, %track, "fetching track"); - let deadline = kio::clock::now() + tokio::time::Duration::from_secs(30); + let deadline = kio::clock::now().saturating_add(tokio::time::Duration::from_secs(30)); // The lease outlives this handler: the body streams after it returns, so the // response holds the lease and ends it when the last frame is served. diff --git a/rs/moq-relay/tests/integration/runtime_uring.rs b/rs/moq-relay/tests/integration/runtime_uring.rs index 5b793d75b31..a1204c93f76 100644 --- a/rs/moq-relay/tests/integration/runtime_uring.rs +++ b/rs/moq-relay/tests/integration/runtime_uring.rs @@ -362,7 +362,7 @@ async fn uring_workers_report_link_facts() { } // A client can see its session established before the relay lists it. - let deadline = kio::clock::now() + TIMEOUT; + let deadline = kio::clock::now().saturating_add(TIMEOUT); let views = loop { let views = sessions.list(&Default::default()); if views.len() == 4 { @@ -447,9 +447,9 @@ async fn drain_on_the_trigger(version: Option) { let pending = admissions.next().await.expect("pending admission"); // The relay fixes its deadline inside `start`, so these bracket it: what is // left of each bounds what the relay tells the arrival from below and above. - let earliest = kio::clock::now() + DRAIN; + let earliest = kio::clock::now().saturating_add(DRAIN); trigger.start(); - let deadline = kio::clock::now() + DRAIN; + let deadline = kio::clock::now().saturating_add(DRAIN); let draining = established.draining().expect("connected"); let goaway = kio::clock::timeout(TIMEOUT, kio::wait(|waiter| draining.poll(waiter))) .await @@ -473,7 +473,7 @@ async fn drain_on_the_trigger(version: Option) { // distinguishable from a fresh one. Measured from the deadline, not from // the first session leaving, so a slow close cannot push the admission // past the deadline (where the relay rejects it). - kio::clock::sleep_until(deadline - DRAIN / 2).await; + kio::clock::sleep_until(deadline.saturating_sub(DRAIN / 2)).await; } let (_arrival_lease, arrival_consumer) = moq_auth::lease::Producer::new(moq_auth::Grant::new(all(), all())); let granted = kio::clock::now(); diff --git a/rs/moq-relay/tests/integration/shutdown_signal.rs b/rs/moq-relay/tests/integration/shutdown_signal.rs index fd5f714e701..cf95cae703e 100644 --- a/rs/moq-relay/tests/integration/shutdown_signal.rs +++ b/rs/moq-relay/tests/integration/shutdown_signal.rs @@ -333,7 +333,7 @@ async fn a_session_arriving_mid_drain_gets_what_is_left_inner() { // Keeps the relay up for the arrival below once `established` leaves. let _straggler = straggler(port).await; trigger.start(); - let deadline = kio::clock::now() + DRAIN_TIMEOUT; + let deadline = kio::clock::now().saturating_add(DRAIN_TIMEOUT); let goaway = kio::clock::timeout(Duration::from_secs(5), kio::wait(|waiter| draining.poll(waiter))) .await .expect("no GOAWAY within 5s of the trigger") @@ -418,7 +418,7 @@ async fn a_trigger_before_run_keeps_the_deadline_inner() { // Fired while `run` is still starting. The session deadline is this instant; // `drain` must not open a fresh window when it finally observes the watch. trigger.start(); - let deadline = kio::clock::now() + DRAIN_TIMEOUT; + let deadline = kio::clock::now().saturating_add(DRAIN_TIMEOUT); kio::clock::sleep(DRAIN_TIMEOUT / 2).await; let run = tokio::spawn(relay.run()); @@ -556,7 +556,7 @@ fn relay_config() -> Config { /// Wait until the internal listener on `port` reports `line` at `/metrics`. async fn wait_metric(port: u16, line: &str) { - let deadline = kio::clock::now() + Duration::from_secs(5); + let deadline = kio::clock::now().saturating_add(Duration::from_secs(5)); loop { let metrics = reqwest::get(format!("http://127.0.0.1:{port}/metrics")) .await diff --git a/rs/moq-room/src/chat.rs b/rs/moq-room/src/chat.rs index 0639bd8d5e1..55d74b30911 100644 --- a/rs/moq-room/src/chat.rs +++ b/rs/moq-room/src/chat.rs @@ -92,7 +92,7 @@ impl Publisher { self.prune()?; self.producer .push(moq_net::Timed::from(&text.to_owned()).at(moq_net::Timestamp::now()))?; - self.expires.push_back(kio::clock::now() + HISTORY); + self.expires.push_back(kio::clock::now().saturating_add(HISTORY)); Ok(()) } diff --git a/rs/moq-rtmp/src/dial.rs b/rs/moq-rtmp/src/dial.rs index 369cd3c49da..4947fecc6a7 100644 --- a/rs/moq-rtmp/src/dial.rs +++ b/rs/moq-rtmp/src/dial.rs @@ -561,13 +561,13 @@ impl Publisher { Ok(Self { importer, catalog, - media_deadline: kio::clock::Instant::now() + crate::server::PUBLISH_IDLE_TIMEOUT, + media_deadline: kio::clock::Instant::now().saturating_add(crate::server::PUBLISH_IDLE_TIMEOUT), route, }) } fn push(&mut self, tag_type: u8, timestamp: u32, body: &Bytes) -> anyhow::Result<()> { - self.media_deadline = kio::clock::Instant::now() + crate::server::PUBLISH_IDLE_TIMEOUT; + self.media_deadline = kio::clock::Instant::now().saturating_add(crate::server::PUBLISH_IDLE_TIMEOUT); flv::import(&mut self.importer, tag_type, timestamp, body) } diff --git a/rs/moq-rtmp/src/server.rs b/rs/moq-rtmp/src/server.rs index 866027730a8..557233d0b5f 100644 --- a/rs/moq-rtmp/src/server.rs +++ b/rs/moq-rtmp/src/server.rs @@ -421,7 +421,7 @@ impl Server { tracing::warn!(%err, "failed to accept RTMP connection; continuing"); let wait = self.accept_delay.mul_f64(0.5 + kio::clock::rng().random::() / 2.0); self.accept_delay = (self.accept_delay * 2).min(ACCEPT_RETRY_MAX); - self.accept_retry = Some(kio::clock::Instant::now() + wait); + self.accept_retry = Some(kio::clock::Instant::now().saturating_add(wait)); } }, } @@ -1227,7 +1227,7 @@ async fn pump( peer: SocketAddr, ) -> anyhow::Result { let mut buffer = [0u8; READ_BUFFER]; - let mut media_deadline = kio::clock::Instant::now() + PUBLISH_IDLE_TIMEOUT; + let mut media_deadline = kio::clock::Instant::now().saturating_add(PUBLISH_IDLE_TIMEOUT); loop { let mut finished = false; while let Some(result) = work.pop_front() { @@ -1240,11 +1240,11 @@ async fn pump( ServerSessionResult::RaisedEvent(event) => match event { // A timestamp restart ends this publisher; isolated malformed tags are skipped. ServerSessionEvent::AudioDataReceived { data, timestamp, .. } => { - media_deadline = kio::clock::Instant::now() + PUBLISH_IDLE_TIMEOUT; + media_deadline = kio::clock::Instant::now().saturating_add(PUBLISH_IDLE_TIMEOUT); publisher.push(flv::TAG_AUDIO, timestamp.value, &data)?; } ServerSessionEvent::VideoDataReceived { data, timestamp, .. } => { - media_deadline = kio::clock::Instant::now() + PUBLISH_IDLE_TIMEOUT; + media_deadline = kio::clock::Instant::now().saturating_add(PUBLISH_IDLE_TIMEOUT); publisher.push(flv::TAG_VIDEO, timestamp.value, &data)?; } ServerSessionEvent::PublishStreamFinished { .. } => finished = true, diff --git a/rs/moq-rtsp/src/client.rs b/rs/moq-rtsp/src/client.rs index 2ea8bb7318a..74693adad65 100644 --- a/rs/moq-rtsp/src/client.rs +++ b/rs/moq-rtsp/src/client.rs @@ -224,14 +224,14 @@ impl Client { tracing::info!(%url, streams = tracks.len(), "RTSP session playing"); let playing = kio::clock::now(); // Measured from the last frame, so RTCP reports alone cannot keep a dead camera alive. - let mut deadline = playing + self.timeout; + let mut deadline = playing.saturating_add(self.timeout); while let Some(item) = kio::clock::timeout(deadline - kio::clock::now(), session.next()) .await .map_err(|_| Error::Stalled(self.timeout))? { let item = item?; if matches!(item, CodecItem::VideoFrame(_) | CodecItem::AudioFrame(_)) { - deadline = kio::clock::now() + self.timeout; + deadline = kio::clock::now().saturating_add(self.timeout); } if ingest.push(item, session.streams())?.is_some() { tracing::warn!(%url, "RTSP timeline jumped, ending the session"); diff --git a/rs/moq-shaper/src/lib.rs b/rs/moq-shaper/src/lib.rs index 9ae947789d6..8eea72df2d2 100644 --- a/rs/moq-shaper/src/lib.rs +++ b/rs/moq-shaper/src/lib.rs @@ -358,7 +358,7 @@ impl Rate { .checked_sub(self.cost(self.burst)) .map_or(at, |drained| drained.max(at)); let owed = full_at.saturating_duration_since(drained); - drained + owed.mul_f64(self.bits_per_second as f64 / new.bits_per_second as f64) + drained.saturating_add(owed.mul_f64(self.bits_per_second as f64 / new.bits_per_second as f64)) } } @@ -970,7 +970,7 @@ impl Held { if let Some(closes) = self.closes.filter(|&closes| closes <= arrived) { self.release(closes, ready, tally); } - self.closes.get_or_insert(arrived + batch.window); + self.closes.get_or_insert(arrived.saturating_add(batch.window)); self.parcels.push(parcel); if self.parcels.len() >= batch.count { self.release(arrived, ready, tally); @@ -1220,7 +1220,7 @@ impl Link { if let Some(rate) = &self.profile.rate { // GCRA: a datagram may leave once the backlog, itself included, is // within the burst allowance. - let full_at = self.full_at.max(now) + rate.cost(size as u64); + let full_at = self.full_at.max(now).saturating_add(rate.cost(size as u64)); let start = full_at .checked_sub(rate.cost(rate.burst)) .map_or(now, |start| start.max(now)); @@ -1242,7 +1242,9 @@ impl Link { } else if self.jitter == Jitter::Gaussian { // A queue: nothing leaves before the datagram in front of it. let wait = self.profile.delay.as_secs_f64() + self.profile.jitter.as_secs_f64() * spread; - let leave = (depart + Duration::from_secs_f64(wait.max(0.0))).max(self.floor); + let leave = depart + .saturating_add(Duration::from_secs_f64(wait.max(0.0))) + .max(self.floor); // Counted like the uniform model whenever a delay is configured, so // the chance `verify` holds it to is the same. delayed = !self.profile.delay.is_zero() || leave > depart; @@ -1250,7 +1252,7 @@ impl Link { depart = leave; } else if !self.profile.delay.is_zero() { let jitter = self.profile.jitter.as_secs_f64() * spread; - depart += Duration::from_secs_f64(self.profile.delay.as_secs_f64() + jitter); + depart = depart.saturating_add(Duration::from_secs_f64(self.profile.delay.as_secs_f64() + jitter)); delayed = true; } if delayed { @@ -1293,7 +1295,7 @@ mod tests { let tally = Tally::default(); for index in 0..3 { link.push( - start + Duration::from_secs(index * 10), + start.saturating_add(Duration::from_secs(index * 10)), vec![0; 1000], &socket, LOCALHOST, @@ -1307,7 +1309,10 @@ mod tests { ); burst.completed().await.unwrap(); for _ in 0..2 { - assert_eq!(received.try_recv().unwrap().arrived, start + Duration::from_secs(20)); + assert_eq!( + received.try_recv().unwrap().arrived, + start.saturating_add(Duration::from_secs(20)) + ); } assert!(received.try_recv().is_err()); } @@ -1421,7 +1426,7 @@ mod tests { let a = Tally::default(); let b = Tally::default(); for index in 0..32 { - let now = start + Duration::from_secs(index * 10); + let now = start.saturating_add(Duration::from_secs(index * 10)); gated.push(now, vec![0; 1000], &socket, LOCALHOST, &a); plain.push(now, vec![0; 1000], &socket, LOCALHOST, &b); } @@ -1973,7 +1978,7 @@ mod tests { let mut link = Link::new(profile, options, 7, 0, now, queue); let tally = Tally::default(); let mut sent: Vec<(u32, Instant)> = (0..count) - .filter_map(|id| Some((id, link.treat(now + spacing * id, 4, &tally)?.0))) + .filter_map(|id| Some((id, link.treat(now.saturating_add(spacing * id), 4, &tally)?.0))) .collect(); // Ties leave in arrival order, which is id order here. sent.sort_by_key(|&(id, at)| (at, id)); @@ -2270,19 +2275,19 @@ mod tests { let mut ready = Vec::new(); held.hold(batch, parcel(now), &mut ready, &tally); - held.hold(batch, parcel(now + ms(10)), &mut ready, &tally); + held.hold(batch, parcel(now.saturating_add(ms(10))), &mut ready, &tally); assert!(ready.is_empty(), "a partial batch leaked"); assert_eq!( held.closes, - Some(now + ms(160)), + Some(now.saturating_add(ms(160))), "the window counts from the first arrival" ); - held.hold(batch, parcel(now + ms(20)), &mut ready, &tally); + held.hold(batch, parcel(now.saturating_add(ms(20))), &mut ready, &tally); let leaves: Vec = ready.drain(..).map(|parcel| parcel.at).collect(); assert_eq!( leaves, - [now + ms(20); 3], + [now.saturating_add(ms(20)); 3], "a full batch leaves together, as the latest would" ); assert_eq!( @@ -2292,9 +2297,9 @@ mod tests { ); // The window closes a batch that never fills, and nothing in it leaves sooner. - held.hold(batch, parcel(now + ms(30)), &mut ready, &tally); + held.hold(batch, parcel(now.saturating_add(ms(30))), &mut ready, &tally); let closes = held.closes.unwrap(); - assert_eq!(closes, now + ms(190)); + assert_eq!(closes, now.saturating_add(ms(190))); held.release(closes, &mut ready, &tally); assert_eq!(ready.iter().map(|parcel| parcel.at).collect::>(), [closes]); assert_eq!(tally.snapshot().delayed, 3); @@ -2302,12 +2307,12 @@ mod tests { // A datagram that arrives after the window closed, before its timer fired, // starts the next batch rather than joining the closed one. - held.hold(batch, parcel(now + ms(200)), &mut ready, &tally); + held.hold(batch, parcel(now.saturating_add(ms(200))), &mut ready, &tally); let closes = held.closes.unwrap(); - held.hold(batch, parcel(closes + ms(1)), &mut ready, &tally); + held.hold(batch, parcel(closes.saturating_add(ms(1))), &mut ready, &tally); assert_eq!(ready.iter().map(|parcel| parcel.at).collect::>(), [closes]); assert_eq!(held.parcels.len(), 1, "the late datagram joined the closed batch"); - assert_eq!(held.closes, Some(closes + ms(1) + ms(160))); + assert_eq!(held.closes, Some(closes.saturating_add(ms(1)).saturating_add(ms(160)))); assert_eq!(tally.snapshot().delayed, 4); assert_eq!(tally.batched.load(Ordering::Relaxed), 4); @@ -2317,13 +2322,13 @@ mod tests { let mut held = Held::default(); let tally = Tally::default(); let late = Parcel { - at: now + ms(1000), + at: now.saturating_add(ms(1000)), delayed: true, ..parcel(now) }; held.hold(batch, late, &mut ready, &tally); held.release(held.closes.unwrap(), &mut ready, &tally); - assert_eq!(ready[0].at, now + ms(1000)); + assert_eq!(ready[0].at, now.saturating_add(ms(1000))); assert_eq!(tally.batched.load(Ordering::Relaxed), 0); } @@ -2499,9 +2504,9 @@ mod tests { let mut link = Link::new(&profile, &options, 7, 0, start, queue); assert_eq!(owed(&mut link, start, &[16]), [ms(5)]); - assert_eq!(owed(&mut link, start + ms(100), &[16]), [ms(60)]); + assert_eq!(owed(&mut link, start.saturating_add(ms(100)), &[16]), [ms(60)]); // The step back restores what the run opened with. - assert_eq!(owed(&mut link, start + ms(200), &[16]), [ms(5)]); + assert_eq!(owed(&mut link, start.saturating_add(ms(200)), &[16]), [ms(5)]); } #[test] @@ -2526,8 +2531,8 @@ mod tests { let mut lost = |at: Instant| (0..100).filter(|_| link.treat(at, 16, &tally).is_none()).count(); assert_eq!(lost(start), 0, "the profile opens clean"); - assert_eq!(lost(start + secs(30)), 100, "the step lost nothing"); - assert_eq!(lost(start + secs(60)), 0, "the step back never cleared"); + assert_eq!(lost(start.saturating_add(secs(30))), 100, "the step lost nothing"); + assert_eq!(lost(start.saturating_add(secs(60))), 0, "the step back never cleared"); } #[tokio::test(start_paused = true)] @@ -2681,7 +2686,10 @@ mod tests { let start = Instant::now(); let mut link = Link::new(&profile, &options, 7, 0, start, queue); let tally = Tally::default(); - let mut leave = |at: Duration| link.treat(start + at, 1000, &tally).map(|(at, _)| at - start); + let mut leave = |at: Duration| { + link.treat(start.saturating_add(at), 1000, &tally) + .map(|(at, _)| at - start) + }; let queued: Vec<_> = (0..6).map(|_| leave(Duration::ZERO).unwrap()).collect(); assert_eq!(queued, [secs(0), secs(0), secs(0), secs(1), secs(2), secs(3)]); @@ -2717,7 +2725,7 @@ mod tests { assert_eq!(owed(&mut link, start, &[1000; 3]), [secs(0), secs(1), secs(2)]); // Behind the one leaving at 2s, then half a second apart at the new rate. - let after = start + ms(500); + let after = start.saturating_add(ms(500)); let owed = owed(&mut link, after, &[1000; 2]); assert_eq!(owed, [ms(2000), ms(2500)]); } @@ -2732,7 +2740,10 @@ mod tests { let (queue, _) = mpsc::unbounded_channel(); let start = Instant::now(); let mut link = Link::new(&Profile::default(), &options, 7, 0, start, queue); - assert_eq!(owed(&mut link, start + Duration::from_secs(1), &[16]), [Duration::ZERO]); + assert_eq!( + owed(&mut link, start.saturating_add(Duration::from_secs(1)), &[16]), + [Duration::ZERO] + ); } #[tokio::test(start_paused = true)] diff --git a/rs/moq-shaper/src/main.rs b/rs/moq-shaper/src/main.rs index 19da706ec9f..d834d35e5f9 100644 --- a/rs/moq-shaper/src/main.rs +++ b/rs/moq-shaper/src/main.rs @@ -128,7 +128,7 @@ async fn main() -> anyhow::Result<()> { // The first tick is a full period in, so a line reports traffic, not the start. let mut interval = args .report_interval - .map(|period| kio::clock::interval_at(kio::clock::now() + period, period)); + .map(|period| kio::clock::interval_at(kio::clock::now().saturating_add(period), period)); let shutdown = shutdown(); tokio::pin!(shutdown); loop { diff --git a/rs/moq-srt/src/server.rs b/rs/moq-srt/src/server.rs index b7c2751210d..7b5ccae89e8 100644 --- a/rs/moq-srt/src/server.rs +++ b/rs/moq-srt/src/server.rs @@ -649,7 +649,7 @@ mod tests { #[test] fn chunker_flushes_before_the_pacing_instant_changes() { let first = moq_net::time::Instant::now(); - let second = first + Duration::from_millis(25); + let second = first.saturating_add(Duration::from_millis(25)); let mut chunker = SrtChunker::default(); assert!(chunker.push(first, &[1; 188]).is_empty()); @@ -732,23 +732,27 @@ mod tests { /// step as a rewind would drag the whole stream onto the reorder's instant. #[test] fn a_reorder_is_not_a_rewind() { - let start = Instant::ZERO + Duration::from_secs(1); + let start = Instant::ZERO.saturating_add(Duration::from_secs(1)); let mut egress = Egress::default(); let first = egress.push(&frame(1_400_000, &[1; SRT_PAYLOAD]), 0, start); let edge = egress.push( &frame(1_483_000, &[2; SRT_PAYLOAD]), 0, - start + Duration::from_millis(1), + start.saturating_add(Duration::from_millis(1)), ); let reorder = egress.push( &frame(1_442_000, &[3; SRT_PAYLOAD]), 0, - start + Duration::from_millis(2), + start.saturating_add(Duration::from_millis(2)), ); assert_eq!(first[0].0, start, "the first payload anchors the connection"); - assert_eq!(edge[0].0, start + Duration::from_millis(1), "the live edge re-anchors"); + assert_eq!( + edge[0].0, + start.saturating_add(Duration::from_millis(1)), + "the live edge re-anchors" + ); assert_eq!(reorder[0].0, first[0].0, "the reorder is clamped, not re-anchored"); } @@ -766,13 +770,13 @@ mod tests { let after = egress.push( &frame(WRAP + 25_000, &[2; SRT_PAYLOAD]), 0, - start + Duration::from_millis(50), + start.saturating_add(Duration::from_millis(50)), ); assert_eq!(before[0].0, start); assert_eq!( after[0].0, - start + Duration::from_millis(50), + start.saturating_add(Duration::from_millis(50)), "the wrap paces like any other 50ms step" ); } @@ -791,12 +795,12 @@ mod tests { // Ten minutes into the program, on the muxer's 25ms grid. let first = egress.push(&frame(600_000_000, &[1; SRT_PAYLOAD]), 0, start); - let second = egress.push(&frame(600_025_000, &[1; SRT_PAYLOAD]), 0, start + SLOT); + let second = egress.push(&frame(600_025_000, &[1; SRT_PAYLOAD]), 0, start.saturating_add(SLOT)); assert_eq!(first[0].0, start, "the first payload anchors the connection"); - assert_eq!(second[0].0, start + SLOT); + assert_eq!(second[0].0, start.saturating_add(SLOT)); // The program switches to an instance whose timeline starts at zero. - let mut now = start + 2 * SLOT; + let mut now = start.saturating_add(2 * SLOT); let switched = egress.push(&frame(0, &[2; SRT_PAYLOAD]), 1, now); assert_eq!(switched[0].0, now, "the new generation becomes the live edge"); @@ -804,7 +808,7 @@ mod tests { // one of them is ten minutes in the past and clamps to `start`, so the receiver // gets the next ten minutes of program under a single timestamp. for slot in 1..=8u64 { - now += SLOT; + now = now.saturating_add(SLOT); let chunks = egress.push(&frame(slot * 25_000, &[3; SRT_PAYLOAD]), 1, now); assert_eq!(chunks[0].0, now, "slot {slot} paces off the new anchor"); } @@ -830,11 +834,23 @@ mod tests { assert_eq!(chunks[1].1.as_ref(), [2u8; SRT_PAYLOAD].as_slice()); // And a tail paced earlier keeps that earlier instant rather than the new clock's. - assert!(egress.push(&frame(25_000, &[3; 188]), 1, start + SLOT).is_empty()); - let chunks = egress.push(&frame(0, &[4; SRT_PAYLOAD]), 2, start + 2 * SLOT); - assert_eq!(chunks[0].0, start + SLOT, "the old tail keeps its own instant"); + assert!( + egress + .push(&frame(25_000, &[3; 188]), 1, start.saturating_add(SLOT)) + .is_empty() + ); + let chunks = egress.push(&frame(0, &[4; SRT_PAYLOAD]), 2, start.saturating_add(2 * SLOT)); + assert_eq!( + chunks[0].0, + start.saturating_add(SLOT), + "the old tail keeps its own instant" + ); assert_eq!(chunks[0].1.as_ref(), [3u8; 188].as_slice()); - assert_eq!(chunks[1].0, start + 2 * SLOT, "the new generation is the live edge"); + assert_eq!( + chunks[1].0, + start.saturating_add(2 * SLOT), + "the new generation is the live edge" + ); } /// End to end over a real SRT receiver: a publisher that declares a marker after diff --git a/rs/moq-stats/src/produce.rs b/rs/moq-stats/src/produce.rs index 530e5af6f52..cc046adb132 100644 --- a/rs/moq-stats/src/produce.rs +++ b/rs/moq-stats/src/produce.rs @@ -1989,9 +1989,9 @@ mod tests { .unwrap(); let start = kio::clock::now(); for phase in (0..1500).step_by(100) { - let at = start + Duration::from_micros(phase); + let at = start.saturating_add(Duration::from_micros(phase)); assert_eq!( - drain.stamp(at + interval).group, + drain.stamp(at.saturating_add(interval)).group, drain.stamp(at).group + 1, "phase {phase}us" ); @@ -3116,7 +3116,7 @@ mod tests { // Empty, acme lingers: still listed, its totals keeping the ended session. drop(acme); - let lingering = start + Duration::from_secs(9); + let lingering = start.saturating_add(Duration::from_secs(9)); let stats = crate::Consumer::new(broadcast.clone(), Default::default()); let mut acme = stats.bucket(moq_net::Path::from_static("acme")).await.unwrap(); let mut frame = pumping_at(&mut drain, lingering, acme.next()).await.unwrap().unwrap(); @@ -3126,7 +3126,7 @@ mod tests { assert_eq!(frame.tiers[""].sessions.sessions_ended, 1); // Past the linger, acme alone is unlisted and its subscription ends. - let lingered = start + Duration::from_secs(20); + let lingered = start.saturating_add(Duration::from_secs(20)); assert_eq!( next_listed(&mut drain, lingered, &mut tracks).await, ("acme".into(), false) diff --git a/rs/moq-stats/src/produce_bench.rs b/rs/moq-stats/src/produce_bench.rs index 56fd2ef9e04..628880e1bd0 100644 --- a/rs/moq-stats/src/produce_bench.rs +++ b/rs/moq-stats/src/produce_bench.rs @@ -51,7 +51,7 @@ impl Driver { /// Drain the registry and encode every track once, one interval after the last tick. pub fn tick(&mut self) -> FrameBytes { - self.now += self.drain.task.interval; + self.now = self.now.saturating_add(self.drain.task.interval); self.drain.collect(); self.drain.publish(self.now); self.drain.bucket_frame_bytes() diff --git a/rs/moq-tokio/src/failover.rs b/rs/moq-tokio/src/failover.rs index d3c0b55f8b2..758a976a6bc 100644 --- a/rs/moq-tokio/src/failover.rs +++ b/rs/moq-tokio/src/failover.rs @@ -162,7 +162,7 @@ where match addr { Some(addr) => { start(addr, &mut attempts); - ready = kio::clock::now() + delay; + ready = kio::clock::now().saturating_add(delay); } None => exhausted = true, } diff --git a/rs/moq-tokio/src/mdns.rs b/rs/moq-tokio/src/mdns.rs index a29434b0634..1bc20cb9f70 100644 --- a/rs/moq-tokio/src/mdns.rs +++ b/rs/moq-tokio/src/mdns.rs @@ -715,7 +715,7 @@ fn addr_url(addr: SocketAddr) -> Option { /// refusing to start over one of those would be wrong; an error only decides the /// outcome if *nothing* announces. async fn announced(monitor: &mdns_sd::Receiver) -> Result<()> { - let deadline = kio::clock::now() + ANNOUNCE_TIMEOUT; + let deadline = kio::clock::now().saturating_add(ANNOUNCE_TIMEOUT); // Kept so a total failure reports why rather than just "timed out". let mut failure = None; diff --git a/rs/moq-tokio/src/quic/driver/endpoint.rs b/rs/moq-tokio/src/quic/driver/endpoint.rs index 087ef733ceb..0d7541e0734 100644 --- a/rs/moq-tokio/src/quic/driver/endpoint.rs +++ b/rs/moq-tokio/src/quic/driver/endpoint.rs @@ -1139,7 +1139,7 @@ mod tests { // Calibrate the next receive cycles to allow two work items each. state.recv_limiter.start_cycle(|| now); state.recv_limiter.record_work(2); - state.recv_limiter.finish_cycle(|| now + RECV_TIME_BOUND); + state.recv_limiter.finish_cycle(|| now.saturating_add(RECV_TIME_BOUND)); let socket = ErrorSocket { error, diff --git a/rs/moq-tokio/src/quic/driver/work_limiter.rs b/rs/moq-tokio/src/quic/driver/work_limiter.rs index e61b06cd9c1..ec208b487a0 100644 --- a/rs/moq-tokio/src/quic/driver/work_limiter.rs +++ b/rs/moq-tokio/src/quic/driver/work_limiter.rs @@ -217,7 +217,7 @@ mod tests { fn advance_time(duration: Duration) { TIME.with(|t| { - *t.borrow_mut() += duration; + t.replace_with(|now| now.saturating_add(duration)); }) } } diff --git a/rs/moq-tokio/src/server.rs b/rs/moq-tokio/src/server.rs index 1834a1b800d..55ad9711d67 100644 --- a/rs/moq-tokio/src/server.rs +++ b/rs/moq-tokio/src/server.rs @@ -2759,7 +2759,7 @@ mod tests { // `serve` binds the socket; wait for it. Keep the last error, since a bind // failure is the only clue to why it never showed up. const MAX_DELAY: std::time::Duration = std::time::Duration::from_millis(100); - let deadline = kio::clock::now() + std::time::Duration::from_secs(5); + let deadline = kio::clock::now().saturating_add(std::time::Duration::from_secs(5)); let mut delay = std::time::Duration::from_millis(1); while let Err(err) = tokio::net::UnixStream::connect(&path).await { assert!(kio::clock::now() < deadline, "unix listener never bound: {err}"); diff --git a/rs/moq-tokio/tests/integration/receive_ts.rs b/rs/moq-tokio/tests/integration/receive_ts.rs index 5826d8d37e9..080314de454 100644 --- a/rs/moq-tokio/tests/integration/receive_ts.rs +++ b/rs/moq-tokio/tests/integration/receive_ts.rs @@ -53,7 +53,7 @@ struct Recorder { impl Controller for Recorder { fn on_sent(&mut self, sent: congestion::Sent) -> congestion::Packet { let start = self.next.map_or(sent.now, |next| next.max(sent.now)); - self.next = Some(start + Duration::from_secs_f64(f64::from(sent.bytes) / self.rate as f64)); + self.next = Some(start.saturating_add(Duration::from_secs_f64(f64::from(sent.bytes) / self.rate as f64))); Default::default() } @@ -167,11 +167,14 @@ async fn run(preset: &str) -> Run { .expect("handshake"); let mut send = conn.open_uni(Default::default()).await.unwrap(); let chunk = Bytes::from(vec![0; 64 * 1024]); - let _ = kio::clock::timeout_at(Instant::now() + duration.saturating_sub(start.elapsed()), async { - loop { - send.write_all(chunk.clone()).await.unwrap(); - } - }) + let _ = kio::clock::timeout_at( + Instant::now().saturating_add(duration.saturating_sub(start.elapsed())), + async { + loop { + send.write_all(chunk.clone()).await.unwrap(); + } + }, + ) .await; conn.close(0u32.into(), "done"); shaper.verify().expect("the shaper acted"); diff --git a/rs/moq-transcode/src/catalog.rs b/rs/moq-transcode/src/catalog.rs index 259969b2ca5..a184d15f374 100644 --- a/rs/moq-transcode/src/catalog.rs +++ b/rs/moq-transcode/src/catalog.rs @@ -1039,7 +1039,11 @@ mod tests { let ago = Duration::from_secs(60); let _ = moq_net::time::Instant::now(); tokio::time::advance(ago).await; - let clock = moq_mux::Clock::at(moq_net::time::Instant::now() - ago, kio::clock::wall() - ago).unwrap(); + let clock = moq_mux::Clock::at( + moq_net::time::Instant::now().saturating_sub(ago), + kio::clock::wall() - ago, + ) + .unwrap(); let mut input = moq_net::broadcast::Info::default().produce(); let source = moq_mux::catalog::Producer::new( &mut input, diff --git a/rs/moq-uring/benches/timers.rs b/rs/moq-uring/benches/timers.rs index 5fbe5705cab..eeacf279c39 100644 --- a/rs/moq-uring/benches/timers.rs +++ b/rs/moq-uring/benches/timers.rs @@ -29,14 +29,17 @@ fn benchmark(c: &mut criterion::Criterion) { let _others: Vec<_> = (0..armed) .map(|i| { let mut timer = handle.timer(); - timer.set(Some(now + Duration::from_secs(60) * i / armed)); + timer.set(Some(now.saturating_add(Duration::from_secs(60) * i / armed))); timer }) .collect(); // Two instants a re-arm alternates between, so every set moves it. let mut timer = handle.timer(); - let at = [now + Duration::from_secs(30), now + Duration::from_secs(31)]; + let at = [ + now.saturating_add(Duration::from_secs(30)), + now.saturating_add(Duration::from_secs(31)), + ]; let mut flip = 0; group.bench_function(BenchmarkId::new("rearm", armed), |b| { b.iter(|| { diff --git a/rs/moq-uring/src/clock.rs b/rs/moq-uring/src/clock.rs index f4fc4b652b5..9054ffd362d 100644 --- a/rs/moq-uring/src/clock.rs +++ b/rs/moq-uring/src/clock.rs @@ -121,7 +121,7 @@ impl Host { } fn now(&self) -> Instant { - self.instant + monotonic().saturating_sub(self.monotonic) + self.instant.saturating_add(monotonic().saturating_sub(self.monotonic)) } /// The monotonic reading at `at`; one before calibration maps to calibration. @@ -155,7 +155,7 @@ mod tests { let now = host.now(); let after = kio::clock::now(); assert!( - before <= now + slack && now <= after + slack, + before <= now.saturating_add(slack) && now <= after.saturating_add(slack), "{before:?} <= {now:?} <= {after:?}" ); } @@ -181,10 +181,10 @@ mod tests { fn deadlines_map_onto_the_monotonic_clock() { let host = Host { monotonic: Duration::from_secs(100), - instant: Instant::ZERO + Duration::from_secs(1 << 32), + instant: Instant::ZERO.saturating_add(Duration::from_secs(1 << 32)), }; assert_eq!( - host.monotonic(host.instant + Duration::from_millis(1500)), + host.monotonic(host.instant.saturating_add(Duration::from_millis(1500))), Duration::from_millis(101_500) ); assert_eq!( diff --git a/rs/moq-uring/src/worker.rs b/rs/moq-uring/src/worker.rs index 1c388a2ebaa..cd9ee6355c1 100644 --- a/rs/moq-uring/src/worker.rs +++ b/rs/moq-uring/src/worker.rs @@ -628,7 +628,7 @@ impl Drop for Worker { self.shared.stopped.set(true); // One deadline bounds cancellation staging and draining together. It is // on the host's time, so it passes even on a manual clock. - let deadline = self.shared.clock.host_now() + TEARDOWN_TIMEOUT; + let deadline = self.shared.clock.host_now().saturating_add(TEARDOWN_TIMEOUT); // The kernel may still write into provided buffers and read send // headers owned by the ops slab. Queue cancels behind every staged // receive and the futex, so partial submissions cannot strand an @@ -911,7 +911,7 @@ mod tests { /// Past on the host clock but ahead of the worker's last turn, so a park /// for it times out at once. fn due(worker: &Worker) -> Instant { - worker.shared.deadlines.now() + Duration::from_nanos(1) + worker.shared.deadlines.now().saturating_add(Duration::from_nanos(1)) } fn worker_result(result: Result, required: bool) -> Option { @@ -1072,7 +1072,7 @@ mod tests { worker.shared.ring.borrow_mut().submit().expect("arm receive"); peer.send_to(b"deferred", sock.local_addr().expect("addr")) .expect("send"); - let deadline = worker.shared.clock.now() + Duration::from_secs(5); + let deadline = worker.shared.clock.now().saturating_add(Duration::from_secs(5)); while !worker.shared.ring.borrow_mut().submission().taskrun() { assert!( worker.shared.clock.now() < deadline, @@ -1240,7 +1240,7 @@ mod tests { let handle = worker.handle(); let at = worker .block_on(async move { - let at = kio::clock::now() + Duration::from_millis(50); + let at = kio::clock::now().saturating_add(Duration::from_millis(50)); let mut timer = handle.timer(); timer.set(Some(at)); timer.wait().await; @@ -1276,7 +1276,7 @@ mod tests { }) .unwrap(); advancer.join().unwrap(); - assert_eq!(woke, start + Duration::from_secs(5)); + assert_eq!(woke, start.saturating_add(Duration::from_secs(5))); } /// Ambient timers and reads on the worker resolve to its clock. @@ -1294,7 +1294,7 @@ mod tests { (now, timed_out.is_err()) }) .unwrap(); - assert_eq!(now, kio::clock::Instant::ZERO + Duration::from_secs(1)); + assert_eq!(now, kio::clock::Instant::ZERO.saturating_add(Duration::from_secs(1))); assert!(timed_out); } @@ -1350,20 +1350,20 @@ mod tests { assert!(timer.poll(&kio::Waiter::noop()).is_ready()); // Re-arming to the future pends again; disarming stays pending. - timer.set(Some(now + Duration::from_secs(60))); + timer.set(Some(now.saturating_add(Duration::from_secs(60)))); assert!(timer.poll(&kio::Waiter::noop()).is_pending()); timer.set(None); assert!(timer.poll(&kio::Waiter::noop()).is_pending()); // And a re-arm fires through the worker once its clock gets there. - timer.set(Some(now + Duration::from_millis(20))); + timer.set(Some(now.saturating_add(Duration::from_millis(20)))); clock.advance(Duration::from_millis(20)); worker .block_on(async move { kio::wait(|waiter| timer.poll(waiter)).await; }) .unwrap(); - assert_eq!(handle.now(), now + Duration::from_millis(20)); + assert_eq!(handle.now(), now.saturating_add(Duration::from_millis(20))); } #[test] @@ -1406,7 +1406,7 @@ mod tests { flags: 0, }; let before = kio::clock::Instant::ZERO; - let deadline = before + Duration::from_millis(1); + let deadline = before.saturating_add(Duration::from_millis(1)); let mut now = [before, deadline].into_iter(); worker.cqes = vec![cqe(first), cqe(second)]; @@ -1546,7 +1546,7 @@ mod tests { // Drive the worker until every completion, backlog included, has been // reaped and released its buffer back to the pool. - let deadline = handle.now() + Duration::from_secs(10); + let deadline = handle.now().saturating_add(Duration::from_secs(10)); loop { overflowed = overflowed || saw_overflow(&worker); let h = handle.clone(); @@ -1786,7 +1786,7 @@ mod tests { // Two trains of two: the first is rejected and resent, the second // never tries GSO. for _ in 0..2 { - let deadline = handle.now() + Duration::from_secs(5); + let deadline = handle.now().saturating_add(Duration::from_secs(5)); let mut received = 0; let Poll::Ready(Ok(mut tx)) = sock.poll_acquire(&kio::Waiter::noop()) else { panic!("the socket failed after a rejected train"); @@ -1840,7 +1840,7 @@ mod tests { // Drive the worker until the loopback delivers, parking on a timer each // turn so the park and timer counters see traffic too. - let deadline = handle.now() + Duration::from_secs(5); + let deadline = handle.now().saturating_add(Duration::from_secs(5)); let mut received = 0; while received == 0 && handle.now() < deadline { let handle = handle.clone(); @@ -1918,7 +1918,7 @@ mod tests { // Hold the received packet: its buffer is the pool, so the re-arm has // nowhere to receive into. - let deadline = handle.now() + Duration::from_secs(5); + let deadline = handle.now().saturating_add(Duration::from_secs(5)); let mut held = None; while held.is_none() && handle.now() < deadline { let handle = handle.clone(); @@ -1963,11 +1963,11 @@ mod tests { let mut timer = handle.timer(); let now = handle.now(); - timer.set(Some(now + Duration::from_secs(60))); + timer.set(Some(now.saturating_add(Duration::from_secs(60)))); assert_eq!(metrics.snapshot().timers_active(), 1); // A re-arm is a cancel plus an arm, which is exactly the churn signal. - timer.set(Some(now + Duration::from_secs(61))); + timer.set(Some(now.saturating_add(Duration::from_secs(61)))); let snap = metrics.snapshot(); assert_eq!((snap.timers_armed, snap.timers_cancelled, snap.timers_fired), (2, 1, 0)); assert_eq!(snap.timers_active(), 1); @@ -1980,7 +1980,7 @@ mod tests { assert_eq!(snap.timers_active(), 0); // A dropped armed timer is a cancel, and the queue empties again. - timer.set(Some(now + Duration::from_secs(60))); + timer.set(Some(now.saturating_add(Duration::from_secs(60)))); assert_eq!(metrics.snapshot().timers_active(), 1); drop(timer); assert_eq!(metrics.snapshot().timers_active(), 0); @@ -2007,7 +2007,7 @@ mod tests { worker.block_on(async {}).unwrap(); drop(dropped); - rearmed.set(Some(handle.now() + Duration::from_secs(1))); + rearmed.set(Some(handle.now().saturating_add(Duration::from_secs(1)))); let snap = metrics.snapshot(); assert_eq!((snap.timers_armed, snap.timers_cancelled, snap.timers_fired), (3, 0, 2)); assert_eq!(snap.timers_active(), 1); diff --git a/rs/moq-video/src/capture/channel.rs b/rs/moq-video/src/capture/channel.rs index f387d0390bd..2c07ca6c5d7 100644 --- a/rs/moq-video/src/capture/channel.rs +++ b/rs/moq-video/src/capture/channel.rs @@ -310,7 +310,7 @@ mod tests { #[tokio::test] async fn timestamp_is_captured_before_queued_delay() { let chan = FrameChannel::new(); - let captured = chan.epoch + std::time::Duration::from_millis(12); + let captured = chan.epoch.saturating_add(std::time::Duration::from_millis(12)); chan.push_at(frame(1), captured); assert_eq!(chan.recv().await.unwrap().unwrap().timestamp.as_micros(), 12_000); } @@ -333,7 +333,7 @@ mod tests { async fn native_timestamps_reanchor_when_the_device_clock_restarts() { let chan = FrameChannel::new(); let us = |micros| Timestamp::from_micros(micros).unwrap(); - let at = |millis| chan.epoch + std::time::Duration::from_millis(millis); + let at = |millis| chan.epoch.saturating_add(std::time::Duration::from_millis(millis)); chan.push_native_at(frame(1), us(0), at(0)); // Real time passes with the device clock, so the mapping stays at arrival. @@ -356,7 +356,7 @@ mod tests { async fn native_timestamps_reanchor_above_a_fast_drain() { let chan = FrameChannel::new(); let us = |micros| Timestamp::from_micros(micros).unwrap(); - let at = |millis| chan.epoch + std::time::Duration::from_millis(millis); + let at = |millis| chan.epoch.saturating_add(std::time::Duration::from_millis(millis)); chan.push_native_at(frame(1), us(0), at(0)); chan.push_native_at(frame(2), us(40_000), at(1)); @@ -383,7 +383,7 @@ mod tests { async fn a_device_clock_at_the_end_of_the_timeline_fails_the_stream() { let chan = FrameChannel::new(); let us = |micros| Timestamp::from_micros(micros).unwrap(); - let at = |millis| chan.epoch + std::time::Duration::from_millis(millis); + let at = |millis| chan.epoch.saturating_add(std::time::Duration::from_millis(millis)); chan.push_native_at(frame(1), us(0), at(0)); chan.push_native_at(frame(2), us((1 << 61) - 1), at(1)); @@ -399,7 +399,7 @@ mod tests { async fn a_stalled_device_clock_falls_back_to_arrival() { let chan = FrameChannel::new(); let constant = Timestamp::from_micros(0).unwrap(); - let at = |millis| chan.epoch + std::time::Duration::from_millis(millis); + let at = |millis| chan.epoch.saturating_add(std::time::Duration::from_millis(millis)); chan.push_native_at(frame(1), constant, at(0)); let first = chan.recv().await.unwrap().unwrap().timestamp; diff --git a/rs/moq-video/src/capture/settle.rs b/rs/moq-video/src/capture/settle.rs index 9a526bb999f..d098809ced2 100644 --- a/rs/moq-video/src/capture/settle.rs +++ b/rs/moq-video/src/capture/settle.rs @@ -49,7 +49,7 @@ impl Settle { /// Wake an event-driven source even if its final resized frame was static. #[cfg(any(target_os = "windows", test))] pub fn deadline(&self) -> Option { - self.pending.as_ref().map(|(_, since)| *since + HOLD) + self.pending.as_ref().map(|(_, since)| since.saturating_add(HOLD)) } /// Feed the geometry observed at `now`. @@ -87,10 +87,16 @@ mod tests { let mut settle = Settle::new((800, 600)); assert_eq!(settle.deadline(), None); assert_eq!(settle.observe(&(900, 600), now), Settled::Waiting); - assert_eq!(settle.deadline(), Some(now + HOLD)); - assert_eq!(settle.observe(&(902, 600), now + HOLD / 2), Settled::Waiting); - assert_eq!(settle.deadline(), Some(now + HOLD + HOLD / 2)); - assert_eq!(settle.observe(&(800, 600), now + HOLD), Settled::Open); + assert_eq!(settle.deadline(), Some(now.saturating_add(HOLD))); + assert_eq!( + settle.observe(&(902, 600), now.saturating_add(HOLD / 2)), + Settled::Waiting + ); + assert_eq!( + settle.deadline(), + Some(now.saturating_add(HOLD).saturating_add(HOLD / 2)) + ); + assert_eq!(settle.observe(&(800, 600), now.saturating_add(HOLD)), Settled::Open); assert_eq!(settle.deadline(), None); } @@ -99,7 +105,10 @@ mod tests { let start = Instant::now(); let mut settle = Settle::new((1920u32, 1080u32)); assert_eq!(settle.observe(&(1920, 1080), start), Settled::Open); - assert_eq!(settle.observe(&(1920, 1080), start + HOLD * 4), Settled::Open); + assert_eq!( + settle.observe(&(1920, 1080), start.saturating_add(HOLD * 4)), + Settled::Open + ); } #[test] @@ -107,8 +116,14 @@ mod tests { let start = Instant::now(); let mut settle = Settle::new((1920u32, 1080u32)); assert_eq!(settle.observe(&(1280, 720), start), Settled::Waiting); - assert_eq!(settle.observe(&(1280, 720), start + HOLD / 2), Settled::Waiting); - assert_eq!(settle.observe(&(1280, 720), start + HOLD), Settled::Changed); + assert_eq!( + settle.observe(&(1280, 720), start.saturating_add(HOLD / 2)), + Settled::Waiting + ); + assert_eq!( + settle.observe(&(1280, 720), start.saturating_add(HOLD)), + Settled::Changed + ); } #[test] @@ -119,13 +134,13 @@ mod tests { // settles while the pointer is moving. let mut now = start; for step in 1..=(2 * HOLD.as_millis() / 10) as u32 { - now = start + Duration::from_millis(u64::from(step) * 10); + now = start.saturating_add(Duration::from_millis(u64::from(step) * 10)); assert_eq!(settle.observe(&(1920 - step * 2, 1080), now), Settled::Waiting); } // The pointer stops: the last size settles one window later. let last = (1920 - (2 * HOLD.as_millis() / 10) as u32 * 2, 1080); - assert_eq!(settle.observe(&last, now + HOLD / 2), Settled::Waiting); - assert_eq!(settle.observe(&last, now + HOLD), Settled::Changed); + assert_eq!(settle.observe(&last, now.saturating_add(HOLD / 2)), Settled::Waiting); + assert_eq!(settle.observe(&last, now.saturating_add(HOLD)), Settled::Changed); } #[test] @@ -133,9 +148,18 @@ mod tests { let start = Instant::now(); let mut settle = Settle::new((1920u32, 1080u32)); assert_eq!(settle.observe(&(1280, 720), start), Settled::Waiting); - assert_eq!(settle.observe(&(1920, 1080), start + HOLD / 2), Settled::Open); + assert_eq!( + settle.observe(&(1920, 1080), start.saturating_add(HOLD / 2)), + Settled::Open + ); // The earlier change is forgotten, so the wait starts over. - assert_eq!(settle.observe(&(1280, 720), start + HOLD), Settled::Waiting); - assert_eq!(settle.observe(&(1280, 720), start + HOLD * 2), Settled::Changed); + assert_eq!( + settle.observe(&(1280, 720), start.saturating_add(HOLD)), + Settled::Waiting + ); + assert_eq!( + settle.observe(&(1280, 720), start.saturating_add(HOLD * 2)), + Settled::Changed + ); } } diff --git a/rs/moq-video/src/capture/wgc.rs b/rs/moq-video/src/capture/wgc.rs index b6f54a51fc7..d92695cf1c2 100644 --- a/rs/moq-video/src/capture/wgc.rs +++ b/rs/moq-video/src/capture/wgc.rs @@ -97,7 +97,7 @@ struct Startup { impl Startup { fn new(now: Instant) -> Self { Self { - deadline: Some(now + Duration::from_secs(5)), + deadline: Some(now.saturating_add(Duration::from_secs(5))), } } @@ -160,7 +160,7 @@ impl Delivery { let elapsed = u64::try_from(now.saturating_duration_since(started).as_micros()).map_err(|_| moq_net::TimeOverflow)?; let timestamp = timestamp.checked_add(Timestamp::from_micros(elapsed)?)?; - self.next = now + self.interval; + self.next = now.saturating_add(self.interval); Ok(Some((frame, timestamp))) } } @@ -196,9 +196,9 @@ mod tests { fn startup_without_frame_events_expires() { let now = Instant::now(); let startup = Startup::new(now); - let deadline = now + Duration::from_secs(5); + let deadline = now.saturating_add(Duration::from_secs(5)); assert_eq!(startup.deadline, Some(deadline)); - assert!(startup.check(deadline - Duration::from_nanos(1)).is_ok()); + assert!(startup.check(deadline.saturating_sub(Duration::from_nanos(1))).is_ok()); // Model WGC silence after minimizing between StartCapture and its first // frame. No callback is required to reach the failure boundary. assert!(matches!(startup.check(deadline), Err(Error::SourceUnavailable(_)))); @@ -215,8 +215,11 @@ mod tests { assert_eq!(signal.wait(startup.deadline), Event::Borderless); assert_eq!(signal.wait(startup.deadline), Event::Frame); // Empty pools and invalid content sizes do not deliver a frame. - assert_eq!(startup.deadline, Some(now + Duration::from_secs(5))); - assert_eq!(startup.check(now + Duration::from_secs(second)).is_err(), second == 5); + assert_eq!(startup.deadline, Some(now.saturating_add(Duration::from_secs(5)))); + assert_eq!( + startup.check(now.saturating_add(Duration::from_secs(second))).is_err(), + second == 5 + ); } } @@ -224,15 +227,15 @@ mod tests { fn first_delivery_removes_the_startup_deadline() { let now = Instant::now(); let mut startup = Startup::new(now); - assert!(startup.check(now + Duration::from_secs(1)).is_ok()); + assert!(startup.check(now.saturating_add(Duration::from_secs(1))).is_ok()); startup.delivered(); assert_eq!(startup.deadline, None); - assert!(startup.check(now + Duration::from_secs(10)).is_ok()); + assert!(startup.check(now.saturating_add(Duration::from_secs(10))).is_ok()); } #[test] fn terminal_events_take_precedence_over_expired_startup() { - let startup = Startup::new(Instant::now() - Duration::from_secs(5)); + let startup = Startup::new(Instant::now().saturating_sub(Duration::from_secs(5))); let signal = Signal::default(); assert_eq!(signal.wait(startup.deadline), Event::Deadline); signal.notify(Event::Frame); @@ -252,7 +255,7 @@ mod tests { delivery.replace(pixels.clone(), Timestamp::from_micros(1_000_000).unwrap(), now); for step in 0..10 { - let now = now + interval * step; + let now = now.saturating_add(interval * step); assert_eq!(delivery.deadline(), Some(now)); let (frame, timestamp) = delivery.next(now).unwrap().unwrap(); assert!( @@ -260,7 +263,7 @@ mod tests { "reuse the owned output without a conversion" ); assert_eq!(timestamp.as_micros(), 1_000_000 + u128::from(step) * 20_000); - assert!(delivery.next(now + interval / 2).unwrap().is_none()); + assert!(delivery.next(now.saturating_add(interval / 2)).unwrap().is_none()); } } @@ -271,24 +274,24 @@ mod tests { let mut delivery = Delivery::new(interval, now); delivery.replace(1, Timestamp::from_micros(1_000_000).unwrap(), now); delivery.next(now).unwrap().unwrap(); - let repeated = now + interval * 5; + let repeated = now.saturating_add(interval * 5); assert_eq!(delivery.next(repeated).unwrap().unwrap().1.as_micros(), 1_100_000); // This changed frame was acquired before the most recent repeated delivery. delivery.replace(2, Timestamp::from_micros(1_090_000).unwrap(), repeated); - let (frame, timestamp) = delivery.next(repeated + interval).unwrap().unwrap(); + let (frame, timestamp) = delivery.next(repeated.saturating_add(interval)).unwrap().unwrap(); assert_eq!(*frame, 2); assert_eq!(timestamp.as_micros(), 1_120_000); // Minimized, empty, or resizing sources stop repeating until new content arrives. delivery.clear(); assert_eq!(delivery.deadline(), None); - let resumed = now + Duration::from_secs(1); + let resumed = now.saturating_add(Duration::from_secs(1)); assert!(delivery.next(resumed).unwrap().is_none()); delivery.replace(3, Timestamp::from_micros(1_990_000).unwrap(), resumed); let (frame, timestamp) = delivery.next(resumed).unwrap().unwrap(); assert_eq!(*frame, 3); assert_eq!(timestamp.as_micros(), 2_000_000); - assert_eq!(delivery.deadline(), Some(resumed + interval)); + assert_eq!(delivery.deadline(), Some(resumed.saturating_add(interval))); } #[tokio::test] @@ -325,7 +328,7 @@ mod tests { // Only one captured picture arrives; more than three intervals of paced // output must still reach a real video subscriber with advancing timestamps. for step in 0..10 { - let now = now + interval * step; + let now = now.saturating_add(interval * step); assert_eq!(delivery.deadline(), Some(now)); let (surface, timestamp) = delivery.next(now).unwrap().unwrap(); let frame = crate::Frame::new(crate::Surface::I420(surface.clone()), timestamp); diff --git a/rs/moq-video/src/capture/x11.rs b/rs/moq-video/src/capture/x11.rs index 2d15b334976..92247cf4eff 100644 --- a/rs/moq-video/src/capture/x11.rs +++ b/rs/moq-video/src/capture/x11.rs @@ -336,7 +336,7 @@ impl Capture { )] std::thread::sleep(self.next - now); } - self.next = Instant::now() + self.interval; + self.next = Instant::now().saturating_add(self.interval); // The encoder's geometry is fixed at open, so a settled change ends the // stream and the caller reopens against the new size. match self.settled()? { @@ -1111,7 +1111,7 @@ mod tests { observed.event(&configure(7, 800, 600), 7); assert_eq!(settle.observe(&observed, now), Settled::Waiting); assert_eq!( - settle.observe(&observed, now + super::super::settle::HOLD), + settle.observe(&observed, now.saturating_add(super::super::settle::HOLD)), Settled::Changed ); observed.event(&configure(7, 640, 480), 7); diff --git a/rs/moq-video/src/decode/backend/v4l2.rs b/rs/moq-video/src/decode/backend/v4l2.rs index 6060443c147..926b72d6ef6 100644 --- a/rs/moq-video/src/decode/backend/v4l2.rs +++ b/rs/moq-video/src/decode/backend/v4l2.rs @@ -192,7 +192,7 @@ impl V4l2 { /// Hand one access unit to the driver, waiting for a free buffer. fn submit(&mut self, access_unit: &Bytes, timestamp: Timestamp) -> Result<(), Error> { - let deadline = Instant::now() + BUFFER_TIMEOUT; + let deadline = Instant::now().saturating_add(BUFFER_TIMEOUT); let index = loop { self.reclaim_coded()?; if let Some(index) = self.coded.take_free() { @@ -397,7 +397,7 @@ impl V4l2 { /// Change". fn drain_tail(&mut self) -> Result<(), Error> { let start = self.ready.len(); - let deadline = Instant::now() + DRAIN_TIMEOUT; + let deadline = Instant::now().saturating_add(DRAIN_TIMEOUT); loop { if self.drain()? { return Ok(()); @@ -425,7 +425,7 @@ impl V4l2 { fn drain_sequence(&mut self) -> Result { let mut ended = false; let mut changed = false; - let mut deadline = Instant::now() + DRAIN_TIMEOUT; + let mut deadline = Instant::now().saturating_add(DRAIN_TIMEOUT); loop { let before = self.ready.len(); let reclaimed = self.reclaim_coded()?; @@ -443,7 +443,7 @@ impl V4l2 { } if reclaimed > 0 || self.ready.len() > before { - deadline = Instant::now() + DRAIN_TIMEOUT; + deadline = Instant::now().saturating_add(DRAIN_TIMEOUT); } else if Instant::now() >= deadline { return Err(Error::codec(anyhow::anyhow!( "V4L2 decoder did not finish its drain within {DRAIN_TIMEOUT:?}, holding {} access unit(s)", @@ -560,7 +560,7 @@ impl Backend for V4l2 { // geometry. if let Phase::Sizing { since } = &mut self.phase { let since = *since.get_or_insert_with(Instant::now); - let deadline = Instant::now() + SOURCE_CHANGE_TIMEOUT; + let deadline = Instant::now().saturating_add(SOURCE_CHANGE_TIMEOUT); while !self.device.take_source_change() { if Instant::now() >= deadline { let waited = since.elapsed(); diff --git a/rs/moq-video/src/decode/select.rs b/rs/moq-video/src/decode/select.rs index b8767605544..824a88b7d47 100644 --- a/rs/moq-video/src/decode/select.rs +++ b/rs/moq-video/src/decode/select.rs @@ -254,7 +254,9 @@ impl Selector { // Only a held min-delay picture has a deadline. let deadline = match self.source { - Lane::Max => self.lanes[Lane::Min as usize].held().map(|(_, at)| at + interval), + Lane::Max => self.lanes[Lane::Min as usize] + .held() + .map(|(_, at)| at.saturating_add(interval)), Lane::Min => None, }; Next::Wait(deadline) @@ -465,9 +467,9 @@ mod tests { let Next::Wait(Some(deadline)) = selector.next(start) else { panic!("a held picture must carry a deadline"); }; - assert_eq!(deadline, start + FRAME); + assert_eq!(deadline, start.saturating_add(FRAME)); assert!(matches!( - selector.next(deadline - Duration::from_millis(1)), + selector.next(deadline.saturating_sub(Duration::from_millis(1))), Next::Wait(_) )); assert_eq!(drain(&mut selector, deadline), [33]); @@ -670,7 +672,7 @@ mod tests { selector.push(Lane::Max, picture(max[b]), now); b += 1; } - now += Duration::from_millis(7); + now = now.saturating_add(Duration::from_millis(7)); out.extend(drain(&mut selector, now)); } selector.finish(Lane::Min); diff --git a/rs/moq-video/src/encode/backend/v4l2.rs b/rs/moq-video/src/encode/backend/v4l2.rs index 805686cfe19..2e62f55afaf 100644 --- a/rs/moq-video/src/encode/backend/v4l2.rs +++ b/rs/moq-video/src/encode/backend/v4l2.rs @@ -338,7 +338,7 @@ impl V4l2 { /// Take a raw buffer, waiting for the driver to release one if it holds them /// all. fn free_buffer(&mut self) -> Result { - let deadline = Instant::now() + BUFFER_TIMEOUT; + let deadline = Instant::now().saturating_add(BUFFER_TIMEOUT); loop { self.reclaim()?; if let Some(index) = self.raw.take_free() { @@ -472,7 +472,7 @@ impl V4l2 { } fn resume_after_last(&mut self) -> Result<(), Error> { - let mut deadline = Instant::now() + FLUSH_TIMEOUT; + let mut deadline = Instant::now().saturating_add(FLUSH_TIMEOUT); loop { let before = self.ready.len(); if self.drain()? { @@ -481,7 +481,7 @@ impl V4l2 { // Progress earns more time, so a slow encoder finishes a long tail while // a stalled one still gives up after `FLUSH_TIMEOUT` of silence. if self.ready.len() > before { - deadline = Instant::now() + FLUSH_TIMEOUT; + deadline = Instant::now().saturating_add(FLUSH_TIMEOUT); } else if Instant::now() >= deadline { return Err(Error::codec(anyhow::anyhow!( "V4L2 encoder did not finish its drain within {FLUSH_TIMEOUT:?}, holding {} frame(s)", @@ -515,7 +515,7 @@ impl V4l2 { /// Only a drain where the encoder holds nothing it has not been asked for, /// which is what an empty [`Pending`] says here. fn wait_out(&mut self) -> Result<(), Error> { - let mut deadline = Instant::now() + FLUSH_TIMEOUT; + let mut deadline = Instant::now().saturating_add(FLUSH_TIMEOUT); loop { let before = self.ready.len(); self.drain()?; @@ -523,7 +523,7 @@ impl V4l2 { return Ok(()); } if self.ready.len() > before { - deadline = Instant::now() + FLUSH_TIMEOUT; + deadline = Instant::now().saturating_add(FLUSH_TIMEOUT); } else if Instant::now() >= deadline { return Err(Error::codec(anyhow::anyhow!( "V4L2 encoder held {} frame(s) for {FLUSH_TIMEOUT:?} without encoding them", diff --git a/rs/moq-video/src/frame.rs b/rs/moq-video/src/frame.rs index 3e8305e037f..2587e904fe6 100644 --- a/rs/moq-video/src/frame.rs +++ b/rs/moq-video/src/frame.rs @@ -180,7 +180,7 @@ pub(crate) fn wait_dma_buf_readable(fd: BorrowedFd<'_>) -> std::io::Result<()> { events: libc::POLLIN, revents: 0, }; - let deadline = kio::clock::now() + DMA_BUF_FENCE_TIMEOUT; + let deadline = kio::clock::now().saturating_add(DMA_BUF_FENCE_TIMEOUT); loop { // A signal restarts the wait against the same deadline rather than // granting a fresh budget, so the total stall stays bounded. diff --git a/rs/moq-video/src/frame/cuda_test.rs b/rs/moq-video/src/frame/cuda_test.rs index 158869770f4..a0506bfe1bb 100644 --- a/rs/moq-video/src/frame/cuda_test.rs +++ b/rs/moq-video/src/frame/cuda_test.rs @@ -404,7 +404,7 @@ async fn vulkan_cuda_three_view_workload() { late = 0; started = kio::clock::now(); } - let deadline = kio::clock::now() + tick; + let deadline = kio::clock::now().saturating_add(tick); let timestamp = moq_net::Timestamp::from_micros(tick_index * 33_333).unwrap(); for (producer, slot, hd, small, signal) in &mut views { diff --git a/rs/moq-webrtc/src/egress.rs b/rs/moq-webrtc/src/egress.rs index 73ecd6fa1c4..80623400c0d 100644 --- a/rs/moq-webrtc/src/egress.rs +++ b/rs/moq-webrtc/src/egress.rs @@ -1338,15 +1338,24 @@ mod tests { assert_eq!(clock.wallclock(MediaTime::from_millis(1_000), t0), t0); assert_eq!( - clock.wallclock(MediaTime::from_millis(1_100), t0 + Duration::from_millis(100)), - t0 + Duration::from_millis(100) + clock.wallclock( + MediaTime::from_millis(1_100), + t0.saturating_add(Duration::from_millis(100)) + ), + t0.saturating_add(Duration::from_millis(100)) ); // Two tracks dequeue the same presentation time 50 ms apart. Their // sender-report wallclocks must still agree. - let audio = clock.wallclock(MediaTime::from_millis(1_200), t0 + Duration::from_millis(250)); - let video = clock.wallclock(MediaTime::from_millis(1_200), t0 + Duration::from_millis(300)); - assert_eq!(audio, t0 + Duration::from_millis(200)); + let audio = clock.wallclock( + MediaTime::from_millis(1_200), + t0.saturating_add(Duration::from_millis(250)), + ); + let video = clock.wallclock( + MediaTime::from_millis(1_200), + t0.saturating_add(Duration::from_millis(300)), + ); + assert_eq!(audio, t0.saturating_add(Duration::from_millis(200))); assert_eq!(video, audio); } @@ -1363,7 +1372,10 @@ mod tests { // Once the live edge is known, another track uses the same mapping even // when its frames dequeue later. assert_eq!( - clock.wallclock(MediaTime::from_millis(1_100), t0 + Duration::from_millis(50)), + clock.wallclock( + MediaTime::from_millis(1_100), + t0.saturating_add(Duration::from_millis(50)) + ), t0 ); } diff --git a/rs/moq-webrtc/src/ice/agent.rs b/rs/moq-webrtc/src/ice/agent.rs index 324c7e16674..9ffa5612a40 100644 --- a/rs/moq-webrtc/src/ice/agent.rs +++ b/rs/moq-webrtc/src/ice/agent.rs @@ -284,7 +284,9 @@ impl Agent { /// When [`ESTABLISH_TIMEOUT`] expires, or `None` while it is held, gathering, or over. fn establish(&self) -> Option { match (&self.phase, self.gathered) { - (Phase::Establishing { started }, Some(gathered)) => Some((*started).max(gathered) + ESTABLISH_TIMEOUT), + (Phase::Establishing { started }, Some(gathered)) => { + Some((*started).max(gathered).saturating_add(ESTABLISH_TIMEOUT)) + } _ => None, } } @@ -419,11 +421,10 @@ impl Agent { return false; } query.sends += 1; - query.deadline = now - + match query.sends { - STUN_SENDS => STUN_RTO * STUN_LAST_WAIT, - _ => query.rto, - }; + query.deadline = now.saturating_add(match query.sends { + STUN_SENDS => STUN_RTO * STUN_LAST_WAIT, + _ => query.rto, + }); query.rto *= 2; due.push((query.request.clone(), query.server)); true @@ -538,7 +539,7 @@ mod tests { agent.stun.clear(); assert!(matches!(agent.next().await, Ok(Event::Gathered))); let gathered = agent.gathered.unwrap(); - assert_eq!(agent.establish(), Some(gathered + ESTABLISH_TIMEOUT)); + assert_eq!(agent.establish(), Some(gathered.saturating_add(ESTABLISH_TIMEOUT))); } /// A peer that answers but never sends: DTLS gives up on its handshake before ICE diff --git a/rs/moq-webrtc/src/rate.rs b/rs/moq-webrtc/src/rate.rs index 7b6f397aecf..4693562b4bb 100644 --- a/rs/moq-webrtc/src/rate.rs +++ b/rs/moq-webrtc/src/rate.rs @@ -124,7 +124,9 @@ impl Meter { let tokens = self.tokens + rate * elapsed.as_secs_f64(); if tokens > burst { // The bucket filled partway through and discarded credit from then until now. - let since = (from + Duration::from_secs_f64((burst - self.tokens).max(0.0) / rate)).min(now); + let since = from + .saturating_add(Duration::from_secs_f64((burst - self.tokens).max(0.0) / rate)) + .min(now); match self.full.back_mut() { Some(full) if full.until == since && full.rate == rate => full.until = now, _ => self.full.push_back(Full { @@ -157,7 +159,7 @@ impl Meter { let start = since.max(at); let take = (rate * until.saturating_duration_since(start).as_secs_f64()).min(limit - refund); refund += take; - self.full[i].since = (start + Duration::from_secs_f64(take / rate)).min(until); + self.full[i].since = start.saturating_add(Duration::from_secs_f64(take / rate)).min(until); if since < at { // The credit discarded before `at` stays for frames that arrived earlier. self.full.insert(i, Full { since, until: at, rate }); @@ -199,7 +201,12 @@ mod tests { let mut meter = Meter::new(Some(cap()), t0); // 500 bytes every half second is exactly the cap, for a minute. for i in 0..120 { - assert!(meter.charge_at(500, t0 + Duration::from_millis(500 * i)).is_ok(), "{i}"); + assert!( + meter + .charge_at(500, t0.saturating_add(Duration::from_millis(500 * i))) + .is_ok(), + "{i}" + ); } } @@ -210,8 +217,11 @@ mod tests { // The whole burst at once is allowed. assert!(meter.charge_at(1000, t0).is_ok()); // A second later, one more second of the cap is allowed, but no more. - assert!(meter.charge_at(1000, t0 + Duration::from_secs(1)).is_ok()); - assert_eq!(meter.charge_at(1, t0 + Duration::from_secs(1)), Err(cap())); + assert!(meter.charge_at(1000, t0.saturating_add(Duration::from_secs(1))).is_ok()); + assert_eq!( + meter.charge_at(1, t0.saturating_add(Duration::from_secs(1))), + Err(cap()) + ); } #[test] @@ -219,7 +229,11 @@ mod tests { let t0 = Instant::now(); let mut meter = Meter::new(Some(cap()), t0); // 10% over the cap: 550 bytes every half second spends 50 bytes of burst per tick. - let refused = (1..100).find(|i| meter.charge_at(550, t0 + Duration::from_millis(500 * i)).is_err()); + let refused = (1..100).find(|i| { + meter + .charge_at(550, t0.saturating_add(Duration::from_millis(500 * i))) + .is_err() + }); assert_eq!(refused, Some(11)); } @@ -227,7 +241,7 @@ mod tests { fn idle_time_banks_no_more_than_the_burst() { let t0 = Instant::now(); let mut meter = Meter::new(Some(cap()), t0); - let later = t0 + Duration::from_secs(3600); + let later = t0.saturating_add(Duration::from_secs(3600)); assert!(meter.charge_at(1000, later).is_ok()); assert!(meter.charge_at(1, later).is_err()); } @@ -235,7 +249,7 @@ mod tests { #[test] fn a_frame_charged_late_is_refunded_the_credit_discarded_since_it_arrived() { let t0 = Instant::now(); - let ms = |ms| t0 + Duration::from_millis(ms); + let ms = |ms| t0.saturating_add(Duration::from_millis(ms)); // A 1000-byte video frame arrives over 0..50 ms with 10-byte audio frames at 20 and // 40 ms, which str0m completes first. In arrival order the bucket ends at 30 bytes. @@ -264,11 +278,18 @@ mod tests { // under the cap, though four times the burst. let cap = Cap::new(Rate::from_kbps(2_000)).with_burst(Duration::from_millis(100)); let mut meter = Meter::new(Some(cap), t0); - assert!(meter.charge(100_000, t0, t0 + Duration::from_millis(500)).is_ok()); + assert!( + meter + .charge(100_000, t0, t0.saturating_add(Duration::from_millis(500))) + .is_ok() + ); // The same keyframe over 100 ms is 8 Mbps. let mut meter = Meter::new(Some(cap), t0); - assert_eq!(meter.charge(100_000, t0, t0 + Duration::from_millis(100)), Err(cap)); + assert_eq!( + meter.charge(100_000, t0, t0.saturating_add(Duration::from_millis(100))), + Err(cap) + ); } #[test] @@ -278,15 +299,24 @@ mod tests { // 20-byte audio frames at 20..180 ms. Arrival order accepts all of them. let mut meter = Meter::new(Some(cap().with_burst(Duration::from_millis(100))), t0); for i in 1..10 { - assert!(meter.charge_at(20, t0 + Duration::from_millis(20 * i)).is_ok(), "{i}"); + assert!( + meter + .charge_at(20, t0.saturating_add(Duration::from_millis(20 * i))) + .is_ok(), + "{i}" + ); } - assert!(meter.charge(100, t0, t0 + Duration::from_millis(180)).is_ok()); + assert!( + meter + .charge(100, t0, t0.saturating_add(Duration::from_millis(180))) + .is_ok() + ); } #[test] fn a_refund_leaves_newer_credit_to_frames_that_arrived_later() { let t0 = Instant::now(); - let ms = |ms| t0 + Duration::from_millis(ms); + let ms = |ms| t0.saturating_add(Duration::from_millis(ms)); // Frame A takes 499 bytes at 0 ms and 1 at 1000 ms. Frame B takes 1000 bytes at // 500 ms and 499 at 1001 ms. In packet order the bucket ends at 1 byte. let mut meter = Meter::new(Some(cap()), t0); @@ -302,10 +332,14 @@ mod tests { let t0 = Instant::now(); // Idle for a minute, then a frame at 60 s and one charged late from 10 ms before it. let mut meter = Meter::new(Some(cap()), t0); - assert!(meter.charge_at(10, t0 + Duration::from_secs(60)).is_ok()); + assert!(meter.charge_at(10, t0.saturating_add(Duration::from_secs(60))).is_ok()); assert!( meter - .charge(1000, t0 + Duration::from_millis(59_990), t0 + Duration::from_secs(60)) + .charge( + 1000, + t0.saturating_add(Duration::from_millis(59_990)), + t0.saturating_add(Duration::from_secs(60)) + ) .is_ok() ); // Only the 10 bytes discarded over those 10 ms came back. @@ -317,8 +351,12 @@ mod tests { let t0 = Instant::now(); let mut meter = Meter::new(Some(cap()), t0); // 100 bytes discarded over 0..100 ms, then two frames from 0 ms charged late. - assert!(meter.charge_at(0, t0 + Duration::from_millis(100)).is_ok()); - let done = t0 + Duration::from_millis(100); + assert!( + meter + .charge_at(0, t0.saturating_add(Duration::from_millis(100))) + .is_ok() + ); + let done = t0.saturating_add(Duration::from_millis(100)); assert!(meter.charge(600, t0, done).is_ok()); assert!(meter.charge(500, t0, done).is_ok()); assert!((meter.tokens - 0.0).abs() < 1e-6, "{}", meter.tokens); @@ -347,8 +385,8 @@ mod tests { let t0 = Instant::now(); let mut meter = Meter::new(None, t0); assert!(meter.charge_at(1_000_000, t0).is_ok()); - meter.set(Some(cap()), t0 + Duration::from_secs(1)); - assert!(meter.charge_at(1000, t0 + Duration::from_secs(1)).is_ok()); - assert!(meter.charge_at(1, t0 + Duration::from_secs(1)).is_err()); + meter.set(Some(cap()), t0.saturating_add(Duration::from_secs(1))); + assert!(meter.charge_at(1000, t0.saturating_add(Duration::from_secs(1))).is_ok()); + assert!(meter.charge_at(1, t0.saturating_add(Duration::from_secs(1))).is_err()); } } diff --git a/rs/moq-webrtc/src/server/whep.rs b/rs/moq-webrtc/src/server/whep.rs index 44a48eac017..0d7b49de17c 100644 --- a/rs/moq-webrtc/src/server/whep.rs +++ b/rs/moq-webrtc/src/server/whep.rs @@ -224,7 +224,7 @@ fn is_sdp(headers: &HeaderMap) -> bool { /// one, would park the handler forever. No route by the deadline is /// [`moq_net::Error::Unroutable`], so the WHEP client sees a 404 and retries (typical). async fn resolve(subscriber: &moq_net::origin::Consumer, path: moq_net::Path) -> Result { - let deadline = kio::clock::now() + CATALOG_TIMEOUT; + let deadline = kio::clock::now().saturating_add(CATALOG_TIMEOUT); let mut following = subscriber.follow(path, None)?; let broadcast = kio::clock::timeout_at(deadline, following.available()) .await diff --git a/rs/moq-webrtc/src/session.rs b/rs/moq-webrtc/src/session.rs index 3834e1d7570..acbcf3b341f 100644 --- a/rs/moq-webrtc/src/session.rs +++ b/rs/moq-webrtc/src/session.rs @@ -390,7 +390,7 @@ impl Session { let Some(rate) = &mut self.rate else { return; }; - rate.next_remb = Instant::now() + REMB_INTERVAL; + rate.next_remb = Instant::now().saturating_add(REMB_INTERVAL); // A REMB ceiling holds until the next one replaces it, so a lifted cap keeps sending // the largest REMB can carry rather than going quiet and leaving the old ceiling. let bitrate = match rate.meter.cap() { @@ -740,7 +740,10 @@ mod tests { let video = Mid::from("1"); let t0 = Instant::now(); assert_eq!(clock.normalize(audio, t0, 0), 0); - assert_eq!(clock.normalize(video, t0 + Duration::from_millis(50), 0), 50_000); + assert_eq!( + clock.normalize(video, t0.saturating_add(Duration::from_millis(50)), 0), + 50_000 + ); // NTP time zero (1900), which a sender without a wall clock may report, and past 2554. let ntp_zero = UNIX_EPOCH - Duration::from_secs(2_208_988_800); @@ -753,11 +756,11 @@ mod tests { // Both tracks stay on arrival time. assert_eq!( - clock.normalize(audio, t0 + Duration::from_secs(1), 1_000_000), + clock.normalize(audio, t0.saturating_add(Duration::from_secs(1)), 1_000_000), 1_000_000 ); assert_eq!( - clock.normalize(video, t0 + Duration::from_millis(1_050), 1_000_000), + clock.normalize(video, t0.saturating_add(Duration::from_millis(1_050)), 1_000_000), 1_050_000 ); assert!(SenderAnchor::new(sender_info(1, UNIX_EPOCH, 0)).is_ok()); @@ -824,7 +827,7 @@ mod tests { // Raw RTP base is a large random value; the first frame must map to 0. assert_eq!(clock.normalize(mid, t0, 5_000_000_000), 0); // A later frame advances by the RTP delta, not by arrival jitter. - let arrival = t0 + Duration::from_millis(17); // jittered arrival, ignored after anchor + let arrival = t0.saturating_add(Duration::from_millis(17)); // jittered arrival, ignored after anchor assert_eq!(clock.normalize(mid, arrival, 5_000_020_000), 20_000); } @@ -838,11 +841,15 @@ mod tests { assert_eq!(clock.normalize(audio, t0, 1_000_000_000), 0); // Video's first frame arrives 5 ms later with an unrelated RTP base; it // must land at +5 ms on the shared timeline, not at video's raw base. - let video_arrival = t0 + Duration::from_millis(5); + let video_arrival = t0.saturating_add(Duration::from_millis(5)); assert_eq!(clock.normalize(video, video_arrival, 8_000_000_000), 5_000); // And then track its own RTP delta. assert_eq!( - clock.normalize(video, video_arrival + Duration::from_millis(33), 8_000_033_000), + clock.normalize( + video, + video_arrival.saturating_add(Duration::from_millis(33)), + 8_000_033_000 + ), 38_000 ); } @@ -858,10 +865,14 @@ mod tests { // Video's first frame actually arrived 5 ms *before* the epoch. Its lead // pulls the start below zero (clamped to 0), and a frame 33 ms into video // lands 28 ms onto the shared timeline (33 ms - the 5 ms head start). - let video_arrival = t0 - Duration::from_millis(5); + let video_arrival = t0.saturating_sub(Duration::from_millis(5)); assert_eq!(clock.normalize(video, video_arrival, 8_000_000), 0); assert_eq!( - clock.normalize(video, video_arrival + Duration::from_millis(33), 8_033_000), + clock.normalize( + video, + video_arrival.saturating_add(Duration::from_millis(33)), + 8_033_000 + ), 28_000 ); } @@ -877,15 +888,19 @@ mod tests { assert_eq!(clock.normalize(audio, t0, audio_base), 0); assert_eq!( - clock.normalize(video, t0 + Duration::from_millis(50), video_base), + clock.normalize(video, t0.saturating_add(Duration::from_millis(50)), video_base), 50_000 ); assert_eq!( - clock.normalize(audio, t0 + Duration::from_secs(1), audio_base + 1_000_000), + clock.normalize(audio, t0.saturating_add(Duration::from_secs(1)), audio_base + 1_000_000), 1_000_000 ); assert_eq!( - clock.normalize(video, t0 + Duration::from_millis(1_050), video_base + 1_000_000,), + clock.normalize( + video, + t0.saturating_add(Duration::from_millis(1_050)), + video_base + 1_000_000, + ), 1_050_000 ); @@ -895,8 +910,16 @@ mod tests { clock.observe(audio, sender_info(1, report_time, audio_base + 1_000_000)); clock.observe(video, sender_info(2, report_time, video_base + 1_000_000)); - let audio_time = clock.normalize(audio, t0 + Duration::from_millis(1_020), audio_base + 1_020_000); - let video_time = clock.normalize(video, t0 + Duration::from_millis(1_070), video_base + 1_020_000); + let audio_time = clock.normalize( + audio, + t0.saturating_add(Duration::from_millis(1_020)), + audio_base + 1_020_000, + ); + let video_time = clock.normalize( + video, + t0.saturating_add(Duration::from_millis(1_070)), + video_base + 1_020_000, + ); assert_eq!(audio_time, video_time); assert_eq!(audio_time, 1_070_000); } diff --git a/rs/qmux/src/driver.rs b/rs/qmux/src/driver.rs index 365483962ee..9c50dea0d82 100644 --- a/rs/qmux/src/driver.rs +++ b/rs/qmux/src/driver.rs @@ -237,7 +237,7 @@ impl Run { let deadline = self .phase .deadline() - .unwrap_or_else(|| kio::clock::now() + CLOSE_TIMEOUT); + .unwrap_or_else(|| kio::clock::now().saturating_add(CLOSE_TIMEOUT)); self.phase = Phase::Closing(deadline); } Step::Failed(err) => self.finish(Err(err)), @@ -307,7 +307,7 @@ impl Run { let _ = state.conn.poll_closed(waiter); state.check_lost(); if state.conn.is_closed() && matches!(self.phase, Phase::Open) { - self.phase = Phase::Flushing(now + CLOSE_TIMEOUT); + self.phase = Phase::Flushing(now.saturating_add(CLOSE_TIMEOUT)); } let drained = state.conn.is_drained(); let deadline = state.conn.poll_timeout(); diff --git a/rs/qmux/src/socket.rs b/rs/qmux/src/socket.rs index 5a8477398dc..998299e59c7 100644 --- a/rs/qmux/src/socket.rs +++ b/rs/qmux/src/socket.rs @@ -360,7 +360,7 @@ mod rate_filter_tests { use kio::clock::Instant; fn at(start: Instant, ms: u64) -> Instant { - start + Duration::from_millis(ms) + start.saturating_add(Duration::from_millis(ms)) } #[test] diff --git a/rs/qmux/src/transport/websocket.rs b/rs/qmux/src/transport/websocket.rs index 4ee4d8e3821..2852fb2717d 100644 --- a/rs/qmux/src/transport/websocket.rs +++ b/rs/qmux/src/transport/websocket.rs @@ -103,7 +103,10 @@ impl Transport for WsTransport { if let Some(keep_alive) = self.keep_alive { // The first tick is one interval out, so we don't ping on connect. A long pause // sends one Ping, not a catch-up burst. - let mut ping = kio::clock::interval_at(kio::clock::now() + keep_alive.interval, keep_alive.interval); + let mut ping = kio::clock::interval_at( + kio::clock::now().saturating_add(keep_alive.interval), + keep_alive.interval, + ); ping.set_missed_tick_behavior(MissedTickBehavior::Delay); self.ping = Some(ping); self.deadline = Some((kio::clock::sleep(keep_alive.timeout), keep_alive.timeout)); @@ -118,7 +121,7 @@ impl Transport for WsTransport { while let Poll::Ready(message) = Pin::new(&mut self.ws).poll_next(&mut cx) { // Any message, data or control, proves the peer is alive. if let Some((sleep, timeout)) = &mut self.deadline { - sleep.reset(kio::clock::now() + *timeout); + sleep.reset(kio::clock::now().saturating_add(*timeout)); } let message = match message { Some(Ok(message)) => message,