diff --git a/Cargo.lock b/Cargo.lock index f46c261dac2..36db359206d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4769,6 +4769,9 @@ dependencies = [ "kio 0.6.2", "moq-clock", "moq-clock-macros", + "serde", + "serde_json", + "serde_with", "tokio", "wasm-bindgen", "wasm-bindgen-test", @@ -5080,7 +5083,6 @@ dependencies = [ "tracing", "tracing-subscriber", "wasm-bindgen-test", - "web-time", ] [[package]] @@ -5392,6 +5394,7 @@ dependencies = [ "bytes", "hang", "kio 0.6.2", + "moq-clock", "moq-mux", "moq-net", "moq-tokio", diff --git a/quest/m1/time/README.md b/quest/m1/time/README.md index 1c6c48cab41..596cd881541 100644 --- a/quest/m1/time/README.md +++ b/quest/m1/time/README.md @@ -1,4 +1,4 @@ -# Controlled time +# [XS] Controlled time ## Goal @@ -103,9 +103,9 @@ needed by the in-tree QUIC stack and clustering regressions. Unrelated test/priv cleanup and the global lint ratchet belong to [the follow-up sweep](/quest/m2/time-test-sweep.md). -## Required - -- [Public wall times on moq_clock::Wall](/quest/m1/time/wall.md) - public `SystemTime`s become `moq_clock::Wall`, and the ratchets ban the type +Remaining: every child has landed, with public wall times on `moq_clock::Wall` +in [#6298](https://github.com/moq-dev/moq/pull/6298). Move the decisions the +m2 quests still cite into them, then retire this epic. ## Related diff --git a/quest/m1/time/wall.md b/quest/m1/time/wall.md deleted file mode 100644 index ce641e0055f..00000000000 --- a/quest/m1/time/wall.md +++ /dev/null @@ -1,49 +0,0 @@ -# [M] Public wall times on moq_clock::Wall - -## Goal - -Every public wall time in the Rust crates is a `moq_clock::Wall` instead of a -`std::time::SystemTime`, and the per-crate clippy ratchets ban the -`SystemTime` type wherever it no longer crosses a third-party API. - -## Plan - -The remaining public `SystemTime`s, as of -[#6135](https://github.com/moq-dev/moq/pull/6135): - -- hang: `catalog::Clock::wall_clock` and `echo::Arrival::wall`, plus the - snapshot serializer. -- moq-mux: `Clock::at`, `Clock::wall_clock`, `catalog::Timebase::place`, and - the catalog producer's wall argument; this ripples into moq-gst's sink, - moq-audio's capture, and moq-hls. -- moq-hls: the manifest and playlist `program_date_time`, - `availability_start`, `publish`, and `Renditions::anchor`. -- moq-quic: `TimeSource::now` and the token log's issue times. -- moq-relay: the session's `started`. -- moq-tokio: the certificate `expiry`. -- moq-auth: `Claims::{expires, issued, not_before}` with their `with_*` - setters, and `Grant::expires`. -- moq-cli and moq-bench: private wall times, which can move freely. - -`Wall` covers 1970 to 2554, so a catalog wall past that range is an error, as -it already is on Windows. A third-party API on `SystemTime`, such as -str0m's sender reports in moq-rtc, converts at its boundary with -`From` and `TryFrom`. - -Expiries saturate instead (decided 2026-10-22, maintainer, from an external -API audit of [#6298](https://github.com/moq-dev/moq/pull/6298)): a -certificate `not_after` or an auth expiry past 2554 becomes the latest -representable `Wall`, and one before 1970 becomes `Wall::UNIX_EPOCH`, so -`tls::PeerIdentity::expiry` and the auth claims stay infallible and rcgen's -default year-4096 certificates keep working. No representable `now` can compare differently against the -saturated value, so this loses nothing; refusing them would turn a -representation limit into a validity rule for valid identities. Presentation -walls (catalogs, timelines, HLS) still refuse, since their value is shown or -used for arithmetic, not only compared. - -Public API: breaking in hang, moq-mux, moq-hls, moq-quic, moq-relay, moq-auth, and -moq-tokio; the Impact bullet says how to migrate each. Wire: none. - -## Related - -- [Time test sweep](/quest/m2/time-test-sweep.md) - the workspace-wide lint follows this diff --git a/rs/hang/Cargo.toml b/rs/hang/Cargo.toml index f04c3e25327..3c59a1a0ddb 100644 --- a/rs/hang/Cargo.toml +++ b/rs/hang/Cargo.toml @@ -16,6 +16,7 @@ categories = ["multimedia", "network-programming", "web-programming"] bytes = { workspace = true } hex = { workspace = true } kio = { workspace = true } +moq-clock = { workspace = true } moq-json = { workspace = true } moq-net = { workspace = true } regex = "1" @@ -31,7 +32,6 @@ features = ["from", "display", "debug"] [dev-dependencies] anyhow = { workspace = true } -moq-clock = { workspace = true } moq-mux = { path = "../moq-mux" } moq-tokio = { path = "../moq-tokio", default-features = false, features = ["quic", "aws-lc-rs", "websocket"] } tokio = { workspace = true, features = ["macros", "fs"] } diff --git a/rs/hang/clippy.toml b/rs/hang/clippy.toml index f3f8720ac3f..d5a7b48f913 100644 --- a/rs/hang/clippy.toml +++ b/rs/hang/clippy.toml @@ -1,5 +1,4 @@ # Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. -# `SystemTime` stays an allowed type until its wall times move to `moq_clock::Wall`. disallowed-methods = [ { path = "std::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, { path = "std::time::Instant::elapsed", reason = "read the ambient clock: moq_clock::Instant::elapsed()" }, @@ -16,6 +15,7 @@ disallowed-methods = [ ] disallowed-types = [ + { path = "std::time::SystemTime", reason = "use moq_clock::Wall" }, { path = "std::time::Instant", reason = "use moq_clock::Instant" }, { path = "tokio::time::Instant", reason = "use moq_clock::Instant" }, { path = "tokio::time::Sleep", reason = "use moq_clock::Sleep" }, diff --git a/rs/hang/src/catalog/clock.rs b/rs/hang/src/catalog/clock.rs index e13dc91880d..94cf396a3a8 100644 --- a/rs/hang/src/catalog/clock.rs +++ b/rs/hang/src/catalog/clock.rs @@ -64,8 +64,8 @@ impl Clock { /// The wall-clock time of `pts` under this fixed mapping. /// /// Exact down to the nanosecond; an instant finer than that (a 90 kHz tick) is floored. - /// Refuses a result past the JSON-safe range or one the system clock cannot represent. - pub fn wall_clock(&self, pts: moq_net::Timestamp) -> Result { + /// Refuses a result past the JSON-safe range or the wall clock's 1970-2554 range. + pub fn wall_clock(&self, pts: moq_net::Timestamp) -> Result { let overflow = || crate::Error::TimestampOverflow(moq_net::TimeOverflow); let wall_scale = self.wall.scale().as_u64() as u128; let pts_scale = pts.scale().as_u64() as u128; @@ -87,8 +87,8 @@ impl Clock { let secs = u64::try_from(num / den).map_err(|_| overflow())?; let nanos = (num % den).checked_mul(1_000_000_000).ok_or_else(overflow)? / den; let since_moq_epoch = std::time::Duration::new(secs, nanos as u32); - // Windows' `SystemTime` cannot reach the furthest wall a catalog carries. - std::time::UNIX_EPOCH + // A catalog can name a wall beyond the clock's nanosecond range. + moq_clock::Wall::UNIX_EPOCH .checked_add(std::time::Duration::from_millis(MOQ_EPOCH_UNIX_MILLIS)) .and_then(|moq_epoch| moq_epoch.checked_add(since_moq_epoch)) .ok_or_else(overflow) @@ -171,28 +171,27 @@ mod test { )); } - /// Regression: the furthest wall a catalog carries overflowed `SystemTime` on - /// Windows and panicked. Unix reaches it, so only Windows sees the error. + /// A JSON-safe catalog wall can still exceed Wall's nanosecond range. #[test] - fn wall_clock_past_the_system_clock_is_an_error() { + fn wall_clock_past_the_wall_range_is_an_error() { let wall = moq_net::Timestamp::new(MAX_SAFE_INTEGER, moq_net::Timescale::SECOND).unwrap(); let clock = Clock::new(wall).unwrap(); - match clock.wall_clock(moq_net::Timestamp::ZERO) { - Ok(at) => assert!(at > std::time::UNIX_EPOCH + std::time::Duration::from_secs(MAX_SAFE_INTEGER)), - Err(err) => assert!(matches!(err, crate::Error::TimestampOverflow(_)), "{err}"), - } + assert!(matches!( + clock.wall_clock(moq_net::Timestamp::ZERO), + Err(crate::Error::TimestampOverflow(_)) + )); } #[test] fn wall_clock_converts_across_timescales() { let clock = Clock::new(moq_net::Timestamp::from_micros(1_000_000).unwrap()).unwrap(); - let epoch = std::time::UNIX_EPOCH + std::time::Duration::from_millis(MOQ_EPOCH_UNIX_MILLIS + 1_000); + let epoch = moq_clock::Wall::UNIX_EPOCH + std::time::Duration::from_millis(MOQ_EPOCH_UNIX_MILLIS + 1_000); assert_eq!( clock.wall_clock(moq_net::Timestamp::from_millis(0).unwrap()).unwrap(), epoch ); - let second = std::time::UNIX_EPOCH + std::time::Duration::from_millis(MOQ_EPOCH_UNIX_MILLIS + 2_000); + let second = moq_clock::Wall::UNIX_EPOCH + std::time::Duration::from_millis(MOQ_EPOCH_UNIX_MILLIS + 2_000); assert_eq!( clock .wall_clock(moq_net::Timestamp::from_millis(1000).unwrap()) @@ -216,7 +215,7 @@ mod test { /// Regression: the result was floored to the millisecond, dropping the sub-millisecond part. #[test] fn wall_clock_keeps_sub_millisecond_precision() { - let moq_epoch = std::time::UNIX_EPOCH + std::time::Duration::from_millis(MOQ_EPOCH_UNIX_MILLIS); + let moq_epoch = moq_clock::Wall::UNIX_EPOCH + std::time::Duration::from_millis(MOQ_EPOCH_UNIX_MILLIS); let micros = |v| moq_net::Timestamp::from_micros(v).unwrap(); let nanos = std::time::Duration::from_nanos; diff --git a/rs/hang/src/catalog/root.rs b/rs/hang/src/catalog/root.rs index 6a37747685f..78798d0078d 100644 --- a/rs/hang/src/catalog/root.rs +++ b/rs/hang/src/catalog/root.rs @@ -1095,7 +1095,7 @@ mod test { assert_eq!(archive.timescale, 1000); // Archive PTS 2000 (ms) lands 2s after the wall epoch, whatever the track timescale. - let expected = std::time::UNIX_EPOCH + let expected = moq_clock::Wall::UNIX_EPOCH + std::time::Duration::from_millis(crate::catalog::MOQ_EPOCH_UNIX_MILLIS + 1_751_846_402_000); assert_eq!( clock diff --git a/rs/hang/src/echo.rs b/rs/hang/src/echo.rs index 6c7b13cc613..afd380bb0fe 100644 --- a/rs/hang/src/echo.rs +++ b/rs/hang/src/echo.rs @@ -77,12 +77,12 @@ pub struct Arrival { pub timestamp: moq_net::Timestamp, /// The arrival wall time, encoded in milliseconds since the MoQ epoch. #[serde_as(as = "crate::snapshot::Wall")] - pub wall: std::time::SystemTime, + pub wall: moq_clock::Wall, } impl Arrival { /// Pair a received media timestamp with the wall time it arrived. - pub fn new(timestamp: moq_net::Timestamp, wall: std::time::SystemTime) -> Self { + pub fn new(timestamp: moq_net::Timestamp, wall: moq_clock::Wall) -> Self { Self { timestamp, wall } } } diff --git a/rs/hang/src/snapshot.rs b/rs/hang/src/snapshot.rs index bf3e2b1430c..a2806d88c18 100644 --- a/rs/hang/src/snapshot.rs +++ b/rs/hang/src/snapshot.rs @@ -50,17 +50,19 @@ impl<'de> DeserializeAs<'de, moq_net::Timestamp> for Millis { } pub(crate) struct Wall; -fn epoch() -> std::time::SystemTime { - std::time::UNIX_EPOCH + Duration::from_millis(crate::catalog::MOQ_EPOCH_UNIX_MILLIS) +fn epoch() -> moq_clock::Wall { + moq_clock::Wall::UNIX_EPOCH + Duration::from_millis(crate::catalog::MOQ_EPOCH_UNIX_MILLIS) } -impl SerializeAs for Wall { - fn serialize_as(value: &std::time::SystemTime, serializer: S) -> Result { - let duration = value.duration_since(epoch()).map_err(serde::ser::Error::custom)?; +impl SerializeAs for Wall { + fn serialize_as(value: &moq_clock::Wall, serializer: S) -> Result { + let duration = value + .checked_duration_since(epoch()) + .ok_or_else(|| serde::ser::Error::custom("snapshot wall is before the MoQ epoch"))?; Millis::serialize_as(&duration, serializer) } } -impl<'de> DeserializeAs<'de, std::time::SystemTime> for Wall { - fn deserialize_as>(deserializer: D) -> Result { +impl<'de> DeserializeAs<'de, moq_clock::Wall> for Wall { + fn deserialize_as>(deserializer: D) -> Result { epoch() .checked_add(Millis::deserialize_as(deserializer)?) .ok_or_else(|| serde::de::Error::custom("snapshot wall clock overflow")) @@ -82,6 +84,27 @@ mod tests { assert_eq!(serde_json::to_value(decoded).unwrap(), value); } + #[test] + fn wall_range_and_epoch_are_checked() { + #[serde_with::serde_as] + #[derive(Debug, Serialize, Deserialize)] + struct Value { + #[serde_as(as = "Wall")] + wall: moq_clock::Wall, + } + let last_millis = (u64::MAX / 1_000_000) - crate::catalog::MOQ_EPOCH_UNIX_MILLIS; + let last = format!(r#"{{"wall":{last_millis}}}"#); + let value: Value = serde_json::from_str(&last).unwrap(); + assert_eq!(serde_json::to_string(&value).unwrap(), last); + assert!(serde_json::from_str::(&format!(r#"{{"wall":{}}}"#, last_millis + 1)).is_err()); + assert!( + serde_json::to_string(&Value { + wall: epoch() - Duration::from_nanos(1) + }) + .is_err() + ); + } + #[test] fn shared_snapshots_roundtrip() { roundtrip::(include_str!("../fixtures/stats-snapshot.json")); @@ -188,7 +211,7 @@ mod tests { let arrival = report.renditions["hd"].arrival.as_ref().unwrap(); assert_eq!(arrival.timestamp, moq_net::Timestamp::from_millis(30_000).unwrap()); assert_eq!( - arrival.wall.duration_since(epoch()).unwrap(), + arrival.wall.checked_duration_since(epoch()).unwrap(), Duration::from_millis(175_184_640_000) ); assert_eq!(report.renditions["hd"].stalled, Duration::from_millis(120)); diff --git a/rs/moq-audio/src/encode/capture.rs b/rs/moq-audio/src/encode/capture.rs index 36c20d022e2..1f9c477d617 100644 --- a/rs/moq-audio/src/encode/capture.rs +++ b/rs/moq-audio/src/encode/capture.rs @@ -1214,11 +1214,7 @@ fn frame(samples: &[f32], timestamp_us: u64) -> Result { } #[cfg(test)] -#[expect( - clippy::disallowed_methods, - clippy::disallowed_types, - reason = "tests read the host clock directly" -)] +#[expect(clippy::disallowed_methods, reason = "tests read the host clock directly")] mod tests { use std::collections::VecDeque; use std::future::Future; @@ -2118,7 +2114,8 @@ mod tests { /// the broadcast clock's own correlation, so the published timestamp is exactly that /// instant however late the read happens. mod clock { - use std::time::{Duration, SystemTime}; + use moq_clock::Wall; + use std::time::Duration; use super::*; @@ -2139,7 +2136,7 @@ mod tests { impl Fixture { /// Run a publication over `opens` on a broadcast whose clock began `behind` ago, at `wall`. - fn start(behind: Duration, wall: SystemTime, opens: impl IntoIterator) -> Self { + fn start(behind: Duration, wall: Wall, opens: impl IntoIterator) -> Self { let epoch = Instant::now() .checked_sub(behind) .expect("a monotonic clock that far back"); @@ -2232,7 +2229,7 @@ mod tests { #[tokio::test] async fn a_late_first_buffer_publishes_its_capture() { let (samples, input) = stream(None); - let mut fixture = Fixture::start(Duration::from_secs(5), SystemTime::now(), [Open::Stream(input)]); + let mut fixture = Fixture::start(Duration::from_secs(5), moq_clock::wall(), [Open::Stream(input)]); let mut track = fixture.subscribe().await; let published = fixture.deliver(&samples, &mut track, &[]).await; @@ -2245,7 +2242,7 @@ mod tests { #[tokio::test] async fn a_queued_buffer_publishes_its_capture_instant() { let (samples, input) = stream(None); - let mut fixture = Fixture::start(Duration::from_secs(5), SystemTime::now(), [Open::Stream(input)]); + let mut fixture = Fixture::start(Duration::from_secs(5), moq_clock::wall(), [Open::Stream(input)]); let mut track = fixture.subscribe().await; let captured = Instant::now() - Duration::from_millis(40); @@ -2263,7 +2260,7 @@ mod tests { #[tokio::test] async fn a_buffer_before_the_clock_began_clamps_to_zero() { let (samples, input) = stream(None); - let mut fixture = Fixture::start(Duration::ZERO, SystemTime::now(), [Open::Stream(input)]); + let mut fixture = Fixture::start(Duration::ZERO, moq_clock::wall(), [Open::Stream(input)]); let mut track = fixture.subscribe().await; samples @@ -2286,7 +2283,7 @@ mod tests { #[tokio::test] async fn a_buffer_captured_after_now_clamps_to_the_read() { let (samples, input) = stream(None); - let mut fixture = Fixture::start(Duration::from_secs(1), SystemTime::now(), [Open::Stream(input)]); + let mut fixture = Fixture::start(Duration::from_secs(1), moq_clock::wall(), [Open::Stream(input)]); let mut track = fixture.subscribe().await; let pushed = fixture.at(Instant::now()); @@ -2311,7 +2308,7 @@ mod tests { #[tokio::test] async fn a_buffer_without_a_capture_instant_publishes_its_read() { let (samples, input) = stream(None); - let mut fixture = Fixture::start(Duration::from_secs(1), SystemTime::now(), [Open::Stream(input)]); + let mut fixture = Fixture::start(Duration::from_secs(1), moq_clock::wall(), [Open::Stream(input)]); let mut track = fixture.subscribe().await; let pushed = fixture.at(Instant::now()); @@ -2332,7 +2329,7 @@ mod tests { #[tokio::test] async fn a_gap_reanchors_to_the_next_capture_instant() { let (samples, input) = stream(None); - let mut fixture = Fixture::start(Duration::from_secs(1), SystemTime::now(), [Open::Stream(input)]); + let mut fixture = Fixture::start(Duration::from_secs(1), moq_clock::wall(), [Open::Stream(input)]); let mut track = fixture.subscribe().await; let second_at = Instant::now() - Duration::from_millis(20); @@ -2358,7 +2355,7 @@ mod tests { let (second, reopened) = stream(None); let mut fixture = Fixture::start( Duration::from_secs(1), - SystemTime::now(), + moq_clock::wall(), [Open::Stream(failing), Open::Stream(reopened)], ); let mut track = fixture.subscribe().await; @@ -2389,7 +2386,7 @@ mod tests { let (second, resumed) = stream(None); let mut fixture = Fixture::start( Duration::from_secs(1), - SystemTime::now(), + moq_clock::wall(), [Open::Stream(input), Open::Stream(resumed)], ); @@ -2415,8 +2412,8 @@ mod tests { #[tokio::test] async fn a_system_wall_adjustment_retimes_nothing() { // Whole seconds, so the advertised mapping holds it exactly. - let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap(); - let wall = SystemTime::UNIX_EPOCH + Duration::from_secs(now.as_secs() - 3600); + let now = moq_clock::wall().checked_duration_since(Wall::UNIX_EPOCH).unwrap(); + let wall = Wall::UNIX_EPOCH + Duration::from_secs(now.as_secs() - 3600); let (samples, input) = stream(None); let mut fixture = Fixture::start(Duration::from_secs(1), wall, [Open::Stream(input)]); let advertised = fixture.catalog.snapshot().clock; @@ -2442,7 +2439,7 @@ mod tests { let (second, resumed) = stream(None); let mut fixture = Fixture::start( Duration::from_secs(1), - SystemTime::now(), + moq_clock::wall(), [Open::Stream(input), Open::Stream(resumed)], ); let mut live = Vec::new(); diff --git a/rs/moq-auth/Cargo.toml b/rs/moq-auth/Cargo.toml index 990e6809915..79251954f24 100644 --- a/rs/moq-auth/Cargo.toml +++ b/rs/moq-auth/Cargo.toml @@ -24,7 +24,7 @@ axum = { workspace = true, optional = true } base64 = { workspace = true } jsonwebtoken = { workspace = true, features = ["aws_lc_rs"] } kio = { workspace = true } -moq-clock = { version = "0.11.0", path = "../moq-clock", default-features = false } +moq-clock = { version = "0.11.0", path = "../moq-clock", default-features = false, features = ["serde"] } moq-pattern = { workspace = true, features = ["serde"] } p256 = "0.14.0" p384 = "0.14.0" diff --git a/rs/moq-auth/clippy.toml b/rs/moq-auth/clippy.toml index 4f84c08c2d2..d5a7b48f913 100644 --- a/rs/moq-auth/clippy.toml +++ b/rs/moq-auth/clippy.toml @@ -15,6 +15,7 @@ disallowed-methods = [ ] disallowed-types = [ + { path = "std::time::SystemTime", reason = "use moq_clock::Wall" }, { path = "std::time::Instant", reason = "use moq_clock::Instant" }, { path = "tokio::time::Instant", reason = "use moq_clock::Instant" }, { path = "tokio::time::Sleep", reason = "use moq_clock::Sleep" }, diff --git a/rs/moq-auth/examples/asymmetric.rs b/rs/moq-auth/examples/asymmetric.rs index b92f4213d1b..dc08f9ed3ef 100644 --- a/rs/moq-auth/examples/asymmetric.rs +++ b/rs/moq-auth/examples/asymmetric.rs @@ -9,7 +9,7 @@ reason = "`Claims` takes `SystemTime`, so the example reads the host clock" )] -use std::time::{Duration, SystemTime}; +use std::time::Duration; fn main() -> anyhow::Result<()> { // Generate an ECDSA P-256 key pair. @@ -25,8 +25,8 @@ fn main() -> anyhow::Result<()> { .with_root("rooms/meeting-123") .with_publish(["alice/**".parse()?]) .with_subscribe(["**".parse()?]) - .with_expires(SystemTime::now() + Duration::from_secs(3600)) - .with_issued(SystemTime::now()); + .with_expires(moq_clock::wall() + Duration::from_secs(3600)) + .with_issued(moq_clock::wall()); let token = private_key.sign(&claims)?; println!("Signed token:\n{token}\n"); diff --git a/rs/moq-auth/examples/basic.rs b/rs/moq-auth/examples/basic.rs index 0af201d05dc..61981be89cc 100644 --- a/rs/moq-auth/examples/basic.rs +++ b/rs/moq-auth/examples/basic.rs @@ -5,7 +5,7 @@ reason = "`Claims` takes `SystemTime`, so the example reads the host clock" )] -use std::time::{Duration, SystemTime}; +use std::time::Duration; fn main() -> anyhow::Result<()> { // Generate an HMAC key with a random key ID. @@ -20,8 +20,8 @@ fn main() -> anyhow::Result<()> { .with_root("demo") .with_publish(["my-stream/**".parse()?]) // Can publish to demo/my-stream and below .with_subscribe(["**".parse()?]) // Can subscribe to anything under demo/ - .with_expires(SystemTime::now() + Duration::from_secs(3600)) - .with_issued(SystemTime::now()); + .with_expires(moq_clock::wall() + Duration::from_secs(3600)) + .with_issued(moq_clock::wall()); // Validate the claims (ensures at least one publish or subscribe path). claims.validate()?; diff --git a/rs/moq-auth/src/claims.rs b/rs/moq-auth/src/claims.rs index 2795be75e81..867c0fb191b 100644 --- a/rs/moq-auth/src/claims.rs +++ b/rs/moq-auth/src/claims.rs @@ -126,14 +126,14 @@ pub struct Claims { pub subscribe: Patterns, /// The expiration time of the token as a unix timestamp (`exp`). - pub expires: Option, + pub expires: Option, /// The issued time of the token as a unix timestamp (`iat`). - pub issued: Option, + pub issued: Option, /// The time before which the token is refused, as a unix timestamp (`nbf`). /// Enforced by [`Key::verify`](crate::Key::verify). - pub not_before: Option, + pub not_before: Option, } impl Claims { @@ -158,7 +158,7 @@ impl Claims { /// Expire the token at this time. Enforced by [`Key::verify`](crate::Key::verify). /// /// Accepts an `Option` so a caller can pass one through without unwrapping it. - pub fn with_expires(mut self, at: impl Into>) -> Self { + pub fn with_expires(mut self, at: impl Into>) -> Self { self.expires = at.into(); self } @@ -166,7 +166,7 @@ impl Claims { /// Record when the token was issued. Purely informational; nothing enforces it. /// /// Accepts an `Option` so a caller can pass one through without unwrapping it. - pub fn with_issued(mut self, at: impl Into>) -> Self { + pub fn with_issued(mut self, at: impl Into>) -> Self { self.issued = at.into(); self } @@ -237,11 +237,10 @@ impl Claims { } #[cfg(test)] -#[expect(clippy::disallowed_methods, reason = "tests read the host clock directly")] mod tests { use super::*; - use std::time::{Duration, SystemTime}; + use std::time::Duration; fn patterns(texts: &[&str]) -> Patterns { texts.iter().map(|text| text.parse().unwrap()).collect() @@ -252,8 +251,8 @@ mod tests { root: "test-path".to_string(), publish: patterns(&["test-pub/**"]), subscribe: patterns(&["test-sub/**"]), - expires: Some(SystemTime::now() + Duration::from_secs(3600)), - issued: Some(SystemTime::now()), + expires: Some(moq_clock::wall() + Duration::from_secs(3600)), + issued: Some(moq_clock::wall()), not_before: None, } } diff --git a/rs/moq-auth/src/client.rs b/rs/moq-auth/src/client.rs index 4ba217565d9..fd5c6310198 100644 --- a/rs/moq-auth/src/client.rs +++ b/rs/moq-auth/src/client.rs @@ -498,7 +498,6 @@ mod tests { use super::*; use moq_pattern::Patterns; use std::task::Poll; - use std::time::SystemTime; use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, Request as Received, ResponseTemplate}; @@ -620,7 +619,7 @@ mod tests { /// as zero and be refused; these tests run on a one-second cadence. fn grant(expires_in: Option, revalidate: Option) -> Grant { let mut grant = Grant::new(patterns(&["**"]), Patterns::new()); - grant.expires = expires_in.map(|d| SystemTime::now() + d); + grant.expires = expires_in.map(|d| moq_clock::wall() + d); grant.revalidate = revalidate; grant } @@ -1250,7 +1249,7 @@ mod tests { async fn an_expired_grant_is_refused() { tokio::time::pause(); let mut grant = Grant::new(patterns(&["**"]), Patterns::new()); - grant.expires = Some(SystemTime::now() - Duration::from_secs(1)); + grant.expires = Some(moq_clock::wall() - Duration::from_secs(1)); let script = Script::new(Log::default(), move |_| Some(Ok(grant.clone()))); assert!(matches!(script.connect().await, Err(Error::GrantExpired))); } @@ -1283,7 +1282,7 @@ mod tests { #[tokio::test] async fn an_outage_keeps_the_grant_until_expires() { tokio::time::pause(); - let expires = SystemTime::now() + Duration::from_secs(3); + let expires = moq_clock::wall() + Duration::from_secs(3); let log = Log::default(); let script = Script::new(log.clone(), move |request| { Some(match request.event { @@ -1298,10 +1297,10 @@ mod tests { // `expires` is wall-clock time, which the client maps onto Tokio's clock // somewhere inside `connect`, so bracket it: the bounds hold however long it takes. - let (wall, tick) = (SystemTime::now(), tokio::time::Instant::now()); + let (wall, tick) = (moq_clock::wall(), tokio::time::Instant::now()); let consumer = script.connect().await.unwrap(); - let earliest = tick + expires.duration_since(SystemTime::now()).unwrap(); - let latest = tokio::time::Instant::now() + expires.duration_since(wall).unwrap(); + let earliest = tick + expires.checked_duration_since(moq_clock::wall()).unwrap(); + let latest = tokio::time::Instant::now() + expires.checked_duration_since(wall).unwrap(); // A millisecond either side for Tokio's timer resolution. let tolerance = Duration::from_millis(1); diff --git a/rs/moq-auth/src/grant.rs b/rs/moq-auth/src/grant.rs index 4de070a26d3..ab9f39a10de 100644 --- a/rs/moq-auth/src/grant.rs +++ b/rs/moq-auth/src/grant.rs @@ -1,8 +1,9 @@ +use moq_clock::Wall; use moq_pattern::Patterns; use serde::{Deserialize, Serialize}; -use serde_with::{DurationSeconds, TimestampSeconds, serde_as}; +use serde_with::{DurationSeconds, serde_as}; use std::collections::BTreeMap; -use std::time::{Duration, SystemTime}; +use std::time::Duration; /// What a session may do, as the auth server answered. /// @@ -35,8 +36,8 @@ pub struct Grant { pub mounts: BTreeMap, /// When the session closes, as unix seconds. - #[serde_as(as = "Option>")] - pub expires: Option, + #[serde_as(as = "Option")] + pub expires: Option, /// How long until the relay asks again, in seconds. #[serde_as(as = "Option>")] @@ -77,8 +78,8 @@ impl Grant { // Read the instant first, so a pause between the two reads shortens the grant // instead of extending it. let start = moq_clock::now(); - let now = SystemTime::from(moq_clock::wall()); - let remaining = self.expires?.duration_since(now).unwrap_or_default(); + let now = moq_clock::wall(); + let remaining = self.expires?.checked_duration_since(now).unwrap_or_default(); start.checked_add(remaining) } @@ -101,10 +102,7 @@ impl Grant { if let Some(label) = &self.label { moq_pattern::Pattern::literal(label).map_err(crate::Error::InvalidLabel)?; } - if self - .expires - .is_some_and(|expires| expires <= SystemTime::from(moq_clock::wall())) - { + if self.expires.is_some_and(|expires| expires <= moq_clock::wall()) { return Err(crate::Error::GrantExpired); } Ok(()) @@ -126,7 +124,7 @@ mod tests { subscribe: patterns(&["**"]), root: Some("pid/room".into()), mounts: BTreeMap::new(), - expires: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(4_102_444_800)), + expires: Some(Wall::UNIX_EPOCH + Duration::from_secs(4_102_444_800)), revalidate: Some(Duration::from_secs(60)), tier: Some("websocket".into()), label: Some("project/key/123".into()), @@ -151,7 +149,7 @@ mod tests { subscribe: patterns(&["**"]), root: Some("pid/room".into()), mounts: BTreeMap::new(), - expires: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(4_102_444_800)), + expires: Some(Wall::UNIX_EPOCH + Duration::from_secs(4_102_444_800)), revalidate: Some(Duration::from_secs(60)), tier: Some("websocket".into()), label: Some("project/key/123".into()), @@ -191,7 +189,7 @@ mod tests { assert!(matches!(grant.validate(), Err(crate::Error::UnboundedRevalidate))); // Exact: no grace for an auth server whose clock runs behind. - let now = SystemTime::from(moq_clock::wall()); + let now = moq_clock::wall(); grant.expires = Some(now); assert!(matches!(grant.validate(), Err(crate::Error::GrantExpired))); @@ -232,7 +230,7 @@ mod tests { #[moq_clock::test] async fn deadline_is_the_exact_expiry() { let start = moq_clock::now(); - let now = SystemTime::from(moq_clock::wall()); + let now = moq_clock::wall(); let mut grant = Grant::new(patterns(&["**"]), Patterns::default()); assert_eq!(grant.deadline(), None); @@ -248,13 +246,19 @@ mod tests { ); } - /// Regression: the furthest `expires` the wire carries overflowed the instant - /// and panicked. Windows' `SystemTime` cannot represent it, so the grant does not - /// parse there. - #[cfg(unix)] #[moq_clock::test] - async fn deadline_past_the_clock_is_never() { - let grant: Grant = serde_json::from_str(r#"{"publish":["**"],"expires":9223372036854775807}"#).unwrap(); - assert_eq!(grant.deadline(), None); + async fn expiry_saturates_to_the_wall_range() { + let parse = |expires: i64| { + serde_json::from_value::(serde_json::json!({"publish":["**"],"expires":expires})).unwrap() + }; + let past = parse(-1); + assert_eq!(past.expires, Some(Wall::UNIX_EPOCH)); + assert!(matches!(past.validate(), Err(crate::Error::GrantExpired))); + + // The furthest expiry the wire carries must not overflow the instant. + let far = parse(i64::MAX); + assert_eq!(far.expires, Some(Wall::UNIX_EPOCH.saturating_add(Duration::MAX))); + far.validate().unwrap(); + far.deadline(); } } diff --git a/rs/moq-auth/src/key.rs b/rs/moq-auth/src/key.rs index afc8b3071e4..a119502629c 100644 --- a/rs/moq-auth/src/key.rs +++ b/rs/moq-auth/src/key.rs @@ -558,7 +558,7 @@ impl Key { /// [`Claims::authorize`]. pub fn verify(&self, token: &str) -> crate::Result { let claims = self.verify_claims(token)?; - validate_times(&claims, moq_clock::wall().into())?; + validate_times(&claims, moq_clock::wall())?; Ok(claims) } @@ -637,7 +637,7 @@ impl Key { } /// Refuse claims expired at `now` (`exp <= now`) or not yet valid (`nbf > now`), as `jose` does. -pub(crate) fn validate_times(claims: &Claims, now: std::time::SystemTime) -> crate::Result<()> { +pub(crate) fn validate_times(claims: &Claims, now: moq_clock::Wall) -> crate::Result<()> { if claims.expires.is_some_and(|exp| exp <= now) { return Err(crate::Error::TokenExpired); } @@ -701,14 +701,14 @@ where } #[cfg(test)] -#[expect(clippy::disallowed_methods, reason = "tests read the host clock directly")] mod tests { use super::*; fn patterns(texts: &[&str]) -> crate::Patterns { texts.iter().map(|text| text.parse().unwrap()).collect() } - use std::time::{Duration, SystemTime}; + use moq_clock::Wall; + use std::time::Duration; fn create_test_key() -> Key { let mut jwk = Jwk::new( @@ -726,8 +726,8 @@ mod tests { root: "test-path".to_string(), publish: patterns(&["test-pub/**"]), subscribe: patterns(&["test-sub/**"]), - expires: Some(SystemTime::now() + Duration::from_secs(3600)), - issued: Some(SystemTime::now()), + expires: Some(moq_clock::wall() + Duration::from_secs(3600)), + issued: Some(moq_clock::wall()), not_before: None, } } @@ -1043,8 +1043,8 @@ mod tests { #[test] fn test_key_verify_only_registered_claims() { let key = create_test_key(); - let now = SystemTime::now() - .duration_since(SystemTime::UNIX_EPOCH) + let now = moq_clock::wall() + .checked_duration_since(Wall::UNIX_EPOCH) .unwrap() .as_secs(); @@ -1081,8 +1081,8 @@ mod tests { fn test_key_verify_enforces_not_before() { let key = create_test_key(); let at = |offset: i64| { - let now = SystemTime::now() - .duration_since(SystemTime::UNIX_EPOCH) + let now = moq_clock::wall() + .checked_duration_since(Wall::UNIX_EPOCH) .unwrap() .as_secs() as i64; sign_raw( @@ -1097,10 +1097,10 @@ mod tests { /// `exp` is refused at the instant itself and `nbf` accepted at it, matching `jose`. #[test] fn validate_times_at_the_boundary() { - let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000); + let now = Wall::UNIX_EPOCH + Duration::from_secs(1_000); let second = Duration::from_secs(1); - let at = |expires: Option, not_before: Option| { + let at = |expires: Option, not_before: Option| { let mut claims = create_test_claims(); claims.expires = expires; claims.not_before = not_before; @@ -1123,7 +1123,7 @@ mod tests { fn test_key_verify_expired_token() { let key = create_test_key(); let mut claims = create_test_claims(); - claims.expires = Some(SystemTime::now() - Duration::from_secs(3600)); // 1 hour ago + claims.expires = Some(moq_clock::wall() - Duration::from_secs(3600)); // 1 hour ago let token = key.sign(&claims).unwrap(); let result = key.verify(&token); @@ -1134,8 +1134,8 @@ mod tests { async fn token_validity_uses_the_ambient_wall() { let key = create_test_key(); let mut claims = create_test_claims(); - claims.issued = Some(moq_clock::wall().into()); - claims.expires = Some((moq_clock::wall() + Duration::from_secs(10)).into()); + claims.issued = Some(moq_clock::wall()); + claims.expires = Some(moq_clock::wall() + Duration::from_secs(10)); let token = key.sign(&claims).unwrap(); key.verify(&token).unwrap(); moq_clock::sleep(Duration::from_secs(10)).await; @@ -1169,8 +1169,8 @@ mod tests { root: "test-path".to_string(), publish: patterns(&["test-pub/**"]), subscribe: patterns(&["test-sub/**"]), - expires: Some(SystemTime::now() + Duration::from_secs(3600)), - issued: Some(SystemTime::now()), + expires: Some(moq_clock::wall() + Duration::from_secs(3600)), + issued: Some(moq_clock::wall()), not_before: None, }; @@ -1870,8 +1870,8 @@ mod tests { use std::os::unix::fs::PermissionsExt; fn temp_path(name: &str) -> std::path::PathBuf { - let unique = SystemTime::now() - .duration_since(SystemTime::UNIX_EPOCH) + let unique = moq_clock::wall() + .checked_duration_since(Wall::UNIX_EPOCH) .unwrap() .as_nanos(); std::env::temp_dir().join(format!("test_perms_{name}_{unique}.jwk")) diff --git a/rs/moq-auth/src/lease.rs b/rs/moq-auth/src/lease.rs index 538f73f43f2..4f4489034b9 100644 --- a/rs/moq-auth/src/lease.rs +++ b/rs/moq-auth/src/lease.rs @@ -457,7 +457,6 @@ mod tests { use std::future::Future; use std::pin::pin; use std::task::{Context, Waker}; - use std::time::SystemTime; fn grant(publish: &str) -> Grant { Grant::new( @@ -594,7 +593,7 @@ mod tests { tokio::time::pause(); let mut grant = grant("a/**"); grant.revalidate = Some(Duration::from_secs(10)); - grant.expires = Some(SystemTime::now() + Duration::from_secs(60)); + grant.expires = Some(moq_clock::wall() + Duration::from_secs(60)); let (producer, consumer) = Producer::new(grant.clone()); assert!(tokio::time::timeout(Duration::ZERO, producer.due()).await.is_err()); tokio::time::advance(Duration::from_secs(10)).await; @@ -619,7 +618,7 @@ mod tests { tokio::time::pause(); let mut grant = grant("a/**"); grant.revalidate = Some(Duration::from_secs(30)); - grant.expires = Some(SystemTime::now() + Duration::from_secs(3600)); + grant.expires = Some(moq_clock::wall() + Duration::from_secs(3600)); let (producer, _consumer) = Producer::new(grant.clone()); let producer = std::sync::Arc::new(producer); let waiter = tokio::spawn({ @@ -639,7 +638,7 @@ mod tests { tokio::time::pause(); let mut grant = grant("a/**"); grant.revalidate = Some(Duration::from_secs(30)); - grant.expires = Some(SystemTime::now() + Duration::from_secs(3600)); + grant.expires = Some(moq_clock::wall() + Duration::from_secs(3600)); let (producer, _consumer) = Producer::new(grant); let first = producer.failed(); assert!(first >= Duration::from_millis(750) && first <= Duration::from_millis(1250)); @@ -666,7 +665,7 @@ mod tests { async fn due_expires_even_without_a_recheck() { tokio::time::pause(); let mut grant = grant("a/**"); - grant.expires = Some(SystemTime::now() - Duration::from_secs(4)); + grant.expires = Some(moq_clock::wall() - Duration::from_secs(4)); let (producer, _consumer) = Producer::new(grant); let task = tokio::spawn(async move { producer.due().await }); tokio::task::yield_now().await; diff --git a/rs/moq-auth/src/request.rs b/rs/moq-auth/src/request.rs index c9da30f8e11..7cf96ff40db 100644 --- a/rs/moq-auth/src/request.rs +++ b/rs/moq-auth/src/request.rs @@ -1,9 +1,10 @@ +use moq_clock::Wall; use serde::{Deserialize, Serialize}; use serde_with::base64::{Base64, UrlSafe}; use serde_with::formats::Unpadded; -use serde_with::{DurationSecondsWithFrac, TimestampSeconds, serde_as}; +use serde_with::{DurationSecondsWithFrac, serde_as}; use std::net::SocketAddr; -use std::time::{Duration, SystemTime}; +use std::time::Duration; use crate::lease::Reason; @@ -207,8 +208,8 @@ pub struct Peer { /// SHA-256 of the leaf certificate, hex. pub fingerprint: String, /// The certificate's notAfter. - #[serde_as(as = "Option>")] - pub expires: Option, + #[serde_as(as = "Option")] + pub expires: Option, /// The issuer's distinguished name. pub issuer: String, } @@ -238,7 +239,7 @@ mod tests { request.tls = Some(Peer { name: "edge0".into(), fingerprint: "ab".repeat(32), - expires: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(4_102_444_800)), + expires: Some(Wall::UNIX_EPOCH + Duration::from_secs(4_102_444_800)), issuer: "CN=cluster".into(), }); request diff --git a/rs/moq-auth/src/serve.rs b/rs/moq-auth/src/serve.rs index 5eb1c4f14fb..b94c095f10b 100644 --- a/rs/moq-auth/src/serve.rs +++ b/rs/moq-auth/src/serve.rs @@ -12,7 +12,7 @@ use std::collections::HashMap; use std::net::IpAddr; use std::path::PathBuf; use std::sync::{Arc, Mutex}; -use std::time::{Duration, SystemTime}; +use std::time::Duration; use axum::extract::State; use axum::http::StatusCode; @@ -258,11 +258,7 @@ impl Policy { let mut grant = Grant::new(permissions.publish, permissions.subscribe); grant.expires = match (expires, self.expires) { (Some(expires), _) => Some(expires), - (None, Some(bound)) => Some( - SystemTime::from(moq_clock::wall()) - .checked_add(bound) - .ok_or(Denial::ExpiresOutOfRange)?, - ), + (None, Some(bound)) => Some(moq_clock::wall().checked_add(bound).ok_or(Denial::ExpiresOutOfRange)?), (None, None) => None, }; grant.revalidate = self.revalidate; @@ -301,7 +297,7 @@ impl Policy { crate::Error::Key(crate::KeyError::KeyNotFound(_)) => Denial::UnknownKey, other => Denial::InvalidToken(other.to_string()), })?; - crate::key::validate_times(&claims, SystemTime::from(moq_clock::wall())).map_err(|err| match err { + crate::key::validate_times(&claims, moq_clock::wall()).map_err(|err| match err { crate::Error::TokenExpired => Denial::Expired { root: claims.root.clone(), }, @@ -465,7 +461,7 @@ impl Server { } if policy .expires - .is_some_and(|bound| SystemTime::from(moq_clock::wall()).checked_add(bound).is_none()) + .is_some_and(|bound| moq_clock::wall().checked_add(bound).is_none()) { return Err(crate::Error::ExpiresOutOfRange); } @@ -546,7 +542,6 @@ async fn handle(State(server): State, Json(request): Json) -> R } #[cfg(test)] -#[expect(clippy::disallowed_methods, reason = "tests read the host clock directly")] mod tests { use super::*; use crate::{Algorithm, Bytes, Claims, Client, Error, Peer, Transport, lease::Reason}; @@ -574,10 +569,7 @@ mod tests { ..Default::default() }; let grant = policy.decide(&request("/demo")).await.unwrap(); - assert_eq!( - grant.expires, - Some((moq_clock::wall() + Duration::from_secs(30)).into()) - ); + assert_eq!(grant.expires, Some(moq_clock::wall() + Duration::from_secs(30))); } fn with_token(mut request: Request, jwt: &str) -> Request { @@ -585,7 +577,7 @@ mod tests { request } - fn with_peer(mut request: Request, expires: Option) -> Request { + fn with_peer(mut request: Request, expires: Option) -> Request { request.tls = Some(Peer { name: "edge0".into(), fingerprint: "ab".repeat(32), @@ -603,7 +595,7 @@ mod tests { (dir, key) } - fn sign(key: &Key, root: &str, publish: &[&str], subscribe: &[&str], expires: Option) -> String { + fn sign(key: &Key, root: &str, publish: &[&str], subscribe: &[&str], expires: Option) -> String { let claims = Claims::default() .with_root(root) .with_publish(patterns(publish)) @@ -647,12 +639,12 @@ mod tests { ..Default::default() }; // `exp` is whole seconds on the wire. - let secs = SystemTime::now() - .duration_since(SystemTime::UNIX_EPOCH) + let secs = moq_clock::wall() + .checked_duration_since(moq_clock::Wall::UNIX_EPOCH) .unwrap() .as_secs() + 600; - let exp = SystemTime::UNIX_EPOCH + Duration::from_secs(secs); + let exp = moq_clock::Wall::UNIX_EPOCH + Duration::from_secs(secs); let jwt = sign(&key, "demo/room", &["alice/**"], &["**"], Some(exp)); let grant = policy.decide(&with_token(request("/demo/room/"), &jwt)).await.unwrap(); @@ -673,11 +665,11 @@ mod tests { ..Default::default() }; let jwt = sign(&key, "demo", &["**"], &[], None); - let before = SystemTime::now(); + let before = moq_clock::wall(); let grant = policy.decide(&with_token(request("/demo"), &jwt)).await.unwrap(); let expires = grant.expires.unwrap(); assert!(expires >= before + Duration::from_secs(3600)); - assert!(expires <= SystemTime::now() + Duration::from_secs(3600)); + assert!(expires <= moq_clock::wall() + Duration::from_secs(3600)); } #[tokio::test] @@ -715,7 +707,7 @@ mod tests { "demo", &["**"], &[], - Some(SystemTime::now() - Duration::from_secs(1)), + Some(moq_clock::wall() - Duration::from_secs(1)), ); let err = policy.decide(&with_token(request("/demo"), &jwt)).await.unwrap_err(); assert!(matches!(err, Denial::Expired { .. }), "{err}"); @@ -973,7 +965,7 @@ mod tests { mtls: rules(&["**"], &["**"]), ..Default::default() }; - let not_after = SystemTime::now() + Duration::from_secs(86400 * 30); + let not_after = moq_clock::wall() + Duration::from_secs(86400 * 30); let grant = policy.decide(&with_peer(request("/"), Some(not_after))).await.unwrap(); assert_eq!(grant.publish, patterns(&["**"])); assert_eq!(grant.expires, Some(not_after)); @@ -1283,7 +1275,7 @@ mod tests { "demo", &["**"], &[], - Some(SystemTime::now() + Duration::from_secs(60)), + Some(moq_clock::wall() + Duration::from_secs(60)), ); let mut same_host = with_token(request("/demo"), &other); same_host.remote = Some("[::ffff:203.0.113.9]:9".parse().unwrap()); @@ -1309,7 +1301,7 @@ mod tests { ..limited() }) .unwrap(); - let exp = Some(SystemTime::now() + Duration::from_secs(60)); + let exp = Some(moq_clock::wall() + Duration::from_secs(60)); let a = sign(&key, "demo", &["**"], &[], None); let b = sign(&key, "demo", &["**"], &[], exp); let c = sign( @@ -1317,7 +1309,7 @@ mod tests { "demo", &["**"], &[], - Some(SystemTime::now() + Duration::from_secs(61)), + Some(moq_clock::wall() + Duration::from_secs(61)), ); let mut first = with_token(request("/demo"), &a); @@ -1373,7 +1365,7 @@ mod tests { use crate::refusal::Reason; let (dir, key) = key_dir(); let stranger = Key::generate(Algorithm::HS256, key.kid.clone()).unwrap(); - let expired = Some(SystemTime::UNIX_EPOCH + Duration::from_secs(1)); + let expired = Some(moq_clock::Wall::UNIX_EPOCH + Duration::from_secs(1)); for tier in [None, Some("edge")] { let (client, _) = serve(Policy { keys: Some(Keys::Dir(dir.path().into())), @@ -1442,7 +1434,7 @@ mod tests { "attacker", &["**"], &[], - Some(SystemTime::UNIX_EPOCH + Duration::from_secs(1)), + Some(moq_clock::Wall::UNIX_EPOCH + Duration::from_secs(1)), ); let Error::Refused(refusal) = client .connect(with_token(request("/attacker"), &token)) diff --git a/rs/moq-auth/src/set.rs b/rs/moq-auth/src/set.rs index bd9a0af26e4..0999e831cea 100644 --- a/rs/moq-auth/src/set.rs +++ b/rs/moq-auth/src/set.rs @@ -137,7 +137,6 @@ impl KeySet { } #[cfg(test)] -#[expect(clippy::disallowed_methods, reason = "tests read the host clock directly")] mod tests { use super::*; @@ -145,15 +144,16 @@ mod tests { texts.iter().map(|text| text.parse().unwrap()).collect() } use crate::Algorithm; - use std::time::{Duration, SystemTime}; + use moq_clock::Wall; + use std::time::Duration; fn create_test_claims() -> Claims { Claims { root: "test-path".to_string(), publish: patterns(&["test-pub/**"]), subscribe: patterns(&["test-sub/**"]), - expires: Some(SystemTime::now() + Duration::from_secs(3600)), - issued: Some(SystemTime::now()), + expires: Some(moq_clock::wall() + Duration::from_secs(3600)), + issued: Some(moq_clock::wall()), not_before: None, } } @@ -370,8 +370,8 @@ mod tests { // Use a random-ish name to avoid collisions let filename = format!( "test_keyset_{}.json", - SystemTime::now() - .duration_since(SystemTime::UNIX_EPOCH) + moq_clock::wall() + .checked_duration_since(Wall::UNIX_EPOCH) .unwrap() .as_nanos() ); @@ -392,8 +392,8 @@ mod tests { fn test_file_io_permissions() { use std::os::unix::fs::PermissionsExt; - let unique = SystemTime::now() - .duration_since(SystemTime::UNIX_EPOCH) + let unique = moq_clock::wall() + .checked_duration_since(Wall::UNIX_EPOCH) .unwrap() .as_nanos(); let path = std::env::temp_dir().join(format!("test_keyset_perms_{unique}.json")); diff --git a/rs/moq-auth/src/wire.rs b/rs/moq-auth/src/wire.rs index 09d56739d50..61c4896e117 100644 --- a/rs/moq-auth/src/wire.rs +++ b/rs/moq-auth/src/wire.rs @@ -9,7 +9,7 @@ use moq_pattern::{Pattern, Patterns}; use serde::{Deserialize, Deserializer, Serialize}; -use serde_with::{TimestampSeconds, serde_as}; +use serde_with::serde_as; /// The wire form of [`Claims`](crate::Claims). #[serde_with::skip_serializing_none] @@ -27,12 +27,12 @@ pub(crate) struct Claims { publish: Option, #[serde(deserialize_with = "present")] subscribe: Option, - #[serde_as(as = "Option>")] - exp: Option, - #[serde_as(as = "Option>")] - iat: Option, - #[serde_as(as = "Option>")] - nbf: Option, + #[serde_as(as = "Option")] + exp: Option, + #[serde_as(as = "Option")] + iat: Option, + #[serde_as(as = "Option")] + nbf: Option, // Registered claims that narrow nothing: an issuer's bookkeeping, read and dropped. // Every other claim is refused, since an unknown one may narrow the grant, and a // misspelled `root` would otherwise widen it to everything. diff --git a/rs/moq-bench/clippy.toml b/rs/moq-bench/clippy.toml index f3f8720ac3f..d5a7b48f913 100644 --- a/rs/moq-bench/clippy.toml +++ b/rs/moq-bench/clippy.toml @@ -1,5 +1,4 @@ # Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. -# `SystemTime` stays an allowed type until its wall times move to `moq_clock::Wall`. disallowed-methods = [ { path = "std::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, { path = "std::time::Instant::elapsed", reason = "read the ambient clock: moq_clock::Instant::elapsed()" }, @@ -16,6 +15,7 @@ disallowed-methods = [ ] disallowed-types = [ + { path = "std::time::SystemTime", reason = "use moq_clock::Wall" }, { path = "std::time::Instant", reason = "use moq_clock::Instant" }, { path = "tokio::time::Instant", reason = "use moq_clock::Instant" }, { path = "tokio::time::Sleep", reason = "use moq_clock::Sleep" }, diff --git a/rs/moq-bench/src/connection.rs b/rs/moq-bench/src/connection.rs index d26616ae09a..0f5bcde0373 100644 --- a/rs/moq-bench/src/connection.rs +++ b/rs/moq-bench/src/connection.rs @@ -1,7 +1,8 @@ +use moq_clock::Wall; use std::collections::HashSet; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use std::time::Duration; use moq_tokio::Status; use moq_tokio::moq_net::{self, bytes::Bytes}; @@ -261,9 +262,8 @@ async fn produce( group_size: rolled.group_size, broadcasts: rolled.broadcasts, subscribe: rolled.subscribe, - timestamp_ms: SystemTime::from(moq_clock::wall()) - .duration_since(UNIX_EPOCH) - .unwrap_or_default() + timestamp_ms: moq_clock::wall() + .saturating_duration_since(Wall::UNIX_EPOCH) .as_millis(), pad: String::new(), }; diff --git a/rs/moq-bench/src/host.rs b/rs/moq-bench/src/host.rs index c884df69fe0..439ba50e1c8 100644 --- a/rs/moq-bench/src/host.rs +++ b/rs/moq-bench/src/host.rs @@ -16,9 +16,10 @@ #[cfg(target_os = "linux")] mod linux { + use moq_clock::Wall; use std::collections::HashMap; use std::io::Write; - use std::time::{Duration, SystemTime, UNIX_EPOCH}; + use std::time::Duration; use anyhow::Context; use procfs::CurrentSI; @@ -230,9 +231,8 @@ mod linux { target.ctx.retain(|tid| live.contains(&tid)); Ok(Sample { - timestamp_ms: SystemTime::from(moq_clock::wall()) - .duration_since(UNIX_EPOCH) - .unwrap_or_default() + timestamp_ms: moq_clock::wall() + .saturating_duration_since(Wall::UNIX_EPOCH) .as_millis(), pid: target.proc.pid, comm: stat.comm.clone(), diff --git a/rs/moq-bench/src/stats.rs b/rs/moq-bench/src/stats.rs index ab4aba5480d..f7848897e69 100644 --- a/rs/moq-bench/src/stats.rs +++ b/rs/moq-bench/src/stats.rs @@ -1,7 +1,8 @@ +use moq_clock::Wall; use std::io::Write; use std::sync::Mutex; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use std::time::Duration; use anyhow::Context; use serde::Serialize; @@ -100,9 +101,8 @@ impl Stats { /// Record one group keyframe's wall-clock delivery latency. pub fn latency(&self, sent_ms: u128) { // Read the clock before locking so contention is not measured as latency. - let now_ms = SystemTime::from(moq_clock::wall()) - .duration_since(UNIX_EPOCH) - .unwrap_or_default() + let now_ms = moq_clock::wall() + .saturating_duration_since(Wall::UNIX_EPOCH) .as_millis(); self.latency.observe(sent_ms, now_ms); } @@ -210,8 +210,16 @@ struct Record<'a> { impl<'a> Record<'a> { fn new(previous: &Snapshot, snapshot: &'a Snapshot, interval: &'a IntervalLatency) -> anyhow::Result { - let interval_start_ms = previous.captured_at.duration_since(UNIX_EPOCH)?.as_millis(); - let interval_end_ms = snapshot.captured_at.duration_since(UNIX_EPOCH)?.as_millis(); + let interval_start_ms = previous + .captured_at + .checked_duration_since(Wall::UNIX_EPOCH) + .expect("Wall is after the Unix epoch") + .as_millis(); + let interval_end_ms = snapshot + .captured_at + .checked_duration_since(Wall::UNIX_EPOCH) + .expect("Wall is after the Unix epoch") + .as_millis(); Ok(Self { timestamp_ms: interval_end_ms, interval_start_ms, @@ -239,7 +247,7 @@ struct Activity { struct Snapshot { ready: bool, #[serde(skip)] - captured_at: SystemTime, + captured_at: Wall, connections: Connections, broadcasts: Activity, subscriptions: Activity, @@ -419,7 +427,7 @@ impl Latency { // include only part of an observation. One that reads the clock before the // boundary but locks after it counts in the next interval, unaltered. let state = self.state.lock().expect("latency lock poisoned"); - let captured_at = SystemTime::from(moq_clock::wall()); + let captured_at = moq_clock::wall(); let LatencyState { buckets, max_ms, @@ -443,7 +451,7 @@ impl Latency { } struct LatencySnapshot { - captured_at: SystemTime, + captured_at: Wall, samples: u64, p50_ms: Option, p90_ms: Option, @@ -724,10 +732,10 @@ mod tests { fn report_bounds_belong_to_captured_samples() { let stats = Stats::default(); let mut previous = Snapshot::take(&stats); - previous.captured_at = UNIX_EPOCH + Duration::from_millis(1_000); + previous.captured_at = Wall::UNIX_EPOCH + Duration::from_millis(1_000); stats.latency.observe(1_000, 1_050); let mut snapshot = Snapshot::take(&stats); - snapshot.captured_at = UNIX_EPOCH + Duration::from_millis(2_000); + snapshot.captured_at = Wall::UNIX_EPOCH + Duration::from_millis(2_000); // This delivery belongs to the next capture, even if report construction is delayed. stats.latency.observe(2_000, 2_050); @@ -750,7 +758,11 @@ mod tests { fn observation_racing_a_capture_keeps_its_latency() { let latency = Latency::default(); let first = latency.snapshot(); - let captured_ms = first.captured_at.duration_since(UNIX_EPOCH).unwrap().as_millis(); + let captured_ms = first + .captured_at + .checked_duration_since(Wall::UNIX_EPOCH) + .unwrap() + .as_millis(); latency.observe(captured_ms - 100, captured_ms - 50); latency.observe(captured_ms - 50, captured_ms - 100); diff --git a/rs/moq-cli/clippy.toml b/rs/moq-cli/clippy.toml index f3f8720ac3f..d5a7b48f913 100644 --- a/rs/moq-cli/clippy.toml +++ b/rs/moq-cli/clippy.toml @@ -1,5 +1,4 @@ # Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. -# `SystemTime` stays an allowed type until its wall times move to `moq_clock::Wall`. disallowed-methods = [ { path = "std::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, { path = "std::time::Instant::elapsed", reason = "read the ambient clock: moq_clock::Instant::elapsed()" }, @@ -16,6 +15,7 @@ disallowed-methods = [ ] disallowed-types = [ + { path = "std::time::SystemTime", reason = "use moq_clock::Wall" }, { path = "std::time::Instant", reason = "use moq_clock::Instant" }, { path = "tokio::time::Instant", reason = "use moq_clock::Instant" }, { path = "tokio::time::Sleep", reason = "use moq_clock::Sleep" }, diff --git a/rs/moq-cli/src/auth.rs b/rs/moq-cli/src/auth.rs index 625c79aa1d3..a75d3cd9bc3 100644 --- a/rs/moq-cli/src/auth.rs +++ b/rs/moq-cli/src/auth.rs @@ -591,9 +591,9 @@ fn read_token(path: &std::path::Path) -> anyhow::Result { } #[derive(Clone, Copy, Debug)] -struct UnixTimestamp(std::time::SystemTime); +struct UnixTimestamp(moq_clock::Wall); -impl From for std::time::SystemTime { +impl From for moq_clock::Wall { fn from(value: UnixTimestamp) -> Self { value.0 } @@ -605,13 +605,10 @@ impl std::str::FromStr for UnixTimestamp { fn from_str(s: &str) -> Result { let timestamp = s.parse::().context("expected unix timestamp")?; let timestamp = timestamp.try_into().context("timestamp out of range")?; - // checked_add, because plain `+` panics on overflow and how far a SystemTime - // reaches is platform-dependent: a timespec holds i64 seconds, while Windows - // counts 100ns ticks and runs out far sooner. - let value = std::time::SystemTime::UNIX_EPOCH - .checked_add(std::time::Duration::from_secs(timestamp)) - .context("timestamp out of range")?; - Ok(Self(value)) + // Past 2554 saturates, like a decoded token time. + Ok(Self( + moq_clock::Wall::UNIX_EPOCH.saturating_add(std::time::Duration::from_secs(timestamp)), + )) } } @@ -998,10 +995,11 @@ mod tests { assert!("not-a-number".parse::().is_err()); } - // Whether the largest parseable timestamp is representable depends on the - // platform's SystemTime, so assert only that it never panics. #[test] - fn timestamp_at_the_maximum_does_not_panic() { - let _ = i64::MAX.to_string().parse::(); + fn timestamp_past_the_wall_range_saturates() { + let last = moq_clock::Wall::UNIX_EPOCH.saturating_add(std::time::Duration::MAX); + let parse = |text: &str| moq_clock::Wall::from(text.parse::().unwrap()); + assert_eq!(parse(&i64::MAX.to_string()), last); + assert!(parse("18446744073") < last); } } diff --git a/rs/moq-cli/src/publish.rs b/rs/moq-cli/src/publish.rs index 33cd4bb4d5b..865f18b44f8 100644 --- a/rs/moq-cli/src/publish.rs +++ b/rs/moq-cli/src/publish.rs @@ -1421,9 +1421,9 @@ pub(crate) mod tests { let Source::Stream { decoder, .. } = &mut publish.source else { panic!("expected a stream source"); }; - let before = std::time::SystemTime::now(); + let before = moq_clock::wall(); decoder.decode_chunk(BBB).unwrap(); - let after = std::time::SystemTime::now(); + let after = moq_clock::wall(); decoder.finish().unwrap(); let catalog = hang::catalog::Catalog::<()>::subscribe(&consumer) diff --git a/rs/moq-clock/Cargo.toml b/rs/moq-clock/Cargo.toml index 00c795cb3d1..aea73c9d624 100644 --- a/rs/moq-clock/Cargo.toml +++ b/rs/moq-clock/Cargo.toml @@ -14,7 +14,7 @@ keywords = ["moq", "time", "clock", "timer", "simulation"] categories = ["asynchronous", "date-and-time", "development-tools::testing"] [package.metadata.docs.rs] -features = ["manual", "sim"] +features = ["manual", "sim", "serde"] # The self dev-dependency below only enables a feature; no code names it. [package.metadata.cargo-shear] @@ -22,6 +22,8 @@ ignored = ["moq-clock"] [features] default = ["runtime"] +# Numeric Unix-second JSON adapters for public wall times. +serde = ["dep:serde", "dep:serde_with"] # The deterministic single-threaded executor and `#[moq_clock::test]`. Meant for # dev-dependencies, so production builds never compile it. sim = ["dep:futures", "dep:moq-clock-macros", "kio/sim"] @@ -34,6 +36,8 @@ manual = ["runtime"] futures = { workspace = true, optional = true } kio = { workspace = true } moq-clock-macros = { workspace = true, optional = true } +serde = { workspace = true, optional = true } +serde_with = { workspace = true, optional = true } web-async = { workspace = true, optional = true } # The browser's only clocks, read with or without the runtime's timers. @@ -47,7 +51,8 @@ tokio = { workspace = true, features = ["rt", "time"], optional = true } [dev-dependencies] # Enable the simulator so its tests run in the merge gate. Without default features, # so `--no-default-features` still tests the build without the runtime. -moq-clock = { path = ".", default-features = false, features = ["sim"] } +moq-clock = { path = ".", default-features = false, features = ["sim", "serde"] } +serde_json = { workspace = true } [target.'cfg(all(target_arch = "wasm32", not(target_os = "wasi")))'.dev-dependencies] # Match the wasm-bindgen CLI schema used by the browser runner. @@ -56,7 +61,7 @@ wasm-bindgen-test = "=0.3.79" [target.'cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))'.dev-dependencies] # Test the installed manual clock, which needs tokio's runtime and so is native only. -moq-clock = { path = ".", default-features = false, features = ["manual", "sim"] } +moq-clock = { path = ".", default-features = false, features = ["manual", "sim", "serde"] } tokio = { workspace = true, features = ["rt", "rt-multi-thread", "test-util", "time"] } [lints] diff --git a/rs/moq-clock/src/lib.rs b/rs/moq-clock/src/lib.rs index 90071a8a0be..9dc024845e2 100644 --- a/rs/moq-clock/src/lib.rs +++ b/rs/moq-clock/src/lib.rs @@ -22,6 +22,9 @@ //! The `sim` feature adds the `sim` module, a deterministic executor whose clock //! starts at [`Instant::ZERO`], and the `#[moq_clock::test]` attribute that runs an //! `async fn` test on it. Enable it for dev-dependencies only. +//! +//! The `serde` feature adds `serde::UnixSeconds`, matching existing integer +//! Unix-second JSON encodings for wall times. #![warn(missing_docs)] @@ -33,6 +36,8 @@ mod instant; compile_error!("the `manual` feature installs on a tokio runtime, which the browser has none of"); mod manual; mod runtime; +#[cfg(feature = "serde")] +pub mod serde; #[cfg(feature = "sim")] pub mod sim; mod timer; diff --git a/rs/moq-clock/src/serde.rs b/rs/moq-clock/src/serde.rs new file mode 100644 index 00000000000..e46487a2279 --- /dev/null +++ b/rs/moq-clock/src/serde.rs @@ -0,0 +1,82 @@ +//! JSON adapters that preserve existing wall-time encodings. + +use crate::Wall; +use ::serde::{Deserialize, Deserializer, Serializer}; +use serde_with::{DeserializeAs, SerializeAs, TimestampSeconds}; + +/// Encode a wall time as whole Unix seconds, matching serde_with's integer timestamp adapter. +/// +/// Decoding saturates: before 1970 reads as the epoch, and past 2554 as Wall's last time. +pub struct UnixSeconds; + +impl SerializeAs for UnixSeconds { + fn serialize_as(value: &Wall, serializer: S) -> Result { + TimestampSeconds::::serialize_as(&std::time::SystemTime::from(*value), serializer) + } +} + +impl<'de> DeserializeAs<'de, Wall> for UnixSeconds { + fn deserialize_as>(deserializer: D) -> Result { + let seconds = i64::deserialize(deserializer)?; + let since = std::time::Duration::from_secs(u64::try_from(seconds).unwrap_or(0)); + Ok(Wall::UNIX_EPOCH.saturating_add(since)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use ::serde::{Deserialize, Serialize}; + use std::time::Duration; + + #[serde_with::serde_as] + #[derive(Debug, Serialize, Deserialize, PartialEq)] + struct Value { + #[serde_as(as = "Option")] + wall: Option, + } + + #[test] + fn preserves_integer_seconds_and_null() { + for json in [ + r#"{"wall":0}"#, + r#"{"wall":1700000000}"#, + r#"{"wall":18446744073}"#, + r#"{"wall":null}"#, + ] { + let value: Value = serde_json::from_str(json).unwrap(); + assert_eq!(serde_json::to_string(&value).unwrap(), json); + } + for nanos in [1, 499_999_999, 500_000_000, 999_999_999] { + let wall = Wall::UNIX_EPOCH + Duration::new(1_700_000_000, nanos); + let actual = serde_json::to_string(&Value { wall: Some(wall) }).unwrap(); + let expected = serde_with::As::>::serialize( + &std::time::SystemTime::from(wall), + serde_json::value::Serializer, + ) + .unwrap(); + assert_eq!( + serde_json::from_str::(&actual).unwrap()["wall"], + expected + ); + } + } + + #[test] + fn saturates_outside_the_wall_range() { + let last = Wall::UNIX_EPOCH.saturating_add(Duration::MAX); + for (seconds, expected) in [ + (i64::MIN, Wall::UNIX_EPOCH), + (-1, Wall::UNIX_EPOCH), + (18_446_744_074, last), + (i64::MAX, last), + ] { + let value: Value = serde_json::from_str(&format!(r#"{{"wall":{seconds}}}"#)).unwrap(); + assert_eq!(value.wall, Some(expected)); + } + // The last wall time rounds up past the range and reads back as itself. + let json = serde_json::to_string(&Value { wall: Some(last) }).unwrap(); + assert_eq!(json, r#"{"wall":18446744074}"#); + assert_eq!(serde_json::from_str::(&json).unwrap().wall, Some(last)); + } +} diff --git a/rs/moq-clock/src/wall.rs b/rs/moq-clock/src/wall.rs index be5d7df1e2b..313871c259f 100644 --- a/rs/moq-clock/src/wall.rs +++ b/rs/moq-clock/src/wall.rs @@ -42,6 +42,12 @@ impl Wall { self.0.checked_add(nanos).map(Self) } + /// This time moved forward by `duration`, stopping at the last time in 2554. + pub fn saturating_add(&self, duration: Duration) -> Self { + let nanos = u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX); + Self(self.0.saturating_add(nanos)) + } + /// This time moved back by `duration`, or `None` before 1970. pub fn checked_sub(&self, duration: Duration) -> Option { let nanos = u64::try_from(duration.as_nanos()).ok()?; @@ -116,6 +122,13 @@ mod tests { assert_eq!(back.checked_duration_since(wall), None); assert_eq!(back.saturating_duration_since(wall), Duration::ZERO); assert_eq!(Wall::UNIX_EPOCH.checked_sub(Duration::from_nanos(1)), None); + let last = Wall::UNIX_EPOCH.saturating_add(Duration::MAX); + assert_eq!(last, Wall::UNIX_EPOCH + Duration::from_nanos(u64::MAX)); + assert_eq!(last.saturating_add(Duration::from_nanos(1)), last); + assert_eq!( + wall.saturating_add(Duration::from_secs(1)), + wall + Duration::from_secs(1) + ); } #[test] diff --git a/rs/moq-ffi/clippy.toml b/rs/moq-ffi/clippy.toml index db1d0ee8dbe..d2d69deef2c 100644 --- a/rs/moq-ffi/clippy.toml +++ b/rs/moq-ffi/clippy.toml @@ -8,3 +8,5 @@ disallowed-methods = [ { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()", allow-invalid = true }, { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()", allow-invalid = true }, ] + +disallowed-types = [{ path = "std::time::SystemTime", reason = "use moq_clock::Wall" }] diff --git a/rs/moq-ffi/src/origin.rs b/rs/moq-ffi/src/origin.rs index 3f0e621660c..66ece34585a 100644 --- a/rs/moq-ffi/src/origin.rs +++ b/rs/moq-ffi/src/origin.rs @@ -105,9 +105,10 @@ pub fn moq_mint_epoch() -> String { #[uniffi::export] pub fn moq_epoch_time_ms(epoch: String) -> Result { let epoch: moq_net::Epoch = epoch.parse()?; - let since = epoch.time().duration_since(std::time::UNIX_EPOCH).unwrap_or_default(); - // A UUIDv7 holds 48 bits of milliseconds, so this never truncates. - Ok(since.as_millis() as u64) + // This numeric API retains UUIDv7's full 48-bit range, beyond Wall's year 2554. + // Parsing above guarantees these fields are canonical hexadecimal Unix milliseconds. + let text = epoch.as_str(); + Ok(u64::from_str_radix(&text[..8], 16).unwrap() << 16 | u64::from_str_radix(&text[9..13], 16).unwrap()) } /// An origin in which broadcasts can be published. diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index b15f6172d97..e2a94ebba3d 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -414,9 +414,17 @@ async fn announced_route_keeps_static_cost_on_reannounce() { #[test] fn epoch_helpers_mint_parse_and_refuse() { + assert_eq!( + moq_epoch_time_ms("ffffffff-ffff-7fff-bfff-ffffffffffff".into()).unwrap(), + (1_u64 << 48) - 1 + ); let epoch = moq_mint_epoch(); let parsed: moq_net::Epoch = epoch.parse().unwrap(); - let unix_ms = parsed.time().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis(); + let unix_ms = parsed + .time() + .unwrap() + .saturating_duration_since(moq_clock::Wall::UNIX_EPOCH) + .as_millis(); assert_eq!(u128::from(moq_epoch_time_ms(epoch.clone()).unwrap()), unix_ms); assert!(moq_mint_epoch() > epoch, "a later mint orders newer"); diff --git a/rs/moq-gst/clippy.toml b/rs/moq-gst/clippy.toml index f3f8720ac3f..d5a7b48f913 100644 --- a/rs/moq-gst/clippy.toml +++ b/rs/moq-gst/clippy.toml @@ -1,5 +1,4 @@ # Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. -# `SystemTime` stays an allowed type until its wall times move to `moq_clock::Wall`. disallowed-methods = [ { path = "std::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, { path = "std::time::Instant::elapsed", reason = "read the ambient clock: moq_clock::Instant::elapsed()" }, @@ -16,6 +15,7 @@ disallowed-methods = [ ] disallowed-types = [ + { path = "std::time::SystemTime", reason = "use moq_clock::Wall" }, { path = "std::time::Instant", reason = "use moq_clock::Instant" }, { path = "tokio::time::Instant", reason = "use moq_clock::Instant" }, { path = "tokio::time::Sleep", reason = "use moq_clock::Sleep" }, diff --git a/rs/moq-gst/src/sink/imp.rs b/rs/moq-gst/src/sink/imp.rs index 784a3a7a57c..31df8e90bb9 100644 --- a/rs/moq-gst/src/sink/imp.rs +++ b/rs/moq-gst/src/sink/imp.rs @@ -661,7 +661,7 @@ impl MoqSink { }); let sample = super::wall::Sample { running: reference_running_time, - wall: moq_clock::wall().into(), + wall: moq_clock::wall(), }; let map = buffer.map_readable().map_err(|_| { gst::error!(CAT, "failed to map buffer on pad {}", pad.name()); @@ -1179,7 +1179,7 @@ mod tests { Duration::ZERO, super::super::wall::Sample { running: Some(gst::ClockTime::ZERO), - wall: std::time::SystemTime::UNIX_EPOCH + Duration::from_secs(1_735_689_600), + wall: moq_clock::Wall::UNIX_EPOCH + Duration::from_secs(1_735_689_600), }, ) .unwrap(); diff --git a/rs/moq-gst/src/sink/wall.rs b/rs/moq-gst/src/sink/wall.rs index 38bf525b771..4d3b9fea990 100644 --- a/rs/moq-gst/src/sink/wall.rs +++ b/rs/moq-gst/src/sink/wall.rs @@ -4,7 +4,7 @@ use std::sync::{ Arc, Mutex, atomic::{AtomicBool, Ordering}, }; -use std::time::{Duration, SystemTime}; +use std::time::Duration; use anyhow::{Context, Result}; @@ -12,7 +12,7 @@ use anyhow::{Context, Result}; #[derive(Clone, Copy)] pub(super) struct Sample { pub running: Option, - pub wall: SystemTime, + pub wall: moq_clock::Wall, } /// Places running-time zero on the wall clock once per run, holding the first catalog until then. @@ -54,7 +54,7 @@ impl Wall { } } -fn wall_zero(buffer: &gst::BufferRef, pts: Duration, sample: Sample) -> Result { +fn wall_zero(buffer: &gst::BufferRef, pts: Duration, sample: Sample) -> Result { for meta in buffer.iter_meta::() { let Some(reference) = meta.reference().structure(0) else { continue; @@ -68,7 +68,7 @@ fn wall_zero(buffer: &gst::BufferRef, pts: Duration, sample: Sample) -> Result continue, }; - return SystemTime::UNIX_EPOCH + return moq_clock::Wall::UNIX_EPOCH .checked_add(unix) .and_then(|wall| wall.checked_sub(pts)) .context("reference timestamp cannot place running-time zero"); @@ -93,7 +93,7 @@ mod tests { #[test] fn delayed_buffers_and_unknown_domains_use_the_pipeline_clock() { gst::init().unwrap(); - let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_735_689_620); + let now = moq_clock::Wall::UNIX_EPOCH + Duration::from_secs(1_735_689_620); let mut buffer = gst::Buffer::new(); gst::ReferenceTimestampMeta::add( buffer.get_mut().unwrap(), @@ -145,11 +145,11 @@ mod tests { Duration::from_secs(3), Sample { running: None, - wall: SystemTime::UNIX_EPOCH + wall: moq_clock::Wall::UNIX_EPOCH } ) .unwrap(), - SystemTime::UNIX_EPOCH + Duration::from_secs(1_735_689_600) + moq_clock::Wall::UNIX_EPOCH + Duration::from_secs(1_735_689_600) ); } } diff --git a/rs/moq-hls/clippy.toml b/rs/moq-hls/clippy.toml index f3f8720ac3f..d5a7b48f913 100644 --- a/rs/moq-hls/clippy.toml +++ b/rs/moq-hls/clippy.toml @@ -1,5 +1,4 @@ # Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. -# `SystemTime` stays an allowed type until its wall times move to `moq_clock::Wall`. disallowed-methods = [ { path = "std::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, { path = "std::time::Instant::elapsed", reason = "read the ambient clock: moq_clock::Instant::elapsed()" }, @@ -16,6 +15,7 @@ disallowed-methods = [ ] disallowed-types = [ + { path = "std::time::SystemTime", reason = "use moq_clock::Wall" }, { path = "std::time::Instant", reason = "use moq_clock::Instant" }, { path = "tokio::time::Instant", reason = "use moq_clock::Instant" }, { path = "tokio::time::Sleep", reason = "use moq_clock::Sleep" }, diff --git a/rs/moq-hls/src/export/mod.rs b/rs/moq-hls/src/export/mod.rs index d424fe5f66a..9648e4cae04 100644 --- a/rs/moq-hls/src/export/mod.rs +++ b/rs/moq-hls/src/export/mod.rs @@ -41,7 +41,7 @@ pub mod renditions; pub mod segments; use std::sync::{Arc, Mutex}; -use std::time::{Duration, SystemTime}; +use std::time::Duration; use moq_mux::catalog::{self, CatalogFormat, Stream}; use rand::RngExt; @@ -344,7 +344,7 @@ impl Broadcaster { Ok(Some(mpd::render_manifest( &mpd::Manifest { availability_start, - publish: SystemTime::from(moq_clock::wall()), + publish: moq_clock::wall(), window: self.renditions.window(), finished, video, @@ -2468,15 +2468,13 @@ mod tests { // timescale into the clock's. #[tokio::test] async fn root_clock_times_playlists_and_manifest() { - use std::time::{SystemTime, UNIX_EPOCH}; - let origin = produce_origin(); let mut broadcast = origin.create_broadcast("live").expect("publish allowed"); broadcast.announce(Default::default()).expect("publish allowed"); settle().await; // PTS zero at exactly the moq epoch, so every timestamp maps to a fixed string. - let wall = UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS); + let wall = moq_clock::Wall::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS); let config = moq_mux::catalog::Config::default() .with_clock(moq_mux::Clock::at(moq_net::time::Instant::now(), wall).expect("a representable wall")); let catalog = moq_mux::catalog::Producer::new(&mut broadcast, config).unwrap(); @@ -2506,7 +2504,7 @@ mod tests { let snapshot = rendition.snapshot(); assert_eq!( snapshot.program_date_time, - Some(SystemTime::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS)) + Some(moq_clock::Wall::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS)) ); let playlist = rendition.media_playlist(None).unwrap().expect("playlist renders"); assert!( @@ -2646,7 +2644,10 @@ mod tests { let first = anchored .wall_clock(moq_net::Timestamp::from_micros(start).unwrap()) .unwrap(); - let expected = format!("#EXT-X-PROGRAM-DATE-TIME:{}\n", humantime::format_rfc3339_millis(first)); + let expected = format!( + "#EXT-X-PROGRAM-DATE-TIME:{}\n", + humantime::format_rfc3339_millis(first.into()) + ); assert!(playlist.contains(&expected), "{expected} in {playlist}"); drop((import, catalog)); diff --git a/rs/moq-hls/src/export/mpd.rs b/rs/moq-hls/src/export/mpd.rs index 54b2f6ce69a..d31e17f788c 100644 --- a/rs/moq-hls/src/export/mpd.rs +++ b/rs/moq-hls/src/export/mpd.rs @@ -13,10 +13,11 @@ //! `Representation` id keeps the raw name. The resources are shared byte-for-byte with the //! HLS routes; only the time-addressed segment alias `seg/t.m4s` is DASH's own. +use moq_clock::Wall; use std::collections::{BTreeMap, BTreeSet}; use std::fmt::Write; use std::sync::Arc; -use std::time::{Duration, SystemTime}; +use std::time::Duration; use percent_encoding::utf8_percent_encode; @@ -67,9 +68,9 @@ pub(crate) struct Representation { pub(crate) struct Manifest { /// The wall-clock time of timeline `pts` 0 (`MPD@availabilityStartTime`). Required while /// live (`type="dynamic"`); ignored once [`finished`](Self::finished). - pub availability_start: Option, + pub availability_start: Option, /// When this render happened (`MPD@publishTime`, dynamic only). - pub publish: SystemTime, + pub publish: Wall, /// The playlist window (`MPD@timeShiftBufferDepth`, dynamic only), or `None` when the /// timeline bounds itself and the depth is the span it lists. pub window: Option, @@ -286,7 +287,7 @@ pub(crate) fn render_manifest(manifest: &Manifest, query: Option<&str>) -> Strin xs_duration(duration) ); } else { - let availability = manifest.availability_start.unwrap_or(SystemTime::UNIX_EPOCH); + let availability = manifest.availability_start.unwrap_or(Wall::UNIX_EPOCH); // Reload cadence and live delay follow HLS conventions: players refresh about once // per segment and sit a few segments behind the live edge (bounded by the window). let update = Duration::from_secs(target); @@ -295,8 +296,8 @@ pub(crate) fn render_manifest(manifest: &Manifest, query: Option<&str>) -> Strin let _ = write!( out, " type=\"dynamic\" availabilityStartTime=\"{}\" publishTime=\"{}\" minimumUpdatePeriod=\"{}\" timeShiftBufferDepth=\"{}\" suggestedPresentationDelay=\"{}\"", - humantime::format_rfc3339_millis(availability), - humantime::format_rfc3339_millis(manifest.publish), + humantime::format_rfc3339_millis(availability.into()), + humantime::format_rfc3339_millis(manifest.publish.into()), xs_duration(update), xs_duration(window), xs_duration(delay), @@ -368,8 +369,8 @@ mod tests { next.period = moq_net::Timestamp::from_secs(6).unwrap(); next.tag = "next".into(); let manifest = Manifest { - availability_start: Some(SystemTime::UNIX_EPOCH), - publish: SystemTime::UNIX_EPOCH, + availability_start: Some(Wall::UNIX_EPOCH), + publish: Wall::UNIX_EPOCH, window: None, finished: false, video: vec![old, next], @@ -393,8 +394,8 @@ mod tests { next.timescale = 90_000; next.period = moq_net::Timestamp::new(1, scale).unwrap(); let manifest = Manifest { - availability_start: Some(SystemTime::UNIX_EPOCH), - publish: SystemTime::UNIX_EPOCH, + availability_start: Some(Wall::UNIX_EPOCH), + publish: Wall::UNIX_EPOCH, window: None, finished: false, video: vec![next], @@ -428,8 +429,8 @@ mod tests { #[test] fn renders_dynamic_manifest() { let manifest = Manifest { - availability_start: Some(SystemTime::UNIX_EPOCH + Duration::from_millis(1_751_846_400_123)), - publish: SystemTime::UNIX_EPOCH + Duration::from_millis(1_751_846_410_000), + availability_start: Some(Wall::UNIX_EPOCH + Duration::from_millis(1_751_846_400_123)), + publish: Wall::UNIX_EPOCH + Duration::from_millis(1_751_846_410_000), window: Some(Duration::from_secs(16)), finished: false, video: vec![video(vec![(0, 2_000), (2_000, 2_000)], false)], @@ -469,7 +470,7 @@ mod tests { fn renders_static_manifest_when_finished() { let manifest = Manifest { availability_start: None, - publish: SystemTime::UNIX_EPOCH, + publish: Wall::UNIX_EPOCH, window: Some(Duration::from_secs(16)), finished: true, // The window starts mid-broadcast: presentation time stays anchored at pts 0 (no @@ -492,8 +493,8 @@ mod tests { #[test] fn query_rides_child_urls_escaped() { let manifest = Manifest { - availability_start: Some(SystemTime::UNIX_EPOCH), - publish: SystemTime::UNIX_EPOCH, + availability_start: Some(Wall::UNIX_EPOCH), + publish: Wall::UNIX_EPOCH, window: Some(Duration::from_secs(16)), finished: false, video: vec![video(vec![(0, 2_000)], false)], @@ -510,8 +511,8 @@ mod tests { let mut rep = video(vec![(0, 2_000)], false); rep.generation = Some("run-7".into()); let manifest = Manifest { - availability_start: Some(SystemTime::UNIX_EPOCH), - publish: SystemTime::UNIX_EPOCH, + availability_start: Some(Wall::UNIX_EPOCH), + publish: Wall::UNIX_EPOCH, window: Some(Duration::from_secs(16)), finished: false, video: vec![rep], @@ -533,8 +534,8 @@ mod tests { #[test] fn empty_and_gap_only_representations_are_omitted() { let manifest = Manifest { - availability_start: Some(SystemTime::UNIX_EPOCH), - publish: SystemTime::UNIX_EPOCH, + availability_start: Some(Wall::UNIX_EPOCH), + publish: Wall::UNIX_EPOCH, window: Some(Duration::from_secs(16)), finished: false, video: vec![video(vec![(0, 2_000)], false)], @@ -551,8 +552,8 @@ mod tests { rep.name = name.into(); render_manifest( &Manifest { - availability_start: Some(SystemTime::UNIX_EPOCH), - publish: SystemTime::UNIX_EPOCH, + availability_start: Some(Wall::UNIX_EPOCH), + publish: Wall::UNIX_EPOCH, window: Some(Duration::from_secs(16)), finished: false, video: vec![rep], diff --git a/rs/moq-hls/src/export/playlist.rs b/rs/moq-hls/src/export/playlist.rs index 3d28ac6f296..336b47df054 100644 --- a/rs/moq-hls/src/export/playlist.rs +++ b/rs/moq-hls/src/export/playlist.rs @@ -6,9 +6,10 @@ //! (`////media.m3u8`), so they resolve against the rendition //! directory. +use moq_clock::Wall; use std::fmt::Write; use std::sync::Arc; -use std::time::{Duration, SystemTime}; +use std::time::Duration; /// fMP4 segments via `EXT-X-MAP` require protocol version 6. const VERSION: u32 = 6; @@ -31,7 +32,7 @@ pub(crate) struct Snapshot { pub finished: bool, /// Wall-clock time of the first listed segment (`EXT-X-PROGRAM-DATE-TIME`), when the /// catalog advertises its root broadcast clock. - pub program_date_time: Option, + pub program_date_time: Option, /// The publisher run every segment URL carries (`seg/{generation}.{tag}.{segment}.m4s`). pub generation: Option>, } @@ -88,7 +89,7 @@ pub(crate) fn render_media(snapshot: &Snapshot, init: &str, query: Option<&str>) let _ = writeln!( out, "#EXT-X-PROGRAM-DATE-TIME:{}", - humantime::format_rfc3339_millis(pdt) + humantime::format_rfc3339_millis(pdt.into()) ); } if segment.discontinuity { @@ -137,7 +138,7 @@ mod tests { }, ], finished: false, - program_date_time: Some(SystemTime::UNIX_EPOCH + Duration::from_millis(1_751_846_400_123)), + program_date_time: Some(Wall::UNIX_EPOCH + Duration::from_millis(1_751_846_400_123)), generation: None, }; diff --git a/rs/moq-hls/src/export/rendition.rs b/rs/moq-hls/src/export/rendition.rs index 2d2e6e00447..3e9d66cbba7 100644 --- a/rs/moq-hls/src/export/rendition.rs +++ b/rs/moq-hls/src/export/rendition.rs @@ -1,10 +1,11 @@ //! One rendition: playlists from its view of the broadcast's segments, resolved against its own //! timeline, and segments fetched on demand. +use moq_clock::Wall; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, RwLock}; use std::task::Poll; -use std::time::{Duration, SystemTime}; +use std::time::Duration; use bytes::Bytes; use hang::catalog::{Archive, AudioConfig, Clock, Reference, VideoConfig}; @@ -1003,7 +1004,7 @@ impl Rendition { /// The wall-clock time of a media timestamp, when the catalog advertises its broadcast /// clock. Converts the timeline-timescale timestamp into the clock's timescale and applies /// the root mapping; an unrepresentable result maps to no time rather than a truncated one. - pub(crate) fn wall_clock(&self, pts: moq_net::Timestamp) -> Option { + pub(crate) fn wall_clock(&self, pts: moq_net::Timestamp) -> Option { let clock = self.clock.as_ref()?; clock.wall_clock(pts).ok() } diff --git a/rs/moq-hls/src/export/renditions.rs b/rs/moq-hls/src/export/renditions.rs index f75a3f825d8..000831c70df 100644 --- a/rs/moq-hls/src/export/renditions.rs +++ b/rs/moq-hls/src/export/renditions.rs @@ -10,10 +10,11 @@ //! set as [`Added`](Event::Added) when first consumed, and returning `None` once the source //! finishes cleanly, or an error when the recording is incomplete. +use moq_clock::Wall; use std::collections::{BTreeMap, VecDeque}; use std::sync::{Arc, Weak}; use std::task::Poll; -use std::time::{Duration, SystemTime}; +use std::time::Duration; use moq_mux::catalog::hang::Catalog; use moq_mux::timeline::Entry; @@ -72,7 +73,7 @@ struct Feed { /// `availabilityStartTime` falls back to this when the catalog declares no `clock`; set /// once so reloads see a stable presentation, and reset with the window when the /// timeline restarts. - anchor: Option, + anchor: Option, /// The publisher run every segment URL carries; late-created renditions inherit it. generation: Option>, /// The playlist window duration applied on every push (see @@ -159,7 +160,7 @@ impl Producer { /// The estimated wall-clock time of timeline `pts` 0 (see [`Feed::anchor`]); `None` until /// the first record arrives. - pub fn anchor(&self) -> Option { + pub fn anchor(&self) -> Option { self.fanout.feed.read().anchor } @@ -309,11 +310,7 @@ impl Fanout { }); } if feed.anchor.is_none() { - feed.anchor = Some( - SystemTime::from(moq_clock::wall()) - .checked_sub(end) - .unwrap_or(SystemTime::UNIX_EPOCH), - ); + feed.anchor = Some(moq_clock::wall().checked_sub(end).unwrap_or(Wall::UNIX_EPOCH)); } let period = feed.last.as_ref().map_or(moq_net::Timestamp::ZERO, |last| { if last.reference == *reference { diff --git a/rs/moq-hls/src/export/segments.rs b/rs/moq-hls/src/export/segments.rs index 85bbc421239..fedb064bced 100644 --- a/rs/moq-hls/src/export/segments.rs +++ b/rs/moq-hls/src/export/segments.rs @@ -18,10 +18,11 @@ //! every reload. A new reference lists its records under its own tag, continuing past the last //! advertised number rather than reusing the old one's URIs. +use moq_clock::Wall; use std::collections::VecDeque; use std::sync::Arc; use std::task::{Poll, ready}; -use std::time::{Duration, SystemTime}; +use std::time::Duration; use bytes::Bytes; use sha2::{Digest, Sha256}; @@ -475,7 +476,7 @@ pub struct Segment { /// Presentation duration. pub duration: Duration, /// Wall-clock start time, when the timeline advertises an anchor. - pub program_date_time: Option, + pub program_date_time: Option, /// The absolute timeline discontinuity sequence within this broadcaster. /// /// Use the first retained segment's value as `EXT-X-DISCONTINUITY-SEQUENCE`, then write diff --git a/rs/moq-mux/clippy.toml b/rs/moq-mux/clippy.toml index db1d0ee8dbe..d2d69deef2c 100644 --- a/rs/moq-mux/clippy.toml +++ b/rs/moq-mux/clippy.toml @@ -8,3 +8,5 @@ disallowed-methods = [ { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()", allow-invalid = true }, { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()", allow-invalid = true }, ] + +disallowed-types = [{ path = "std::time::SystemTime", reason = "use moq_clock::Wall" }] diff --git a/rs/moq-mux/src/binary.rs b/rs/moq-mux/src/binary.rs index cf119822a2d..380d88f81a1 100644 --- a/rs/moq-mux/src/binary.rs +++ b/rs/moq-mux/src/binary.rs @@ -640,9 +640,10 @@ mod test { /// payload would read as a near-zero bitrate. #[test] fn an_unset_host_clock_still_marks_a_reanchor() { - use std::time::{Duration, SystemTime}; + use moq_clock::Wall; + use std::time::Duration; - crate::clock::fake_host_wall(SystemTime::UNIX_EPOCH + Duration::from_secs(86_400)); + crate::clock::fake_host_wall(Wall::UNIX_EPOCH + Duration::from_secs(86_400)); let (mut broadcast, catalog) = catalog(); let reserved = catalog.reserve(); let mut stream = catalog diff --git a/rs/moq-mux/src/catalog/producer.rs b/rs/moq-mux/src/catalog/producer.rs index c14ce43369e..cabfdc43628 100644 --- a/rs/moq-mux/src/catalog/producer.rs +++ b/rs/moq-mux/src/catalog/producer.rs @@ -583,7 +583,7 @@ impl Producer { &mut self, timebase: &std::sync::OnceLock, pts: moq_net::Timestamp, - wall: Option, + wall: Option, ) -> crate::Result { let mut guard = self.modify()?; // Another clone of the timebase may have anchored first; the lock orders them. A placement @@ -2059,10 +2059,10 @@ mod test { #[test] fn sibling_broadcasts_share_a_clock_and_capture_time() { - use std::time::{Duration, SystemTime}; + use std::time::Duration; let captured = moq_clock::now(); - let wall = SystemTime::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS + 60_000); + let wall = moq_clock::Wall::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS + 60_000); let clock = crate::Clock::at(captured, wall).unwrap(); let (origin, _driver) = moq_net::origin::Producer::new(Default::default()); let mut front = origin.create_broadcast("robot/front.hang").unwrap(); @@ -2117,11 +2117,11 @@ mod test { /// landing at the clock's reading on arrival, and the advertised mapping never moves. #[moq_clock::test] async fn with_clock_shifts_the_first_importer() { - use std::time::{Duration, SystemTime}; + use std::time::Duration; moq_clock::sleep(Duration::from_secs(5)).await; let mut broadcast = moq_net::broadcast::Info::new().produce(); - let wall = SystemTime::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS + 60_000); + let wall = moq_clock::Wall::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS + 60_000); let start = moq_clock::now() - 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(); @@ -2143,7 +2143,7 @@ mod test { /// verbatim; its clones share that, while another timebase offsets onto the placed clock. #[test] fn the_first_input_places_the_clock() { - use std::time::{Duration, SystemTime}; + use std::time::Duration; let mut broadcast = moq_net::broadcast::Info::new().produce(); let catalog = Producer::new(&mut broadcast, Config::default()).unwrap(); @@ -2157,11 +2157,9 @@ mod test { ); let clock = catalog.clock(); assert_eq!(catalog.snapshot().clock, clock.wall(), "the anchor is advertised"); - let drift = clock - .wall_clock(first) - .unwrap() - .duration_since(SystemTime::now()) - .unwrap_or_else(|err| err.duration()); + let actual = clock.wall_clock(first).unwrap(); + let now = moq_clock::wall(); + let drift = actual.max(now).saturating_duration_since(actual.min(now)); assert!(drift < Duration::from_secs(1), "the first timestamp is live on arrival"); // Its clones keep the offset, whatever they see first. @@ -2229,9 +2227,9 @@ mod test { /// or one already fixed alike, so two importers of one stream publish identical timestamps. #[test] fn a_placed_input_lands_where_it_says() { - use std::time::{Duration, SystemTime}; + use std::time::Duration; - let wall = SystemTime::now() - Duration::from_secs(2); + let wall = moq_clock::Wall::now() - Duration::from_secs(2); let pts = moq_net::Timestamp::from_micros(100_000_000).unwrap(); let later = moq_net::Timestamp::from_micros(101_000_000).unwrap(); @@ -2265,9 +2263,9 @@ mod test { /// the placed clock. #[test] fn a_placement_alone_publishes_nothing() { - use std::time::{Duration, SystemTime}; + use std::time::Duration; - let wall = SystemTime::now() - Duration::from_secs(2); + let wall = moq_clock::Wall::now() - Duration::from_secs(2); let mut broadcast = moq_net::broadcast::Info::new().produce(); let mut catalog = Producer::new(&mut broadcast, Config::default()).unwrap(); catalog.timebase().place(moq_net::Timestamp::ZERO, wall).unwrap(); @@ -2289,11 +2287,11 @@ mod test { /// Fake this thread's host now a day past the moq epoch, returning a root `clock` an hour /// before it in `scale` units. fn an_hour_ago(scale: moq_net::Timescale) -> hang::catalog::Clock { - use std::time::{Duration, SystemTime}; + use std::time::Duration; let now = Duration::from_secs(86_400); crate::clock::fake_host_wall( - SystemTime::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS) + now, + moq_clock::Wall::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS) + now, ); let zero = moq_net::Timestamp::from_secs(now.as_secs() - 3600).unwrap(); hang::catalog::Clock::new(zero.convert(scale).unwrap()).unwrap() @@ -2334,7 +2332,7 @@ mod test { /// never replaced by a fresh clock; one that disagrees with `with_clock` is refused. #[test] fn a_seeded_root_clock_is_adopted() { - use std::time::{Duration, SystemTime}; + use std::time::Duration; let input = an_hour_ago(moq_net::Timescale::MICRO); let mut seed = Catalog::<()>::default(); @@ -2346,12 +2344,12 @@ mod test { // The same mapping from `with_clock` agrees in any units, without reading the host's wall // clock, which may be unset. - let zero = SystemTime::UNIX_EPOCH + let zero = moq_clock::Wall::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS) + Duration::from_micros(input.wall.as_micros() as u64); let fixed = crate::Clock::at(moq_clock::now(), zero).unwrap(); seed.clock = Some(an_hour_ago(moq_net::Timescale::MILLI)); - crate::clock::fake_host_wall(SystemTime::UNIX_EPOCH + Duration::from_secs(86_400)); + crate::clock::fake_host_wall(moq_clock::Wall::UNIX_EPOCH + Duration::from_secs(86_400)); let config = Config::default().with_catalog(seed.clone()).with_clock(fixed); let mut broadcast = moq_net::broadcast::Info::new().produce(); let mut catalog = Producer::new(&mut broadcast, config).unwrap(); @@ -2428,14 +2426,14 @@ mod test { /// wall time is refused, whether it would place the clock or offset onto it. #[test] fn an_unset_host_clock_publishes_without_a_wall() { - use std::time::{Duration, SystemTime}; + use std::time::Duration; - crate::clock::fake_host_wall(SystemTime::UNIX_EPOCH + Duration::from_secs(86_400)); + crate::clock::fake_host_wall(moq_clock::Wall::UNIX_EPOCH + Duration::from_secs(86_400)); let mut broadcast = moq_net::broadcast::Info::new().produce(); let catalog = Producer::new(&mut broadcast, Config::default()).unwrap(); assert_eq!(catalog.snapshot().clock, None); - let wall = SystemTime::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS); + let wall = moq_clock::Wall::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS); let pts = moq_net::Timestamp::from_micros(1_000_000).unwrap(); assert!(matches!( catalog.timebase().place(pts, wall), diff --git a/rs/moq-mux/src/catalog/timebase.rs b/rs/moq-mux/src/catalog/timebase.rs index 9cdcfe51d26..36640f52750 100644 --- a/rs/moq-mux/src/catalog/timebase.rs +++ b/rs/moq-mux/src/catalog/timebase.rs @@ -44,7 +44,7 @@ impl Timebase { /// A placement alone publishes nothing: the clock goes out with the catalog's first track. /// Refused once this timebase has an offset, and when the host's wall clock was unset, leaving no /// wall to place it on. - pub fn place(&self, pts: moq_net::Timestamp, wall: std::time::SystemTime) -> crate::Result<()> { + pub fn place(&self, pts: moq_net::Timestamp, wall: moq_clock::Wall) -> crate::Result<()> { self.catalog.clone().anchor(&self.offset, pts, Some(wall))?; Ok(()) } diff --git a/rs/moq-mux/src/clock.rs b/rs/moq-mux/src/clock.rs index 546a583d189..0bdf0679d49 100644 --- a/rs/moq-mux/src/clock.rs +++ b/rs/moq-mux/src/clock.rs @@ -17,23 +17,21 @@ //! anything fixes the clock places the mapping so that frame is live on arrival; any other shifts //! onto the clock (see [`catalog::Timebase`](crate::catalog::Timebase)). -use std::time::{Duration, SystemTime}; +use moq_clock::Wall; +use std::time::Duration; use hang::catalog::{MAX_SAFE_INTEGER, MOQ_EPOCH_UNIX_MILLIS}; use moq_clock::Instant; /// Microseconds from the moq epoch (2020) to `wall`, negative before it. -fn moq_micros(wall: SystemTime) -> i128 { +fn moq_micros(wall: Wall) -> i128 { let moq_epoch = MOQ_EPOCH_UNIX_MILLIS as i128 * 1000; - match wall.duration_since(SystemTime::UNIX_EPOCH) { - Ok(after) => after.as_micros() as i128 - moq_epoch, - Err(before) => -(before.duration().as_micros() as i128) - moq_epoch, - } + wall.saturating_duration_since(Wall::UNIX_EPOCH).as_micros() as i128 - moq_epoch } /// The host's wall clock, or `None` while it reads before the moq epoch (2020): unset. -pub(crate) fn host_wall() -> Option { - let now = SystemTime::from(moq_clock::wall()); +pub(crate) fn host_wall() -> Option { + let now = moq_clock::wall(); #[cfg(test)] let now = HOST_WALL.get().unwrap_or(now); (moq_micros(now) >= 0).then_some(now) @@ -42,17 +40,17 @@ pub(crate) fn host_wall() -> Option { #[cfg(test)] thread_local! { /// What [`host_wall`] reads on this thread instead of the system clock. - static HOST_WALL: std::cell::Cell> = const { std::cell::Cell::new(None) }; + static HOST_WALL: std::cell::Cell> = const { std::cell::Cell::new(None) }; } /// Make this thread's host wall clock read `now`, so a test can fake one that was never set. #[cfg(test)] -pub(crate) fn fake_host_wall(now: SystemTime) { +pub(crate) fn fake_host_wall(now: Wall) { HOST_WALL.set(Some(now)); } /// The catalog clock for PTS zero at `wall`. -fn wall_clock(wall: SystemTime) -> crate::Result { +fn wall_clock(wall: Wall) -> crate::Result { // A time before 2020 cannot be named on the wire; refuse it rather than advertise 2020. let micros = moq_micros(wall); if micros < 0 { @@ -110,7 +108,7 @@ impl Clock { /// /// The deterministic constructor: synthetic sources and fixtures pin both ends instead of /// sampling. Refuses an unrepresentable wall. - pub fn at(epoch: Instant, wall: SystemTime) -> crate::Result { + pub fn at(epoch: Instant, wall: Wall) -> crate::Result { Ok(Self { instant: epoch, reading: 0, @@ -147,7 +145,7 @@ impl Clock { /// /// Refuses a mapping whose PTS zero lands before the moq epoch (2020) or after now, and a host /// whose wall clock is unset, which has no now to place it against. - pub(crate) fn placed(pts: Duration, wall: SystemTime) -> crate::Result { + pub(crate) fn placed(pts: Duration, wall: Wall) -> crate::Result { let unmappable = |why: &str| crate::Error::UnmappableTimestamp(format!("{pts:?} at {wall:?} {why}")); let zero = wall .checked_sub(pts) @@ -200,7 +198,7 @@ impl Clock { /// What this clock reads at `wall`, in microseconds: negative before PTS zero. /// /// Pure in the stored mapping, like [`wall_clock`](Self::wall_clock), and refused without one. - pub(crate) fn reading(&self, wall: SystemTime) -> crate::Result { + pub(crate) fn reading(&self, wall: Wall) -> crate::Result { Ok(moq_micros(wall) - self.mapping()?.wall.as_micros() as i128) } @@ -251,7 +249,7 @@ impl Clock { /// Pure in the stored mapping: a system-clock adjustment after construction changes nothing. /// Exact down to the nanosecond; an instant finer than that (a 90 kHz tick) is floored. /// Refuses an unrepresentable result, and a clock without a mapping. - pub fn wall_clock(&self, pts: moq_net::Timestamp) -> crate::Result { + pub fn wall_clock(&self, pts: moq_net::Timestamp) -> crate::Result { Ok(self.mapping()?.wall_clock(pts)?) } } @@ -270,8 +268,8 @@ mod tests { moq_clock::now() } - fn moq_epoch() -> SystemTime { - SystemTime::UNIX_EPOCH + Duration::from_millis(MOQ_EPOCH_UNIX_MILLIS) + fn moq_epoch() -> Wall { + Wall::UNIX_EPOCH + Duration::from_millis(MOQ_EPOCH_UNIX_MILLIS) } fn us(v: u64) -> moq_net::Timestamp { @@ -320,7 +318,7 @@ mod tests { assert_eq!(clock.wall(), wall, "a wall correction does not retime archived media"); assert_eq!( Clock::new().wall(), - wall_clock(SystemTime::from(stepped) - Clock::LEAD).ok(), + wall_clock(stepped - Clock::LEAD).ok(), "a new mapping samples the corrected wall" ); @@ -352,11 +350,11 @@ mod tests { fn unrepresentable_walls_are_refused() { // One micro past the JSON-safe integer range: browsers would read a different number. let past_safe = MOQ_EPOCH_UNIX_MILLIS * 1000 + MAX_SAFE_INTEGER + 1; - let far = SystemTime::UNIX_EPOCH + Duration::from_micros(past_safe); + let far = Wall::UNIX_EPOCH + Duration::from_micros(past_safe); assert!(Clock::at(epoch(), far).is_err()); // Before 2020 cannot be named on the wire; saturating to the epoch would lie. - assert!(Clock::at(epoch(), SystemTime::UNIX_EPOCH).is_err()); + assert!(Clock::at(epoch(), Wall::UNIX_EPOCH).is_err()); assert!(Clock::at(epoch(), moq_epoch() - Duration::from_micros(1)).is_err()); assert_eq!(Clock::at(epoch(), moq_epoch()).unwrap().wall().unwrap().wall.value(), 0); } @@ -368,9 +366,8 @@ mod tests { // and the mapping still names the current wall time. assert!(clock.now().as_micros() >= Clock::LEAD.as_micros()); let now = clock.wall_clock(clock.now()).unwrap(); - let drift = now - .duration_since(SystemTime::now()) - .unwrap_or_else(|err| err.duration()); + let host = moq_clock::wall(); + let drift = now.max(host).saturating_duration_since(now.min(host)); assert!(drift < Duration::from_secs(1), "wall + now is the current wall time"); } @@ -382,11 +379,9 @@ mod tests { let clock = Clock::arrival(since).unwrap(); let now = clock.now(); assert!(now.as_micros() >= since.as_micros()); - let drift = clock - .wall_clock(now) - .unwrap() - .duration_since(moq_clock::wall().into()) - .unwrap_or_else(|err| err.duration()); + let actual = clock.wall_clock(now).unwrap(); + let host = moq_clock::wall(); + let drift = actual.max(host).saturating_duration_since(actual.min(host)); 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. @@ -404,7 +399,7 @@ mod tests { /// mapping, and refuses whatever needs one rather than invent it. #[test] fn an_unset_host_clock_has_no_wall() { - fake_host_wall(SystemTime::UNIX_EPOCH + Duration::from_secs(86_400)); + fake_host_wall(Wall::UNIX_EPOCH + Duration::from_secs(86_400)); let clock = Clock::new(); assert_eq!(clock.wall(), None); diff --git a/rs/moq-mux/src/container/flv/import_test.rs b/rs/moq-mux/src/container/flv/import_test.rs index acf4677e8fc..1ab72a52c0c 100644 --- a/rs/moq-mux/src/container/flv/import_test.rs +++ b/rs/moq-mux/src/container/flv/import_test.rs @@ -741,7 +741,7 @@ struct Imported { video: String, /// The root clock the catalog advertised. clock: hang::catalog::Clock, - arrival: std::ops::RangeInclusive, + arrival: std::ops::RangeInclusive, /// Why a chunk was refused, if one was. refused: Option, } @@ -754,7 +754,7 @@ async fn import(chunks: &[Vec]) -> Imported { let catalog = crate::catalog::Producer::new(&mut broadcast, Default::default()).unwrap(); let mut importer = Import::new(broadcast, catalog.reserve()); - let before = std::time::SystemTime::now(); + let before = moq_clock::wall(); let mut after = before; let mut refused = None; for (i, chunk) in chunks.iter().enumerate() { @@ -763,7 +763,7 @@ async fn import(chunks: &[Vec]) -> Imported { break; } if i == 0 { - after = std::time::SystemTime::now(); + after = moq_clock::wall(); } } importer.finish().unwrap(); diff --git a/rs/moq-mux/src/container/fmp4/import_test.rs b/rs/moq-mux/src/container/fmp4/import_test.rs index a6d60d56d33..e9193feac3a 100644 --- a/rs/moq-mux/src/container/fmp4/import_test.rs +++ b/rs/moq-mux/src/container/fmp4/import_test.rs @@ -1964,7 +1964,7 @@ struct Imported { video: String, /// The root clock the catalog advertised. clock: hang::catalog::Clock, - arrival: std::ops::RangeInclusive, + arrival: std::ops::RangeInclusive, /// The first record the video timeline published, the index an archive replays from. record: moq_net::Timestamp, /// Why a chunk was refused, if one was. @@ -1986,7 +1986,7 @@ async fn import_session(chunks: &[Vec]) -> Imported { let section = snapshot.archive.clone().expect("the import advertises its timelines"); let mut timeline = subscribe(&consumer, §ion, &video).await; - let before = std::time::SystemTime::now(); + let before = moq_clock::wall(); let mut after = before; let mut refused = None; for (i, chunk) in chunks.iter().enumerate() { @@ -1995,7 +1995,7 @@ async fn import_session(chunks: &[Vec]) -> Imported { break; } if i == 0 { - after = std::time::SystemTime::now(); + after = moq_clock::wall(); } } fmp4.finish().unwrap(); @@ -2863,7 +2863,7 @@ async fn ttml_samples_become_timed_text_with_source_metadata() { /// The source joins a catalog clock another input already fixed, so its TTML times move with it. #[tokio::test(start_paused = true)] async fn ttml_follows_a_shifted_source_clock() { - let wall = std::time::SystemTime::now(); + let wall = moq_clock::wall(); let mut broadcast = moq_net::broadcast::Info::new().produce(); let consumer = broadcast.consume(); let catalog = crate::catalog::Producer::new(&mut broadcast, Default::default()).unwrap(); diff --git a/rs/moq-mux/src/container/mkv/import_test.rs b/rs/moq-mux/src/container/mkv/import_test.rs index dfd347c8784..ab26dfabdbc 100644 --- a/rs/moq-mux/src/container/mkv/import_test.rs +++ b/rs/moq-mux/src/container/mkv/import_test.rs @@ -996,7 +996,7 @@ struct Imported { published: std::collections::BTreeMap>, /// The root clock the catalog advertised. clock: hang::catalog::Clock, - arrival: std::ops::RangeInclusive, + arrival: std::ops::RangeInclusive, /// Why a chunk was refused, if one was. refused: Option, } @@ -1009,7 +1009,7 @@ async fn import_chunked(data: &[u8], chunk: usize) -> Imported { let catalog = crate::catalog::Producer::new(&mut broadcast, Default::default()).unwrap(); let mut mkv = crate::container::mkv::Import::new(broadcast, catalog.reserve()); - let before = std::time::SystemTime::now(); + let before = moq_clock::wall(); let mut refused = None; for piece in data.chunks(chunk) { if let Err(err) = mkv.decode(piece) { @@ -1017,7 +1017,7 @@ async fn import_chunked(data: &[u8], chunk: usize) -> Imported { break; } } - let after = std::time::SystemTime::now(); + let after = moq_clock::wall(); mkv.finish().unwrap(); let snapshot = catalog.snapshot(); diff --git a/rs/moq-mux/src/container/ts/export_test.rs b/rs/moq-mux/src/container/ts/export_test.rs index d0a66438dbd..f521ff8a6f3 100644 --- a/rs/moq-mux/src/container/ts/export_test.rs +++ b/rs/moq-mux/src/container/ts/export_test.rs @@ -8308,8 +8308,7 @@ async fn the_same_instance_continues_after_a_drop() { /// A returning route serves the same publisher's catalog and monotonically numbered groups. #[tokio::test(start_paused = true)] async fn a_return_keeps_catalog_and_group_history() { - let wall = - std::time::SystemTime::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS + 86_400_000); + let wall = moq_clock::Wall::UNIX_EPOCH + Duration::from_millis(hang::catalog::MOQ_EPOCH_UNIX_MILLIS + 86_400_000); crate::clock::fake_host_wall(wall); let start = tokio::time::Instant::now(); let origin = crate::source::produce_origin(); diff --git a/rs/moq-mux/src/container/ts/import.rs b/rs/moq-mux/src/container/ts/import.rs index a22bf073ef8..3cde3e3d6c5 100644 --- a/rs/moq-mux/src/container/ts/import.rs +++ b/rs/moq-mux/src/container/ts/import.rs @@ -5097,7 +5097,7 @@ pub(super) mod test { if anchored { // The shift then depends on the wall clock, so only its consistency is checked. let first = Timestamp::from_scale(picture(0), 90_000).unwrap(); - timebase.place(first, std::time::SystemTime::now()).unwrap(); + timebase.place(first, moq_clock::wall()).unwrap(); } let mut import = super::Import::new(broadcast, timebase.reserve()); diff --git a/rs/moq-mux/src/container/ts/import_test.rs b/rs/moq-mux/src/container/ts/import_test.rs index 7c67921646b..6499c891c09 100644 --- a/rs/moq-mux/src/container/ts/import_test.rs +++ b/rs/moq-mux/src/container/ts/import_test.rs @@ -703,7 +703,7 @@ struct Imported { published: std::collections::BTreeMap>, /// The root clock the catalog advertised. clock: hang::catalog::Clock, - arrival: std::ops::RangeInclusive, + arrival: std::ops::RangeInclusive, } /// Import `data` on a catalog with the default clock. @@ -713,9 +713,9 @@ async fn import_stream(data: &[u8]) -> Imported { let catalog = crate::catalog::Producer::new(&mut broadcast, Default::default()).unwrap(); let mut import = crate::container::ts::Import::new(broadcast, catalog.reserve()); - let before = std::time::SystemTime::now(); + let before = moq_clock::wall(); import.decode(data).unwrap(); - let after = std::time::SystemTime::now(); + let after = moq_clock::wall(); import.finish().unwrap(); let snapshot = catalog.snapshot(); diff --git a/rs/moq-mux/src/container/ts/programs.rs b/rs/moq-mux/src/container/ts/programs.rs index e48dd5780ce..ee01205b52e 100644 --- a/rs/moq-mux/src/container/ts/programs.rs +++ b/rs/moq-mux/src/container/ts/programs.rs @@ -477,7 +477,7 @@ mod test { let mut programs = Programs::new(origin.clone(), "event.hang", catalog::Config::default()); let input = two_programs(); - let before = std::time::SystemTime::now(); + let before = moq_clock::wall(); programs.decode(&input[..100]).unwrap(); assert!( programs.programs.is_empty(), @@ -485,7 +485,7 @@ mod test { ); programs.decode(&input[100..]).unwrap(); let _finished = programs.finish().unwrap(); - let after = std::time::SystemTime::now(); + let after = moq_clock::wall(); for (path, fills) in [("event/1.hang", [0xAA, 0xBB]), ("event/2.hang", [0xCC, 0xDD])] { let consumer = origin.consume().request_broadcast(path, None).await.unwrap(); diff --git a/rs/moq-mux/src/stats.rs b/rs/moq-mux/src/stats.rs index e626fc18732..a46724ace88 100644 --- a/rs/moq-mux/src/stats.rs +++ b/rs/moq-mux/src/stats.rs @@ -5,10 +5,11 @@ //! the catalog [`Producer`](crate::catalog::Producer) for what a publisher writes, the export //! [`Source`](crate::Source) for what a viewer reads. +use moq_clock::Wall; use std::collections::BTreeMap; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; use std::sync::{Arc, Mutex, PoisonError}; -use std::time::{Duration, UNIX_EPOCH}; +use std::time::Duration; /// What one published track has written. #[derive(Default)] @@ -56,7 +57,7 @@ impl Received { return; }; let wall = wall - .duration_since(UNIX_EPOCH) + .checked_duration_since(Wall::UNIX_EPOCH) .map_or(0, |since| u64::try_from(since.as_millis()).unwrap_or(0)); let micros = u64::try_from(timestamp.as_micros()).unwrap_or(u64::MAX); self.timestamp.store(micros, Relaxed); @@ -73,7 +74,7 @@ impl Received { if wall != 0 && let Ok(timestamp) = moq_net::Timestamp::from_micros(self.timestamp.load(Relaxed)) { - let wall = UNIX_EPOCH + Duration::from_millis(wall); + let wall = Wall::UNIX_EPOCH + Duration::from_millis(wall); report.arrival = Some(hang::echo::Arrival::new(timestamp, wall)); } report @@ -244,7 +245,7 @@ mod tests { let track = registry.track("hd"); assert_eq!(registry.received()["hd"].arrival, None); - let wall = UNIX_EPOCH + Duration::from_secs(1_800_000_000); + let wall = Wall::UNIX_EPOCH + Duration::from_secs(1_800_000_000); crate::clock::fake_host_wall(wall); track.frame(moq_net::Timestamp::from_millis(40).unwrap(), 100); track.frame(moq_net::Timestamp::from_millis(80).unwrap(), 50); @@ -260,7 +261,7 @@ mod tests { fn an_unset_host_clock_records_no_arrival() { let registry = Registry::::default(); let track = registry.track("hd"); - crate::clock::fake_host_wall(UNIX_EPOCH + Duration::from_secs(86_400)); + crate::clock::fake_host_wall(Wall::UNIX_EPOCH + Duration::from_secs(86_400)); track.frame(moq_net::Timestamp::from_millis(40).unwrap(), 100); let report = ®istry.received()["hd"]; assert_eq!((report.frames, report.bytes), (1, 100)); diff --git a/rs/moq-net/clippy.toml b/rs/moq-net/clippy.toml index 892532bf144..9460b0fd5c8 100644 --- a/rs/moq-net/clippy.toml +++ b/rs/moq-net/clippy.toml @@ -7,3 +7,5 @@ disallowed-methods = [ { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, ] + +disallowed-types = [{ path = "std::time::SystemTime", reason = "use moq_clock::Wall" }] diff --git a/rs/moq-net/src/epoch.rs b/rs/moq-net/src/epoch.rs index 12e3eaf941f..f398e5d5c91 100644 --- a/rs/moq-net/src/epoch.rs +++ b/rs/moq-net/src/epoch.rs @@ -1,7 +1,8 @@ +use moq_clock::{OutOfRange, Wall}; use std::fmt; use std::str::FromStr; use std::sync::Arc; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use std::time::Duration; /// One publisher instance's identity, the lowercase hyphenated text of a UUIDv7. #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -24,12 +25,14 @@ impl Epoch { &self.0 } - /// The wall-clock time encoded in the UUID, with millisecond precision. - pub fn time(&self) -> SystemTime { + /// The UUID's wall time in milliseconds, or an error outside Wall's range. + pub fn time(&self) -> Result { // Parsing enforces the canonical UUID form, whose first 48 bits are Unix milliseconds. let millis = u64::from_str_radix(&self.0[..8], 16).unwrap() << 16 | u64::from_str_radix(&self.0[9..13], 16).unwrap(); - UNIX_EPOCH + Duration::from_millis(millis) + Wall::UNIX_EPOCH + .checked_add(Duration::from_millis(millis)) + .ok_or(OutOfRange) } } @@ -101,10 +104,11 @@ mod tests { let text = row["text"].as_str().unwrap(); let epoch: Epoch = text.parse().unwrap(); assert_eq!(epoch.as_str(), text); - assert_eq!( - epoch.time().duration_since(UNIX_EPOCH).unwrap().as_millis(), - row["unix_ms"].as_u64().unwrap() as u128 - ); + let millis = row["unix_ms"].as_u64().unwrap(); + match Wall::UNIX_EPOCH.checked_add(Duration::from_millis(millis)) { + Some(expected) => assert_eq!(epoch.time().unwrap(), expected), + None => assert_eq!(epoch.time(), Err(OutOfRange)), + } } for row in vectors["invalid"].as_array().unwrap() { assert!(row.as_str().unwrap().parse::().is_err(), "{row}"); diff --git a/rs/moq-quic/Cargo.toml b/rs/moq-quic/Cargo.toml index 230d6a1d7fc..20a0b70444e 100644 --- a/rs/moq-quic/Cargo.toml +++ b/rs/moq-quic/Cargo.toml @@ -85,7 +85,6 @@ getrandom = { version = "0.4", default-features = false, features = ["wasm_js"] ring = { version = "0.17", features = ["wasm32_unknown_unknown_js"], optional = true } # only added as dependency to enforce the `web` feature for this target rustls-pki-types = { version = "1.7", features = ["web"] } -web-time = "1" [dev-dependencies] arbitrary = { version = "1.5", features = ["derive"] } diff --git a/rs/moq-quic/README.md b/rs/moq-quic/README.md index 3e02c71e804..8a1f26c2188 100644 --- a/rs/moq-quic/README.md +++ b/rs/moq-quic/README.md @@ -81,7 +81,7 @@ Changes on top of the upstream commit, besides the renames: - **Probes on the peer heard again**: a 1-RTT probe that times out with nothing heard from the peer since the packet it probes for went out lets the next packet heard send the next probe at once, rather than leave a path back from an outage idle for the rest of the backoff, which still doubles with each probe (RFC 9002 section 6.2.1), up to 2^16 times its base. A packet acknowledging anything new already resets the backoff; this covers one that does not, as after an outage that began with everything acknowledged. A peer heard while the probes still go unanswered says nothing of their path, so it leaves the backoff alone. Not offered upstream yet. - `TransportConfig::handshake_idle_timeout` (default 10s, as msquic's `HandshakeIdleTimeoutMs`) governs the idle timer until the handshake completes, and the negotiated idle timeout takes over once established. A 2s idle timeout otherwise expires 3x the initial PTO in, just before the second Initial probe, leaving a client two flights. A server also drops an Initial left waiting for `accept` past it, and a deadline too far out to represent never fires instead of panicking. Also [moq-dev/noq#34](https://github.com/moq-dev/noq/pull/34), whose third change (the handshake idle timeout picks noq's idle-based PTO interval cap) has nothing to apply to here, since quinn's PTO backoff has no such cap. quinn's `handshake_timeout` test in its async layer expects the handshake to end at the idle timeout, so the driver's copy sets both timeouts. -- **Instants on [moq-clock](../moq-clock)**: the crate's `Instant` is `moq_clock::Instant`, so one clock steps every timer, tokio's paused clock and the simulator included. qlog stamps events relative to `QlogConfig::start_time` on that clock rather than the streamer's own `std::time::Instant`. +- **Time on [moq-clock](../moq-clock)**: the crate's `Instant` is `moq_clock::Instant`, and `TimeSource` / token logs use `moq_clock::Wall` for portable 1970-2554 wall times, so one clock steps every timer, tokio's paused clock and the simulator included. qlog stamps events relative to `QlogConfig::start_time` on that clock rather than the streamer's own `std::time::Instant`. - **Send groups** (`streams/schedule.rs`, `Connection::send_groups`): streams outside every group go first, in quinn's order; groups are served strictly by priority, with equal priorities sharing bytes by deficit round robin. A stream's priority is an `i64` ordering it only within its group, and `Streams::open` takes a `SendOptions { group, priority }` to start it there, like W3C WebTransport's send options. The schedule also has scheduling domains that share bytes the same way, crate-private until a consumer needs them. This replaces quinn's single pending-stream heap, so a cherry-pick touching `PendingStreamsQueue` has to be redone against the schedule. moq-tokio's `quic::driver` and moq-uring's driver wrap a group in a shared `SendGroup` handle that closes on drop. - **Scheduled datagrams** (`Datagrams::send`): a datagram is queued by its `SendOptions`, in a send group (or ungrouped) at an `i64` priority, and scheduled with the group's streams, winning a tie with a stream of equal priority and spending the group's byte credit, instead of quinn's datagram-first FIFO in `populate_packet`. Sending never blocks: `datagram_send_buffer_size` is shared, and an overflow evicts the oldest datagram of the lowest-priority group in the domain holding the most datagram bytes. `SendDatagramError::Blocked` and `Event::DatagramsUnblocked` are gone, and a cherry-pick touching the `// DATAGRAM` loop has to be redone against `StreamsState::write_frames`. - **Sharded connection IDs** (`RandomConnectionIdGenerator::set_shard`): every CID names shard `index` of a `count`-endpoint group in its first byte, modulo `count`, and sets a marker in its fourth byte, so a `SO_REUSEPORT` steering filter delivers a packet to the endpoint that issued its CID. `validate` refuses a CID without this shard's prefix and marker, so a misrouted packet is dropped instead of answered with a stateless reset. Not offered upstream; it serves moq-sock's per-core sharding. diff --git a/rs/moq-quic/clippy.toml b/rs/moq-quic/clippy.toml index f3f8720ac3f..d5a7b48f913 100644 --- a/rs/moq-quic/clippy.toml +++ b/rs/moq-quic/clippy.toml @@ -1,5 +1,4 @@ # Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. -# `SystemTime` stays an allowed type until its wall times move to `moq_clock::Wall`. disallowed-methods = [ { path = "std::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, { path = "std::time::Instant::elapsed", reason = "read the ambient clock: moq_clock::Instant::elapsed()" }, @@ -16,6 +15,7 @@ disallowed-methods = [ ] disallowed-types = [ + { path = "std::time::SystemTime", reason = "use moq_clock::Wall" }, { path = "std::time::Instant", reason = "use moq_clock::Instant" }, { path = "tokio::time::Instant", reason = "use moq_clock::Instant" }, { path = "tokio::time::Sleep", reason = "use moq_clock::Sleep" }, diff --git a/rs/moq-quic/src/bloom_token_log.rs b/rs/moq-quic/src/bloom_token_log.rs index a02110397e6..0dc9db876d1 100644 --- a/rs/moq-quic/src/bloom_token_log.rs +++ b/rs/moq-quic/src/bloom_token_log.rs @@ -10,7 +10,7 @@ use fastbloom::BloomFilter; use rustc_hash::FxBuildHasher; use tracing::{trace, warn}; -use crate::{Duration, SystemTime, TokenLog, TokenReuseError, UNIX_EPOCH}; +use crate::{Duration, TokenLog, TokenReuseError, UNIX_EPOCH, Wall}; /// Bloom filter-based [`TokenLog`] /// @@ -57,7 +57,7 @@ impl TokenLog for BloomTokenLog { fn check_and_insert( &self, nonce: u128, - issued: SystemTime, + issued: Wall, lifetime: Duration, ) -> Result<(), TokenReuseError> { trace!(%nonce, "check_and_insert"); @@ -71,9 +71,9 @@ impl TokenLog for BloomTokenLog { let state = &mut *guard; // calculate how many periods past period 1 the token expires - let expires_at = issued + lifetime; - let Ok(periods_forward) = expires_at - .duration_since(state.period_1_start) + let expires_at = issued.checked_add(lifetime).ok_or(TokenReuseError)?; + let Some(periods_forward) = expires_at + .checked_duration_since(state.period_1_start) .map(|duration| duration.as_nanos() / lifetime.as_nanos()) else { // shouldn't happen unless time travels backwards or lifetime changes or the current @@ -89,7 +89,7 @@ impl TokenLog for BloomTokenLog { 2 => { // turn over filter 1 state.filter_1 = take(&mut state.filter_2); - state.period_1_start += lifetime; + state.period_1_start = state.period_1_start + lifetime; &mut state.filter_2 } _ => { @@ -134,7 +134,7 @@ struct State { config: FilterConfig, // filter_1 covers tokens that expire in the period starting at period_1_start and extending // lifetime after. filter_2 covers tokens for the next lifetime after that. - period_1_start: SystemTime, + period_1_start: Wall, filter_1: Filter, filter_2: Filter, } @@ -253,10 +253,6 @@ const DEFAULT_MAX_BYTES: usize = 10 << 20; const DEFAULT_EXPECTED_HITS: u64 = 1_000_000; #[cfg(test)] -#[expect( - clippy::disallowed_methods, - reason = "tests read the host clock directly" -)] mod test { use super::*; use rand::prelude::*; @@ -291,7 +287,7 @@ mod test { let mut rng = new_rng(); let mut log = BloomTokenLog::new_expected_items(800, 200); - let issued = SystemTime::now(); + let issued = Wall::now(); let lifetime = Duration::from_secs(1_000_000); for i in 0..200 { @@ -346,7 +342,7 @@ mod test { fn test_doesnt_panic(log: BloomTokenLog) { let mut rng = new_rng(); - let issued = SystemTime::now(); + let issued = Wall::now(); let lifetime = Duration::from_secs(1_000_000); for _ in 0..200 { diff --git a/rs/moq-quic/src/config/mod.rs b/rs/moq-quic/src/config/mod.rs index 0698325f9fe..1c585e2ea85 100644 --- a/rs/moq-quic/src/config/mod.rs +++ b/rs/moq-quic/src/config/mod.rs @@ -18,8 +18,8 @@ use crate::NoneTokenLog; #[cfg(any(feature = "rustls-aws-lc-rs", feature = "rustls-ring"))] use crate::crypto::rustls::{QuicServerConfig, configured_provider}; use crate::{ - DEFAULT_SUPPORTED_VERSIONS, Duration, MAX_CID_SIZE, RandomConnectionIdGenerator, SystemTime, - TokenLog, TokenMemoryCache, TokenStore, VarInt, VarIntBoundsExceeded, + DEFAULT_SUPPORTED_VERSIONS, Duration, MAX_CID_SIZE, RandomConnectionIdGenerator, TokenLog, + TokenMemoryCache, TokenStore, VarInt, VarIntBoundsExceeded, Wall, cid_generator::{ConnectionIdGenerator, HashedConnectionIdGenerator}, crypto::{self, HandshakeTokenKey, HmacKey}, shared::ConnectionId, @@ -401,7 +401,7 @@ impl ServerConfig { self } - /// Object to get current [`SystemTime`] + /// Object to get current [`Wall`] /// /// This exists to allow system time to be mocked in tests, or wherever else desired. /// @@ -716,12 +716,12 @@ impl From for ConfigError { } } -/// Object to get current [`SystemTime`] +/// Object to get current [`Wall`] /// /// This exists to allow system time to be mocked in tests, or wherever else desired. pub trait TimeSource: Send + Sync { - /// Get [`SystemTime::now()`](SystemTime::now) or the mocked equivalent - fn now(&self) -> SystemTime; + /// Get [`Wall::now()`](Wall::now) or the mocked equivalent + fn now(&self) -> Wall; } /// Default implementation of [`TimeSource`] @@ -730,7 +730,7 @@ pub trait TimeSource: Send + Sync { pub struct StdSystemTime; impl TimeSource for StdSystemTime { - fn now(&self) -> SystemTime { - moq_clock::wall().into() + fn now(&self) -> Wall { + moq_clock::wall() } } diff --git a/rs/moq-quic/src/lib.rs b/rs/moq-quic/src/lib.rs index cedcf328003..87b35184eaf 100644 --- a/rs/moq-quic/src/lib.rs +++ b/rs/moq-quic/src/lib.rs @@ -38,10 +38,6 @@ mod entropy; pub mod fuzz; mod range_set; #[cfg(all(test, any(feature = "rustls-aws-lc-rs", feature = "rustls-ring")))] -#[expect( - clippy::disallowed_methods, - reason = "tests read the host clock directly" -)] mod tests; pub mod transport_parameters; mod varint; @@ -119,11 +115,9 @@ pub use token_memory_cache::TokenMemoryCache; // Deal with time // MoQ's clock, so a caller-driven clock (a test's or the simulator's) reaches the state machine. -pub(crate) use moq_clock::Instant; -#[cfg(not(all(target_family = "wasm", target_os = "unknown")))] -pub(crate) use std::time::{Duration, SystemTime, UNIX_EPOCH}; -#[cfg(all(target_family = "wasm", target_os = "unknown"))] -pub(crate) use web_time::{Duration, SystemTime, UNIX_EPOCH}; +pub(crate) use moq_clock::{Instant, Wall}; +pub(crate) use std::time::Duration; +pub(crate) const UNIX_EPOCH: Wall = Wall::UNIX_EPOCH; /// The QUIC protocol version implemented. pub const DEFAULT_SUPPORTED_VERSIONS: &[u32] = &[ diff --git a/rs/moq-quic/src/tests/token.rs b/rs/moq-quic/src/tests/token.rs index 9037bf437ee..6c979467e35 100644 --- a/rs/moq-quic/src/tests/token.rs +++ b/rs/moq-quic/src/tests/token.rs @@ -435,20 +435,21 @@ fn use_token_expired() { assert_eq!(pair.server.known_cids(), 0); } -pub(super) struct FakeTimeSource(Mutex); +pub(super) struct FakeTimeSource(Mutex); impl FakeTimeSource { pub(super) fn new() -> Self { - Self(Mutex::new(SystemTime::now())) + Self(Mutex::new(Wall::now())) } pub(super) fn advance(&self, dur: Duration) { - *self.0.lock().unwrap() += dur; + let mut time = self.0.lock().unwrap(); + *time = *time + dur; } } impl TimeSource for FakeTimeSource { - fn now(&self) -> SystemTime { + fn now(&self) -> Wall { *self.0.lock().unwrap() } } diff --git a/rs/moq-quic/src/tests/util.rs b/rs/moq-quic/src/tests/util.rs index dfb16aa8b78..2672e74e74c 100644 --- a/rs/moq-quic/src/tests/util.rs +++ b/rs/moq-quic/src/tests/util.rs @@ -992,7 +992,7 @@ impl TokenLog for SimpleTokenLog { fn check_and_insert( &self, nonce: u128, - _issued: SystemTime, + _issued: Wall, _lifetime: Duration, ) -> Result<(), TokenReuseError> { if self.0.lock().unwrap().insert(nonce) { diff --git a/rs/moq-quic/src/token.rs b/rs/moq-quic/src/token.rs index ab58ca28ec7..61a86c58ece 100644 --- a/rs/moq-quic/src/token.rs +++ b/rs/moq-quic/src/token.rs @@ -8,7 +8,7 @@ use bytes::{Buf, BufMut, Bytes}; use rand::{Rng, RngExt}; use crate::{ - Duration, RESET_TOKEN_SIZE, ServerConfig, SystemTime, UNIX_EPOCH, + Duration, RESET_TOKEN_SIZE, ServerConfig, UNIX_EPOCH, Wall, coding::{BufExt, BufMutExt}, crypto::{HandshakeTokenKey, HmacKey}, packet::InitialHeader, @@ -58,7 +58,7 @@ pub trait TokenLog: Send + Sync { fn check_and_insert( &self, nonce: u128, - issued: SystemTime, + issued: Wall, lifetime: Duration, ) -> Result<(), TokenReuseError>; } @@ -70,7 +70,7 @@ pub struct TokenReuseError; pub struct NoneTokenLog; impl TokenLog for NoneTokenLog { - fn check_and_insert(&self, _: u128, _: SystemTime, _: Duration) -> Result<(), TokenReuseError> { + fn check_and_insert(&self, _: u128, _: Wall, _: Duration) -> Result<(), TokenReuseError> { Err(TokenReuseError) } } @@ -152,7 +152,10 @@ impl IncomingToken { if address != remote_address { return Err(InvalidRetryTokenError); } - if issued + server_config.retry_token_lifetime < server_config.time_source.now() { + if issued + .checked_add(server_config.retry_token_lifetime) + .is_none_or(|expires| expires < server_config.time_source.now()) + { return Err(InvalidRetryTokenError); } @@ -166,8 +169,9 @@ impl IncomingToken { if ip != remote_address.ip() { return Ok(unvalidated); } - if issued + server_config.validation_token.lifetime - < server_config.time_source.now() + if issued + .checked_add(server_config.validation_token.lifetime) + .is_none_or(|expires| expires < server_config.time_source.now()) { return Ok(unvalidated); } @@ -288,14 +292,14 @@ pub(crate) enum TokenPayload { /// The destination connection ID set in the very first packet from the client orig_dst_cid: ConnectionId, /// The time at which this token was issued - issued: SystemTime, + issued: Wall, }, /// Token originating from a NEW_TOKEN frame Validation { /// The client's IP address (its port is likely to change between sessions) ip: IpAddr, /// The time at which this token was issued - issued: SystemTime, + issued: Wall, }, } @@ -346,16 +350,12 @@ fn decode_ip(buf: &mut B) -> Option { } } -fn encode_unix_secs(buf: &mut Vec, time: SystemTime) { - buf.write::( - time.duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_secs(), - ); +fn encode_unix_secs(buf: &mut Vec, time: Wall) { + buf.write::(time.saturating_duration_since(UNIX_EPOCH).as_secs()); } -fn decode_unix_secs(buf: &mut B) -> Option { - Some(UNIX_EPOCH + Duration::from_secs(buf.get::().ok()?)) +fn decode_unix_secs(buf: &mut B) -> Option { + UNIX_EPOCH.checked_add(Duration::from_secs(buf.get::().ok()?)) } /// Stateless reset token @@ -429,11 +429,26 @@ mod test { decoded.payload } + #[test] + fn timestamp_decoder_refuses_out_of_range_seconds() { + for seconds in [18_446_744_074, u64::MAX] { + let mut buf = Vec::new(); + buf.write::(seconds); + assert!(decode_unix_secs(&mut buf.as_slice()).is_none()); + } + let mut buf = Vec::new(); + buf.write::(18_446_744_073); + assert_eq!( + decode_unix_secs(&mut buf.as_slice()), + Some(UNIX_EPOCH + Duration::from_secs(18_446_744_073)) + ); + } + #[test] fn retry_token_sanity() { + use crate::Duration; use crate::MAX_CID_SIZE; use crate::cid_generator::{ConnectionIdGenerator, RandomConnectionIdGenerator}; - use crate::{Duration, UNIX_EPOCH}; use std::net::Ipv6Addr; @@ -461,7 +476,7 @@ mod test { #[test] fn validation_token_sanity() { - use crate::{Duration, UNIX_EPOCH}; + use crate::Duration; use std::net::Ipv6Addr; diff --git a/rs/moq-relay/Cargo.toml b/rs/moq-relay/Cargo.toml index 06fe21d1e52..efeda4e0390 100644 --- a/rs/moq-relay/Cargo.toml +++ b/rs/moq-relay/Cargo.toml @@ -69,7 +69,7 @@ humantime = { workspace = true } humantime-serde = { workspace = true } hyper-util = { workspace = true } moq-auth = { workspace = true, features = ["client"] } -moq-clock = { workspace = true } +moq-clock = { workspace = true, features = ["serde"] } moq-net = { workspace = true } # The flow-control limits both QUIC runtimes take, for widening a peer's connection. moq-quic = { workspace = true, optional = true } diff --git a/rs/moq-relay/clippy.toml b/rs/moq-relay/clippy.toml index f3f8720ac3f..d5a7b48f913 100644 --- a/rs/moq-relay/clippy.toml +++ b/rs/moq-relay/clippy.toml @@ -1,5 +1,4 @@ # Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. -# `SystemTime` stays an allowed type until its wall times move to `moq_clock::Wall`. disallowed-methods = [ { path = "std::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, { path = "std::time::Instant::elapsed", reason = "read the ambient clock: moq_clock::Instant::elapsed()" }, @@ -16,6 +15,7 @@ disallowed-methods = [ ] disallowed-types = [ + { path = "std::time::SystemTime", reason = "use moq_clock::Wall" }, { path = "std::time::Instant", reason = "use moq_clock::Instant" }, { path = "tokio::time::Instant", reason = "use moq_clock::Instant" }, { path = "tokio::time::Sleep", reason = "use moq_clock::Sleep" }, diff --git a/rs/moq-relay/src/acme/client.rs b/rs/moq-relay/src/acme/client.rs index 54991e16fa9..5fc3304ef75 100644 --- a/rs/moq-relay/src/acme/client.rs +++ b/rs/moq-relay/src/acme/client.rs @@ -5,12 +5,13 @@ //! that resolver to every TLS listener, so QUIC, HTTPS, and every worker serve //! the same certificate and pick up a renewal on their next handshake. +use moq_clock::Wall; use std::{ io, net::SocketAddr, path::{Path, PathBuf}, sync::Arc, - time::{Duration, SystemTime, UNIX_EPOCH}, + time::Duration, }; use anyhow::Context as _; @@ -265,17 +266,21 @@ struct Failures { impl Failures { /// The failures within [`FAILURE_WINDOW`], oldest first. - fn recent(&self) -> anyhow::Result> { + fn recent(&self) -> anyhow::Result> { let Some(contents) = Cache::read(&self.path)? else { return Ok(Vec::new()); }; - let cutoff = SystemTime::from(moq_clock::wall()) - FAILURE_WINDOW; + let cutoff = moq_clock::wall() + .checked_sub(FAILURE_WINDOW) + .unwrap_or(Wall::UNIX_EPOCH); let mut recent = Vec::new(); for line in String::from_utf8_lossy(&contents).lines() { let secs: u64 = line .parse() .with_context(|| format!("malformed ACME failure record in {}", self.path.display()))?; - let at = UNIX_EPOCH + Duration::from_secs(secs); + let at = Wall::UNIX_EPOCH + .checked_add(Duration::from_secs(secs)) + .context("failure timestamp out of range")?; if at > cutoff { recent.push(at); } @@ -285,12 +290,12 @@ impl Failures { } /// Record a failure now, returning the recent ones including it. - fn record(&self) -> anyhow::Result> { + fn record(&self) -> anyhow::Result> { let mut recent = self.recent()?; - recent.push(SystemTime::from(moq_clock::wall())); + recent.push(moq_clock::wall()); let lines: String = recent .iter() - .map(|at| format!("{}\n", at.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs())) + .map(|at| format!("{}\n", at.saturating_duration_since(Wall::UNIX_EPOCH).as_secs())) .collect(); Cache::write(&self.path, lines.as_bytes())?; Ok(recent) @@ -304,15 +309,17 @@ impl Failures { } /// The startup error once `failed` reaches [`FAILURE_LIMIT`]. - fn refuse(&self, failed: &[SystemTime], domains: &str, addr: SocketAddr, last: Option<&str>) -> anyhow::Error { + fn refuse(&self, failed: &[Wall], domains: &str, addr: SocketAddr, last: Option<&str>) -> anyhow::Error { let retry = failed .first() - .map_or(SystemTime::from(moq_clock::wall()), |oldest| *oldest + FAILURE_WINDOW); + .map_or(Some(moq_clock::wall()), |oldest| oldest.checked_add(FAILURE_WINDOW)) + .map(|retry| humantime::format_rfc3339_seconds(retry.into()).to_string()) + .unwrap_or_else(|| "the supported wall-time range".to_string()); let last = last.map(|last| format!("; last error: {last}")).unwrap_or_default(); anyhow::anyhow!( "ACME validation for {domains} failed {} times in the last hour; stopping before the directory's failed-validation limit locks the hostname out (Let's Encrypt allows 5 failed validations per hostname per hour). Check that each domain resolves to this relay and that TCP port 443 reaches web.https.listen ({addr}), then restart after {} or delete {}{last}", failed.len(), - humantime::format_rfc3339_seconds(retry), + retry, self.path.display(), ) } diff --git a/rs/moq-relay/src/auth.rs b/rs/moq-relay/src/auth.rs index 3801095c5f9..1ac7849d2f6 100644 --- a/rs/moq-relay/src/auth.rs +++ b/rs/moq-relay/src/auth.rs @@ -1117,7 +1117,6 @@ pub(crate) fn peer(identity: &moq_tokio::tls::PeerIdentity) -> Option moq_auth::Patterns { texts.iter().map(|text| text.parse().unwrap()).collect() @@ -1400,7 +1399,7 @@ mod tests { let start = moq_clock::now(); let mut grant = Grant::new(patterns(&["**"]), patterns(&["**"])); - grant.expires = Some(SystemTime::from(moq_clock::wall()) + Duration::from_secs(10)); + grant.expires = Some(moq_clock::wall() + Duration::from_secs(10)); let mut lease = Lease::new("/room", lease::Consumer::fixed(grant)); for _ in 0..9 { assert!(moq_clock::timeout(Duration::from_secs(1), lease.ended()).await.is_err()); @@ -1418,7 +1417,7 @@ mod tests { use std::time::Duration; let mut grant = Grant::new(patterns(&["**"]), patterns(&["**"])); - grant.expires = Some(SystemTime::from(moq_clock::wall()) - Duration::from_secs(1)); + grant.expires = Some(moq_clock::wall() - Duration::from_secs(1)); assert!(matches!(grant.validate(), Err(moq_auth::Error::GrantExpired))); let start = moq_clock::now(); diff --git a/rs/moq-relay/src/auth/refresh.rs b/rs/moq-relay/src/auth/refresh.rs index 1a6b523eea2..99b2fb1bdba 100644 --- a/rs/moq-relay/src/auth/refresh.rs +++ b/rs/moq-relay/src/auth/refresh.rs @@ -465,11 +465,11 @@ fn with_jwt(query: Option<&str>, token: &str) -> String { mod tests { use super::*; use futures::FutureExt; - use std::time::{Duration, SystemTime}; + use std::time::Duration; fn grant(prefix: &str, seconds: u64) -> Grant { let mut grant = Grant::new(prefix.parse::().unwrap(), moq_auth::Patterns::new()); - grant.expires = Some(SystemTime::from(moq_clock::wall()) + Duration::from_secs(seconds)); + grant.expires = Some(moq_clock::wall() + Duration::from_secs(seconds)); grant } diff --git a/rs/moq-relay/src/session.rs b/rs/moq-relay/src/session.rs index c26dba33f17..c6ad0101aa2 100644 --- a/rs/moq-relay/src/session.rs +++ b/rs/moq-relay/src/session.rs @@ -5,17 +5,17 @@ //! a push asks the lease to re-check now, and the server's reply is the verdict. //! One-shot HTTP and LAN peers are not sessions and stay out. +use moq_clock::Wall; use std::collections::HashMap; use std::net::{IpAddr, SocketAddr}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; -use std::time::SystemTime; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use moq_auth::{Pattern, Peer, Request, Role, Transport}; use serde::{Deserialize, Serialize}; -use serde_with::{TimestampSeconds, serde_as}; +use serde_with::serde_as; /// The live sessions on this node, cloned into every connection and the /// internal listener. @@ -26,7 +26,7 @@ pub struct Registry { struct Entry { request: Request, - started: SystemTime, + started: Wall, handle: Handle, } @@ -98,7 +98,7 @@ impl Registry { id.clone(), Entry { request, - started: SystemTime::from(moq_clock::wall()), + started: moq_clock::wall(), handle: handle.clone(), }, ); @@ -439,12 +439,12 @@ pub struct View { /// The verified client certificate, when one was presented. pub tls: Option, /// When the session was admitted, as unix seconds. - #[serde_as(as = "TimestampSeconds")] - pub started: SystemTime, + #[serde_as(as = "moq_clock::serde::UnixSeconds")] + pub started: Wall, } impl View { - fn from_session(request: &Request, started: SystemTime) -> Self { + fn from_session(request: &Request, started: Wall) -> Self { Self { id: request.id.clone(), node: request.node.clone(), diff --git a/rs/moq-relay/tests/integration/auth_lifetime.rs b/rs/moq-relay/tests/integration/auth_lifetime.rs index e30788e2fcb..5020bec9ba0 100644 --- a/rs/moq-relay/tests/integration/auth_lifetime.rs +++ b/rs/moq-relay/tests/integration/auth_lifetime.rs @@ -14,7 +14,7 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex}; -use std::time::{Duration, SystemTime}; +use std::time::Duration; use axum::extract::State; use axum::http::StatusCode; @@ -142,7 +142,7 @@ fn all() -> Patterns { /// Everything under the dialed path, re-checked every second, good for `expires_in`. fn grant(expires_in: Duration) -> Grant { let mut grant = Grant::new(all(), all()); - grant.expires = Some(SystemTime::now() + expires_in); + grant.expires = Some(moq_clock::wall() + expires_in); grant.revalidate = Some(Duration::from_secs(1)); grant } @@ -1416,7 +1416,7 @@ fn manual() -> moq_clock::Installed { /// Everything under the dialed path, until [`EXPIRES`] from now on the ambient clock. fn expiring() -> Grant { let mut grant = Grant::new(all(), all()); - grant.expires = Some(SystemTime::from(moq_clock::wall()) + EXPIRES); + grant.expires = Some(moq_clock::wall() + EXPIRES); grant } @@ -1632,7 +1632,7 @@ async fn quic_and_webtransport_report_distinct_auth_transports() { async fn in_band_tokens_widen_and_withdraw_live_prefixes() { for scheme in ["tcp", "ws"] { let mut initial = Grant::new(all(), "a/**".parse::().unwrap()); - initial.expires = Some(SystemTime::now() + Duration::from_secs(3600)); + initial.expires = Some(moq_clock::wall() + Duration::from_secs(3600)); let script = Script::new(initial); let auth = build_auth(script.spawn().await); let (port, relay) = if scheme == "tcp" { @@ -1682,7 +1682,7 @@ async fn in_band_tokens_widen_and_withdraw_live_prefixes() { .unwrap(); let mut a_sub = a_read.track("video").unwrap().subscribe(None).await.unwrap(); let mut replacement = Grant::new(all(), "b/**".parse::().unwrap()); - replacement.expires = Some(SystemTime::now() + Duration::from_secs(3600)); + replacement.expires = Some(moq_clock::wall() + Duration::from_secs(3600)); script.on_connect(Answer::Grant(replacement)); let token = tokio::time::timeout(TIMEOUT, subscriber.auth().add("replacement")) .await diff --git a/rs/moq-relay/tests/integration/refusals.rs b/rs/moq-relay/tests/integration/refusals.rs index 3dca6fe5cd8..8e301ee79ea 100644 --- a/rs/moq-relay/tests/integration/refusals.rs +++ b/rs/moq-relay/tests/integration/refusals.rs @@ -383,7 +383,7 @@ async fn expired_verified_tokens_count_under_the_token_root_and_auth_tier() { let mut claims = moq_auth::Claims::default() .with_root("verified/tenant") .with_subscribe([moq_auth::Pattern::all()]); - claims.expires = Some(std::time::SystemTime::UNIX_EPOCH + Duration::from_secs(1)); + claims.expires = Some(moq_clock::Wall::UNIX_EPOCH + Duration::from_secs(1)); let token = key.sign(&claims).unwrap(); for tier in [None, Some("edge")] { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); diff --git a/rs/moq-relay/tests/integration/session_revalidate.rs b/rs/moq-relay/tests/integration/session_revalidate.rs index 40585ba7d65..d23b544c23a 100644 --- a/rs/moq-relay/tests/integration/session_revalidate.rs +++ b/rs/moq-relay/tests/integration/session_revalidate.rs @@ -6,7 +6,7 @@ //! session. use std::sync::{Arc, Mutex}; -use std::time::{Duration, SystemTime}; +use std::time::Duration; use axum::extract::State; use axum::http::StatusCode; @@ -99,7 +99,7 @@ fn all() -> Patterns { /// A grant that lasts an hour and would not re-check on its own during a test. fn grant() -> Grant { let mut grant = Grant::new(all(), all()); - grant.expires = Some(SystemTime::now() + Duration::from_secs(3600)); + grant.expires = Some(moq_clock::wall() + Duration::from_secs(3600)); grant.revalidate = Some(Duration::from_secs(3600)); grant } diff --git a/rs/moq-room/clippy.toml b/rs/moq-room/clippy.toml index 892532bf144..9460b0fd5c8 100644 --- a/rs/moq-room/clippy.toml +++ b/rs/moq-room/clippy.toml @@ -7,3 +7,5 @@ disallowed-methods = [ { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, ] + +disallowed-types = [{ path = "std::time::SystemTime", reason = "use moq_clock::Wall" }] diff --git a/rs/moq-rtc/clippy.toml b/rs/moq-rtc/clippy.toml index f3f8720ac3f..d66a788c262 100644 --- a/rs/moq-rtc/clippy.toml +++ b/rs/moq-rtc/clippy.toml @@ -1,5 +1,5 @@ # Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. -# `SystemTime` stays an allowed type until its wall times move to `moq_clock::Wall`. +# str0m sender reports carry SystemTime; convert at that boundary. disallowed-methods = [ { path = "std::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, { path = "std::time::Instant::elapsed", reason = "read the ambient clock: moq_clock::Instant::elapsed()" }, diff --git a/rs/moq-rtc/src/session.rs b/rs/moq-rtc/src/session.rs index 930e454d00f..ab15548af30 100644 --- a/rs/moq-rtc/src/session.rs +++ b/rs/moq-rtc/src/session.rs @@ -11,7 +11,6 @@ use std::collections::{HashMap, HashSet}; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; -use std::time::{SystemTime, UNIX_EPOCH}; use moq_clock::Instant; @@ -318,8 +317,15 @@ pub(crate) struct IngestClock { impl IngestClock { /// Record the newest RTP-to-NTP correlation for a track. + /// + /// A report outside the wall range is ignored, keeping the track on arrival + /// time: RFC 3550 lets a sender without a wall clock report NTP time zero. fn observe(&mut self, mid: str0m::media::Mid, sender: str0m::rtp::rtcp::SenderInfo) { - self.tracks.entry(mid).or_default().sender = Some(SenderAnchor::new(sender)); + let Ok(anchor) = SenderAnchor::new(sender) else { + tracing::debug!(?mid, "ignoring a sender report outside the wall range"); + return; + }; + self.tracks.entry(mid).or_default().sender = Some(anchor); self.establish_ntp_epoch(); } @@ -403,11 +409,12 @@ struct SenderAnchor { } impl SenderAnchor { - fn new(sender: str0m::rtp::rtcp::SenderInfo) -> Self { - Self { - ntp_us: system_time_to_micros(sender.ntp_time), + fn new(sender: str0m::rtp::rtcp::SenderInfo) -> std::result::Result { + let wall = moq_clock::Wall::try_from(sender.ntp_time)?; + Ok(Self { + ntp_us: wall.saturating_duration_since(moq_clock::Wall::UNIX_EPOCH).as_micros() as i128, rtp_us: media_time_to_micros(&sender.rtp_time) as i128, - } + }) } fn capture_time_us(self, media_us: u64) -> i128 { @@ -415,13 +422,6 @@ impl SenderAnchor { } } -fn system_time_to_micros(time: SystemTime) -> i128 { - match time.duration_since(UNIX_EPOCH) { - Ok(duration) => duration.as_micros() as i128, - Err(err) => -(err.duration().as_micros() as i128), - } -} - fn to_u64(value: i128) -> u64 { value.clamp(0, u64::MAX as i128) as u64 } @@ -580,7 +580,7 @@ pub(crate) fn advertised_candidates(advertise: &[SocketAddr], local: SocketAddr) #[cfg(test)] mod tests { - use std::time::{Duration, UNIX_EPOCH}; + use std::time::{Duration, SystemTime, UNIX_EPOCH}; use str0m::media::Mid; use str0m::rtp::Ssrc; @@ -588,6 +588,36 @@ mod tests { use super::*; + #[test] + fn sender_reports_outside_the_wall_range_are_ignored() { + let mut clock = IngestClock::default(); + let audio = Mid::from("0"); + 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); + + // 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); + clock.observe(audio, sender_info(1, ntp_zero, 0)); + clock.observe( + video, + sender_info(2, UNIX_EPOCH + Duration::from_secs(18_446_744_074), 0), + ); + assert!(clock.tracks.values().all(|track| track.sender.is_none())); + + // Both tracks stay on arrival time. + assert_eq!( + clock.normalize(audio, t0 + Duration::from_secs(1), 1_000_000), + 1_000_000 + ); + assert_eq!( + clock.normalize(video, t0 + Duration::from_millis(1_050), 1_000_000), + 1_050_000 + ); + assert!(SenderAnchor::new(sender_info(1, UNIX_EPOCH, 0)).is_ok()); + } + #[test] fn media_flow_respects_negotiated_direction() { use str0m::media::Direction::{Inactive, RecvOnly, SendOnly, SendRecv}; diff --git a/rs/moq-stats/clippy.toml b/rs/moq-stats/clippy.toml index 892532bf144..9460b0fd5c8 100644 --- a/rs/moq-stats/clippy.toml +++ b/rs/moq-stats/clippy.toml @@ -7,3 +7,5 @@ disallowed-methods = [ { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, ] + +disallowed-types = [{ path = "std::time::SystemTime", reason = "use moq_clock::Wall" }] diff --git a/rs/moq-tokio/clippy.toml b/rs/moq-tokio/clippy.toml index f3f8720ac3f..d5a7b48f913 100644 --- a/rs/moq-tokio/clippy.toml +++ b/rs/moq-tokio/clippy.toml @@ -1,5 +1,4 @@ # Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. -# `SystemTime` stays an allowed type until its wall times move to `moq_clock::Wall`. disallowed-methods = [ { path = "std::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, { path = "std::time::Instant::elapsed", reason = "read the ambient clock: moq_clock::Instant::elapsed()" }, @@ -16,6 +15,7 @@ disallowed-methods = [ ] disallowed-types = [ + { path = "std::time::SystemTime", reason = "use moq_clock::Wall" }, { path = "std::time::Instant", reason = "use moq_clock::Instant" }, { path = "tokio::time::Instant", reason = "use moq_clock::Instant" }, { path = "tokio::time::Sleep", reason = "use moq_clock::Sleep" }, diff --git a/rs/moq-tokio/src/tls.rs b/rs/moq-tokio/src/tls.rs index 2fca3f373ae..89b2b9f3633 100644 --- a/rs/moq-tokio/src/tls.rs +++ b/rs/moq-tokio/src/tls.rs @@ -1746,15 +1746,14 @@ impl PeerIdentity { Some(cert.issuer().to_string()) } - /// The leaf certificate's `notAfter`, if it parses. A `notAfter` before the - /// Unix epoch is reported as `None`. - pub fn expiry(&self) -> Option { - use std::time::{Duration, UNIX_EPOCH}; - + /// The leaf certificate's `notAfter`, if it parses, saturated to the wall range. + pub fn expiry(&self) -> Option { let leaf = self.chain.first()?; let (_, cert) = x509_parser::parse_x509_certificate(leaf).ok()?; - let secs = u64::try_from(cert.validity().not_after.timestamp()).ok()?; - Some(UNIX_EPOCH + Duration::from_secs(secs)) + // Before 1970 reads as the epoch and past 2554 as the last wall time: no + // representable now compares differently against the saturated value. + let secs = u64::try_from(cert.validity().not_after.timestamp()).unwrap_or(0); + Some(moq_clock::Wall::UNIX_EPOCH.saturating_add(std::time::Duration::from_secs(secs))) } } @@ -2328,11 +2327,30 @@ mod tests { let parsed = PeerIdentity::from_any(Some(identity)).expect("chain parsed"); let expiry = parsed.expiry().expect("expiry parsed"); assert_eq!( - expiry.duration_since(std::time::UNIX_EPOCH).unwrap().as_secs(), + expiry.saturating_duration_since(moq_clock::Wall::UNIX_EPOCH).as_secs(), 2_000_000_000 ); } + #[cfg(feature = "quic")] + #[test] + fn peer_expiry_saturates_to_the_wall_range() { + let last = moq_clock::Wall::UNIX_EPOCH.saturating_add(std::time::Duration::MAX); + // rcgen's default notAfter is in 4096. + for (seconds, expected) in [ + (-1, moq_clock::Wall::UNIX_EPOCH), + (18_446_744_074, last), + (67_090_118_400, last), + ] { + let key = rcgen::KeyPair::generate().unwrap(); + let mut params = rcgen::CertificateParams::new(vec!["localhost".to_string()]).unwrap(); + params.not_after = ::time::OffsetDateTime::from_unix_timestamp(seconds).unwrap(); + let cert = params.self_signed(&key).unwrap().into(); + let peer = PeerIdentity { chain: vec![cert] }; + assert_eq!(peer.expiry(), Some(expected)); + } + } + #[cfg(feature = "quic")] #[test] fn peer_identity_none_without_chain() { diff --git a/rs/moq-transcode/Cargo.toml b/rs/moq-transcode/Cargo.toml index 8826b199b2d..8bab35ab297 100644 --- a/rs/moq-transcode/Cargo.toml +++ b/rs/moq-transcode/Cargo.toml @@ -45,6 +45,7 @@ tracing = { workspace = true } [dev-dependencies] anyhow = { workspace = true } +moq-clock = { workspace = true } moq-tokio = { path = "../moq-tokio", default-features = false, features = ["quic", "aws-lc-rs", "websocket"] } # The tests encode with OpenH264, the one encoder a GPU-less host has, so they # turn it on without making it a default of the library. diff --git a/rs/moq-transcode/src/catalog.rs b/rs/moq-transcode/src/catalog.rs index 656d1d6e9bb..4b7594abc7d 100644 --- a/rs/moq-transcode/src/catalog.rs +++ b/rs/moq-transcode/src/catalog.rs @@ -410,11 +410,6 @@ pub(crate) fn populate( } #[cfg(test)] -#[expect( - clippy::disallowed_methods, - clippy::disallowed_types, - reason = "tests read the host clock directly" -)] mod tests { use hang::catalog::H264; @@ -1025,13 +1020,13 @@ mod tests { /// `modify()`, so the derivative's clock carries that mapping and its data is stamped on it. #[tokio::test(start_paused = true)] async fn a_derivative_stamps_on_its_source_clock() { - use std::time::{Duration, SystemTime}; + use std::time::Duration; // A minute in, the source's mapping is far from the one a fresh clock would advertise. let ago = Duration::from_secs(60); let _ = moq_net::time::Instant::now(); tokio::time::advance(ago).await; - let clock = moq_mux::Clock::at(moq_net::time::Instant::now() - ago, SystemTime::now() - ago).unwrap(); + let clock = moq_mux::Clock::at(moq_net::time::Instant::now() - ago, moq_clock::wall() - ago).unwrap(); let mut input = moq_net::broadcast::Info::default().produce(); let source = moq_mux::catalog::Producer::new(&mut input, moq_mux::catalog::Config::default().with_clock(clock)).unwrap(); diff --git a/rs/moq-uring/clippy.toml b/rs/moq-uring/clippy.toml index 33fd42e8704..68e9ded5fd7 100644 --- a/rs/moq-uring/clippy.toml +++ b/rs/moq-uring/clippy.toml @@ -12,3 +12,5 @@ disallowed-methods = [ { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, ] + +disallowed-types = [{ path = "std::time::SystemTime", reason = "use moq_clock::Wall" }] diff --git a/rs/moq-video/src/encode/producer.rs b/rs/moq-video/src/encode/producer.rs index ba44911e7a7..d7ee8704fa8 100644 --- a/rs/moq-video/src/encode/producer.rs +++ b/rs/moq-video/src/encode/producer.rs @@ -1148,7 +1148,8 @@ mod tests { /// published timestamp may land up to `SAMPLING` early, never late. #[cfg(all(feature = "capture", feature = "openh264"))] mod clock { - use std::time::{Duration, SystemTime}; + use moq_clock::Wall; + use std::time::Duration; use moq_clock::Instant; @@ -1187,7 +1188,7 @@ mod tests { impl Fixture { /// Start the capture loop on a broadcast whose clock began `behind` ago, at `wall`. - async fn start(behind: Duration, wall: SystemTime) -> Self { + async fn start(behind: Duration, wall: Wall) -> Self { let epoch = moq_clock::now() .checked_sub(behind) .expect("a monotonic clock that far back"); @@ -1343,7 +1344,7 @@ mod tests { async fn a_late_first_frame_publishes_its_acquisition() { tokio::task::LocalSet::new() .run_until(async { - let fixture = Fixture::start(Duration::from_secs(5), SystemTime::now()).await; + let fixture = Fixture::start(Duration::from_secs(5), moq_clock::wall()).await; let mut track = fixture.subscribe().await; let camera = fixture.camera(); @@ -1366,7 +1367,7 @@ mod tests { async fn a_device_clock_restart_continues_forward() { tokio::task::LocalSet::new() .run_until(async { - let fixture = Fixture::start(Duration::from_secs(1), SystemTime::now()).await; + let fixture = Fixture::start(Duration::from_secs(1), moq_clock::wall()).await; let mut track = fixture.subscribe().await; let camera = fixture.camera(); @@ -1409,7 +1410,7 @@ mod tests { tokio::task::LocalSet::new() .run_until(async { let idle = Duration::from_millis(300); - let fixture = Fixture::start(Duration::from_secs(1), SystemTime::now()).await; + let fixture = Fixture::start(Duration::from_secs(1), moq_clock::wall()).await; let mut track = fixture.subscribe().await; let camera = fixture.camera(); @@ -1445,8 +1446,8 @@ mod tests { tokio::task::LocalSet::new() .run_until(async { // Whole seconds, so the advertised mapping holds it exactly. - let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap(); - let wall = SystemTime::UNIX_EPOCH + Duration::from_secs(now.as_secs() - 3600); + let now = moq_clock::wall().checked_duration_since(Wall::UNIX_EPOCH).unwrap(); + let wall = Wall::UNIX_EPOCH + Duration::from_secs(now.as_secs() - 3600); let fixture = Fixture::start(Duration::from_secs(1), wall).await; let advertised = fixture.catalog.snapshot().clock; assert_eq!(advertised, fixture.clock.wall()); @@ -1473,7 +1474,7 @@ mod tests { async fn retained_archive_playback_keeps_the_live_timestamps() { tokio::task::LocalSet::new() .run_until(async { - let fixture = Fixture::start(Duration::from_secs(1), SystemTime::now()).await; + let fixture = Fixture::start(Duration::from_secs(1), moq_clock::wall()).await; let section = fixture .catalog .snapshot()