diff --git a/Cargo.lock b/Cargo.lock index 6322388b2d0..86ad05b6b1a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3136,6 +3136,7 @@ dependencies = [ "derive_more 2.1.1", "hex", "kio 0.6.2", + "moq-clock", "moq-json", "moq-mux", "moq-net", @@ -4553,6 +4554,7 @@ dependencies = [ "fixed-resample", "hang", "kio 0.6.2", + "moq-clock", "moq-mux", "moq-net", "objc2 0.6.5", @@ -4634,6 +4636,7 @@ version = "0.0.1" dependencies = [ "anyhow", "humantime", + "moq-clock", "moq-net", "moq-tokio", "moq-uring", @@ -4656,6 +4659,7 @@ dependencies = [ "bytes", "hang", "moq-audio", + "moq-clock", "moq-json", "moq-mux", "moq-net", @@ -4842,6 +4846,7 @@ dependencies = [ "gstreamer", "hang", "moq-audio", + "moq-clock", "moq-mux", "moq-net", "moq-tokio", @@ -4864,6 +4869,7 @@ dependencies = [ "kio 0.6.2", "m3u8-rs", "moq-archive", + "moq-clock", "moq-json", "moq-mux", "moq-net", @@ -4883,6 +4889,7 @@ dependencies = [ name = "moq-ice" version = "0.1.0" dependencies = [ + "moq-clock", "str0m", "stun-types", "thiserror 2.0.21", @@ -5155,6 +5162,7 @@ dependencies = [ "axum", "bytes", "hang", + "moq-clock", "moq-ice", "moq-mux", "moq-net", @@ -5202,6 +5210,7 @@ dependencies = [ "base64 0.23.1", "futures", "hang", + "moq-clock", "moq-mux", "moq-net", "moq-tokio", @@ -5222,6 +5231,7 @@ dependencies = [ "clap", "humantime", "humantime-serde", + "moq-clock", "rand 0.10.3", "serde", "serde_json", @@ -5458,6 +5468,7 @@ dependencies = [ "libloading 0.9.0", "libvpx-native-sys", "linux-raw-sys 0.12.1", + "moq-clock", "moq-mux", "moq-net", "moq-nvenc", diff --git a/doc/lib/rs/moq-clock.md b/doc/lib/rs/moq-clock.md index cf1e7109891..24841d6e246 100644 --- a/doc/lib/rs/moq-clock.md +++ b/doc/lib/rs/moq-clock.md @@ -28,8 +28,10 @@ and it pauses the instant but not wall time. The simulator is its own clock too. A runtime that reads the time itself, like a moq-uring worker, enters a `Deadlines` queue on its thread, and the ambient clock is that queue. -Instants from different clocks don't compare, and there is no conversion back -to `std::time::Instant`. +Instants from different clocks don't compare. On native, `Instant::into_std()` +and `Instant::from_std()` convert at a third-party API that takes +`std::time::Instant`, through the runtime clock's origin. That is exact on a +running clock, and keeps only durations on paused tokio or the simulator. ## Caller-driven code diff --git a/quest/m1/time/README.md b/quest/m1/time/README.md index b800de32606..80ace584b8f 100644 --- a/quest/m1/time/README.md +++ b/quest/m1/time/README.md @@ -81,6 +81,14 @@ reasons, so later sessions don't reopen them: `disallowed-types` in a per-crate `clippy.toml`, and a biome `noRestrictedGlobals` override, allowing only the backend modules. The workspace-wide test and lint sweep follows in m2. +- **Third-party std clocks.** A third-party API that takes + `std::time::Instant` (str0m, srt-tokio, winit, qlog) converts with + `Instant::into_std` and `Instant::from_std`, native only, through the runtime + clock's origin: exact on a running clock, durations only on paused tokio or + the simulator. Device threads outside any runtime keep `std::thread::sleep` + under a per-site `#[allow]`, since they have no ambient clock to wait on + (decided 2026-10-20 by the maintainer, in + [#6135](https://github.com/moq-dev/moq/pull/6135)). - **Consolidation.** perf/3122 (one clock read per io_uring turn) landed with moq-uring on moq-clock in [#5926](https://github.com/moq-dev/moq/pull/5926). The relay seam [bench-relay](/quest/m2/bench-relay.md) needed is `moq_relay::Accepted`: @@ -97,8 +105,8 @@ cleanup and the global lint ratchet belong to ## Required -- [Every crate on moq-clock](/quest/m1/time/crates.md) - every remaining crate reads time only through moq-clock, with controlled tests for the production/public API migrations - [JS timers fire at their own deadlines](/quest/m1/time/js-deadlines.md) - `Manual.advance` (renamed from `advanceAsync`) steps to each deadline, sync `advance` becomes `jump`, and `Effect.interval` arms its first period synchronously +- [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 ## Related diff --git a/quest/m1/time/crates.md b/quest/m1/time/crates.md deleted file mode 100644 index da2c6197b07..00000000000 --- a/quest/m1/time/crates.md +++ /dev/null @@ -1,55 +0,0 @@ -# [XL] Every crate on moq-clock - -## Goal - -Every remaining workspace crate (moq-tokio, moq-relay, moq-cli, -moq-hls, moq-auth, moq-archive, moq-audio, moq-video, moq-gst, moq-rtc, -moq-rtmp, moq-srt, moq-shaper, moq-sock, moq-transcode, moq-e2ee, moq-boy, -moq-bench, moq-c, hang, and the rest under `rs/`) reads time and arms timers -only through `moq-clock`, and tests needed to prove those migrations use the sim, paused tokio, or -events. No production direct `Instant::now`, `SystemTime::now`, `tokio::time`, or -`std::thread::sleep` remains outside moq-clock's backends and explicit -performance measurement (moq-bench's timings). - -## Plan - -Follow the real-I/O rule in [the line's README](/quest/m1/time/README.md): -a migrated test with no real socket, process, or device uses the sim (or paused -tokio until it can); one that needs real I/O waits on events, never on paused -tokio, which auto-advances to a timer before the OS event arrives, and never -on a fixed sleep. moq-relay's in-memory integration tests -(`tests/integration/connection.rs`) move onto the sim with -[the runtime trait](/quest/m2/runtime-trait.md), not here. - -moq-auth's `Grant` and lease clock, and moq-relay's lease, credential, and -admission timers, already run on moq-clock (`Grant::deadline` returns a -`moq_clock::Instant`); build on that rather than migrating them again. - -Fix mixed clocks first: anything that reads std time but waits on tokio time -(a backoff's stability window, a gate computed with std `Instant` and slept -with tokio) is a bug under paused time. - -Split the PR by crate group if review needs it; ban direct clock reads in each -production scope as it finishes. Unrelated legacy test conversions and the -workspace-wide lint ratchet follow in m2. - -[#5987](https://github.com/moq-dev/moq/pull/5987) migrated moq-auth (auth -accounting, JWT checks, policy expiry), RTMP session timestamps and -deadlines, archive retention, and listener stall accounting, and added the -per-crate ratchet to moq-auth, moq-rtmp, and moq-archive. The ratchet also -covers moq-net, moq-mux, moq-ffi, moq-room, moq-stats, and moq-uring; the -rest of the workspace and public `SystemTime` fields still need migration. In particular, -SRT and WebRTC hand instants to third-party APIs on std's clock, and audio/video -device threads block outside an async runtime; those boundaries still need -clock support rather than a second host-clock read at each call site. -moq-srt's `a_late_payload_keeps_its_past_host_instant` compares a direct -`StdInstant::now()` with `host_instant(moq_net::time::now())`, so it can flake -under load; the SRT boundary migration rewrites it on controlled time -(decided 2026-10-20 instead of a separate flake quest). - -Public API: breaking wherever a crate exposes an instant or a time source. -Wire: none. - -## Related - -- [Time test sweep](/quest/m2/time-test-sweep.md) - unrelated test-only/private clock cleanup and global lint are deferred; migrate production/public APIs and their required regression tests here diff --git a/quest/m1/time/js-deadlines.md b/quest/m1/time/js-deadlines.md index 40604b3c567..079e2dfe494 100644 --- a/quest/m1/time/js-deadlines.md +++ b/quest/m1/time/js-deadlines.md @@ -78,5 +78,4 @@ target, and the clock never ends past the target or moves backward. ## Related -- [Every crate on moq-clock](/quest/m1/time/crates.md) - the Rust side of the same clock contract - [Time test sweep](/quest/m2/time-test-sweep.md) - legacy JS tests converted there get stepped `advance` for free diff --git a/quest/m1/time/wall.md b/quest/m1/time/wall.md new file mode 100644 index 00000000000..d3feec906e8 --- /dev/null +++ b/quest/m1/time/wall.md @@ -0,0 +1,36 @@ +# [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-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`. + +Public API: breaking in hang, moq-mux, moq-hls, moq-quic, moq-relay, and +moq-tokio, each with a `MIGRATE.md` entry. 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 5300c906ed2..a189907d10d 100644 --- a/rs/hang/Cargo.toml +++ b/rs/hang/Cargo.toml @@ -31,6 +31,7 @@ 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 new file mode 100644 index 00000000000..f3f8720ac3f --- /dev/null +++ b/rs/hang/clippy.toml @@ -0,0 +1,23 @@ +# 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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +disallowed-types = [ + { 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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/hang/examples/video.rs b/rs/hang/examples/video.rs index 85fbe218d12..40fc8f57511 100644 --- a/rs/hang/examples/video.rs +++ b/rs/hang/examples/video.rs @@ -103,7 +103,7 @@ async fn run_broadcast(origin: moq_net::origin::Producer) -> anyhow::Result<()> }; producer.write(frame)?; - tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; + moq_clock::sleep(tokio::time::Duration::from_secs(1)).await; let frame = moq_mux::container::Frame { timestamp: moq_net::Timestamp::from_secs(2).unwrap(), @@ -113,7 +113,7 @@ async fn run_broadcast(origin: moq_net::origin::Producer) -> anyhow::Result<()> }; producer.write(frame)?; - tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; + moq_clock::sleep(tokio::time::Duration::from_secs(1)).await; // Marking this frame as a keyframe closes the current group and starts a new one. let frame = moq_mux::container::Frame { @@ -125,7 +125,7 @@ async fn run_broadcast(origin: moq_net::origin::Producer) -> anyhow::Result<()> producer.write(frame)?; // Sleep before exiting and closing the broadcast. - tokio::time::sleep(tokio::time::Duration::from_secs(10)).await; + moq_clock::sleep(tokio::time::Duration::from_secs(10)).await; Ok(()) } diff --git a/rs/libmoq/clippy.toml b/rs/libmoq/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/libmoq/clippy.toml @@ -0,0 +1,23 @@ +# Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. +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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-audio/Cargo.toml b/rs/moq-audio/Cargo.toml index dbbd2c5fa34..a0af4769257 100644 --- a/rs/moq-audio/Cargo.toml +++ b/rs/moq-audio/Cargo.toml @@ -80,6 +80,7 @@ cpal = { version = "0.18", optional = true } fixed-resample = { version = "0.13", optional = true, default-features = false, features = ["channel", "resampler"] } hang = { workspace = true } kio = { workspace = true, optional = true } +moq-clock = { workspace = true } moq-mux = { workspace = true } moq-net = { workspace = true } # We only use the sinc resampler (Async::new_sinc), so skip the default diff --git a/rs/moq-audio/clippy.toml b/rs/moq-audio/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/moq-audio/clippy.toml @@ -0,0 +1,23 @@ +# Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. +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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-audio/src/aec.rs b/rs/moq-audio/src/aec.rs index 8ed9dd2d350..fc40ce13e63 100644 --- a/rs/moq-audio/src/aec.rs +++ b/rs/moq-audio/src/aec.rs @@ -626,6 +626,7 @@ fn channel(rate: u32) -> (ResamplingProd, ResamplingCons) { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use std::collections::VecDeque; use std::time::Duration; diff --git a/rs/moq-audio/src/capture.rs b/rs/moq-audio/src/capture.rs index 41ddc4a2752..8fcd98a5d7c 100644 --- a/rs/moq-audio/src/capture.rs +++ b/rs/moq-audio/src/capture.rs @@ -464,7 +464,7 @@ impl Microphone { // Await the first buffer to surface a permission failure (or dead device) // as an error rather than a silent hang in the capture loop. - let pending = match tokio::time::timeout(FIRST_BUFFER_TIMEOUT, reader.read()).await { + let pending = match moq_clock::timeout(FIRST_BUFFER_TIMEOUT, reader.read()).await { Ok(Ok(Some(samples))) => samples, Ok(Ok(None)) => { return Err(Failure::retry(Error::Capture(format!( diff --git a/rs/moq-audio/src/capture/buffer.rs b/rs/moq-audio/src/capture/buffer.rs index d5a63ced111..cf58ad8a812 100644 --- a/rs/moq-audio/src/capture/buffer.rs +++ b/rs/moq-audio/src/capture/buffer.rs @@ -89,6 +89,8 @@ fn relay(mut pending: HeapCons, tx: mpsc::Sender) { if !pending.write_is_held() { return; } + // The device thread runs outside any runtime, so it blocks on the host clock. + #[allow(clippy::disallowed_methods)] std::thread::sleep(RELAY_POLL_INTERVAL); } } diff --git a/rs/moq-audio/src/capture/channel.rs b/rs/moq-audio/src/capture/channel.rs index 229ad93b430..e336c81d6c1 100644 --- a/rs/moq-audio/src/capture/channel.rs +++ b/rs/moq-audio/src/capture/channel.rs @@ -10,7 +10,9 @@ use std::sync::{ Arc, atomic::{AtomicU64, Ordering}, }; -use std::time::{Duration, Instant}; +use std::time::Duration; + +use moq_clock::Instant; use tokio::sync::mpsc; diff --git a/rs/moq-audio/src/capture/permission.rs b/rs/moq-audio/src/capture/permission.rs index 0c664ee8831..07493fbd815 100644 --- a/rs/moq-audio/src/capture/permission.rs +++ b/rs/moq-audio/src/capture/permission.rs @@ -67,7 +67,7 @@ async fn request_access(media: &objc2_av_foundation::AVMediaType) -> Result<(), unsafe { AVCaptureDevice::requestAccessForMediaType_completionHandler(media, &handler) }; - match tokio::time::timeout(PROMPT_TIMEOUT, rx).await { + match moq_clock::timeout(PROMPT_TIMEOUT, rx).await { Ok(Ok(true)) => Ok(()), Ok(Ok(false)) => Err(denied()), // Prompt dismissed without a decision, or the callback never fired within diff --git a/rs/moq-audio/src/capture/screencapture.rs b/rs/moq-audio/src/capture/screencapture.rs index 5fbb32ea04e..e15da5f403a 100644 --- a/rs/moq-audio/src/capture/screencapture.rs +++ b/rs/moq-audio/src/capture/screencapture.rs @@ -124,7 +124,7 @@ impl SystemAudio { _dispatch: dispatch, }; - let pending = match tokio::time::timeout(FIRST_BUFFER_TIMEOUT, rx.recv()).await { + let pending = match moq_clock::timeout(FIRST_BUFFER_TIMEOUT, rx.recv()).await { Ok(Some(buffer)) => buffer, Ok(None) => { return Err(Error::Capture("system audio stopped before any samples".into())); @@ -352,7 +352,7 @@ async fn shareable_content() -> Result, Error> { }); unsafe { SCShareableContent::getShareableContentWithCompletionHandler(&handler) }; - match tokio::time::timeout(ASYNC_TIMEOUT, rx).await { + match moq_clock::timeout(ASYNC_TIMEOUT, rx).await { Ok(Ok(Ok(content))) => Ok(content.0), Ok(Ok(Err(msg))) => Err(Error::Capture(format!("shareable content: {msg}"))), Ok(Err(_)) => Err(Error::Capture("shareable content handler dropped".into())), @@ -374,7 +374,7 @@ async fn start_capture(stream: &SCStream) -> Result<(), Error> { }); unsafe { stream.startCaptureWithCompletionHandler(Some(&handler)) }; - match tokio::time::timeout(ASYNC_TIMEOUT, rx).await { + match moq_clock::timeout(ASYNC_TIMEOUT, rx).await { Ok(Ok(None)) => Ok(()), Ok(Ok(Some(msg))) => Err(Error::Capture(format!("start system audio: {msg}"))), Ok(Err(_)) => Err(Error::Capture("start-capture handler dropped".into())), diff --git a/rs/moq-audio/src/decode/consumer.rs b/rs/moq-audio/src/decode/consumer.rs index a77ad17ebe7..6a1ab413964 100644 --- a/rs/moq-audio/src/decode/consumer.rs +++ b/rs/moq-audio/src/decode/consumer.rs @@ -2,8 +2,9 @@ use std::collections::VecDeque; +use moq_clock::Instant; use moq_mux::container::Read as Encoded; -use std::time::{Duration, Instant}; +use std::time::Duration; use bytes::Bytes; diff --git a/rs/moq-audio/src/encode/capture.rs b/rs/moq-audio/src/encode/capture.rs index d9ed42b978b..38300a6b750 100644 --- a/rs/moq-audio/src/encode/capture.rs +++ b/rs/moq-audio/src/encode/capture.rs @@ -1056,7 +1056,7 @@ impl Supervisor { }; tracing::warn!(error = %failure, "audio capture format unavailable"); - tokio::time::sleep(self.advance()).await; + moq_clock::sleep(self.advance()).await; } } @@ -1183,7 +1183,7 @@ impl Supervisor { } continue 'demand; } - _ = tokio::time::sleep(wait) => {} + _ = moq_clock::sleep(wait) => {} } } } @@ -1211,6 +1211,7 @@ fn frame(samples: &[f32], timestamp_us: u64) -> Result { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use std::collections::VecDeque; use std::future::Future; diff --git a/rs/moq-audio/src/encode/producer.rs b/rs/moq-audio/src/encode/producer.rs index f26e1844875..5968c94baa6 100644 --- a/rs/moq-audio/src/encode/producer.rs +++ b/rs/moq-audio/src/encode/producer.rs @@ -556,6 +556,7 @@ impl Producer { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { async fn decoded_frame(consumer: &mut crate::decode::Consumer) -> Result, Error> { loop { diff --git a/rs/moq-audio/src/playback/driver.rs b/rs/moq-audio/src/playback/driver.rs index 897b21cf417..f902d20ce22 100644 --- a/rs/moq-audio/src/playback/driver.rs +++ b/rs/moq-audio/src/playback/driver.rs @@ -5,6 +5,7 @@ //! the hot path; they register themselves in [`Shared`] and hand their consumer //! straight to the mixer. +use moq_clock::Instant; use std::collections::VecDeque; use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, Ordering}; #[cfg(feature = "aec")] @@ -12,7 +13,7 @@ use std::sync::mpsc::TrySendError; use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; use std::sync::{Arc, Mutex, OnceLock}; use std::thread::Thread; -use std::time::{Duration, Instant}; +use std::time::Duration; use cpal::traits::{DeviceTrait, StreamTrait}; use rand::RngExt; @@ -936,6 +937,8 @@ impl Driver { } // The mixer's queue is full, which takes a burst far larger than a // device period. Give it a period to drain and try again. + // The device thread runs outside any runtime, so it blocks on the host clock. + #[allow(clippy::disallowed_methods)] std::thread::sleep(SYNC_DELAY); } @@ -1007,6 +1010,7 @@ impl Driver { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; use crate::playback::sink::{self, Input}; diff --git a/rs/moq-audio/src/playback/mixer.rs b/rs/moq-audio/src/playback/mixer.rs index 3341009d85f..18c09ca142c 100644 --- a/rs/moq-audio/src/playback/mixer.rs +++ b/rs/moq-audio/src/playback/mixer.rs @@ -396,6 +396,7 @@ impl Mixer { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; diff --git a/rs/moq-audio/tests/integration/main.rs b/rs/moq-audio/tests/integration/main.rs index 98cdd493f98..425e596c7e0 100644 --- a/rs/moq-audio/tests/integration/main.rs +++ b/rs/moq-audio/tests/integration/main.rs @@ -2,6 +2,7 @@ //! //! Each `tests/*.rs` file is its own crate that links this package and its //! dependencies again, so add new integration tests here as a module. +#![allow(clippy::disallowed_methods, clippy::disallowed_types)] mod import; mod playback; diff --git a/rs/moq-bench/Cargo.toml b/rs/moq-bench/Cargo.toml index c5db0c8f8ab..d0006eaddd0 100644 --- a/rs/moq-bench/Cargo.toml +++ b/rs/moq-bench/Cargo.toml @@ -44,6 +44,7 @@ websocket = ["moq-tokio/websocket"] [dependencies] anyhow = { workspace = true, features = ["backtrace"] } humantime = { workspace = true } +moq-clock = { workspace = true } moq-net = { workspace = true } moq-tokio = { workspace = true, default-features = false, features = ["aws-lc-rs", "net"] } rand = { workspace = true } diff --git a/rs/moq-bench/clippy.toml b/rs/moq-bench/clippy.toml new file mode 100644 index 00000000000..f3f8720ac3f --- /dev/null +++ b/rs/moq-bench/clippy.toml @@ -0,0 +1,23 @@ +# 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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +disallowed-types = [ + { 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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-bench/src/config.rs b/rs/moq-bench/src/config.rs index fa0217c9f49..4f4b524f2da 100644 --- a/rs/moq-bench/src/config.rs +++ b/rs/moq-bench/src/config.rs @@ -223,7 +223,7 @@ impl Config { deprecated.extend(config.deprecated()); anyhow::ensure!(deprecated.is_empty(), "{deprecated}"); config.origins = Some(resolved); - // `Stats::report` feeds this into `tokio::time::interval`, which panics on a + // `Stats::report` feeds this into `moq_clock::interval`, which panics on a // zero period. Reject it up front with a clear message. anyhow::ensure!(!config.report().is_zero(), "--report must be greater than 0s"); if let Some(fanout) = &config.fanout { @@ -484,7 +484,7 @@ url = "https://example.com" #[test] fn zero_report_is_rejected() { - // A zero report interval would panic `tokio::time::interval`; reject it early. + // A zero report interval would panic `moq_clock::interval`; reject it early. let err = Config::parse_and_merge(["moq-bench", "--report", "0s"]).unwrap_err(); assert!(err.to_string().contains("report"), "unexpected error: {err}"); } diff --git a/rs/moq-bench/src/connection.rs b/rs/moq-bench/src/connection.rs index 4a67f1bd2c8..ca6d0597c79 100644 --- a/rs/moq-bench/src/connection.rs +++ b/rs/moq-bench/src/connection.rs @@ -243,8 +243,8 @@ async fn produce( let zeros = Bytes::from(vec![0u8; rolled.frame_size as usize]); let period = Duration::from_secs_f64(1.0 / rolled.fps as f64); - let mut ticker = tokio::time::interval(period); - ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + let mut ticker = moq_clock::interval(period); + ticker.set_missed_tick_behavior(moq_clock::MissedTickBehavior::Delay); let mut sequence = 0u64; loop { @@ -261,7 +261,7 @@ async fn produce( group_size: rolled.group_size, broadcasts: rolled.broadcasts, subscribe: rolled.subscribe, - timestamp_ms: SystemTime::now() + timestamp_ms: SystemTime::from(moq_clock::wall()) .duration_since(UNIX_EPOCH) .unwrap_or_default() .as_millis(), @@ -350,7 +350,7 @@ async fn subscribe( let mut eligible = 0; // Gather candidates until the startup window closes (or the announce stream ends). - let deadline = tokio::time::sleep(startup); + let deadline = moq_clock::sleep(startup); tokio::pin!(deadline); loop { tokio::select! { @@ -657,6 +657,7 @@ impl Drop for Gauge<'_> { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; diff --git a/rs/moq-bench/src/host.rs b/rs/moq-bench/src/host.rs index b9985f73eef..bccc1428a43 100644 --- a/rs/moq-bench/src/host.rs +++ b/rs/moq-bench/src/host.rs @@ -233,7 +233,7 @@ mod linux { target.ctx.retain(|tid| live.contains(&tid)); Ok(Sample { - timestamp_ms: SystemTime::now() + timestamp_ms: SystemTime::from(moq_clock::wall()) .duration_since(UNIX_EPOCH) .unwrap_or_default() .as_millis(), @@ -280,7 +280,7 @@ mod linux { .join(", ") ); - let start = std::time::Instant::now(); + let start = moq_clock::now(); loop { // Host-wide once per round: unlike the per-target reads inside `sample`, // a failure here is not a target exiting, so it fails the run. @@ -313,6 +313,8 @@ mod linux { ) else { return Ok(()); }; + // The sampler runs outside any runtime, so it blocks on the host clock. + #[allow(clippy::disallowed_methods)] std::thread::sleep(delay); } } diff --git a/rs/moq-bench/src/main.rs b/rs/moq-bench/src/main.rs index 31679b1546a..e41865a9de5 100644 --- a/rs/moq-bench/src/main.rs +++ b/rs/moq-bench/src/main.rs @@ -84,7 +84,7 @@ async fn main() -> anyhow::Result<()> { stats: stats.clone(), }; tasks.spawn(async move { - tokio::time::sleep(delay).await; + moq_clock::sleep(delay).await; connection::run(ctx).await; }); } @@ -92,7 +92,7 @@ async fn main() -> anyhow::Result<()> { let duration = config.duration.map(crate::duration::Duration::into_std); let stop = async move { match duration { - Some(d) => tokio::time::sleep(d).await, + Some(d) => moq_clock::sleep(d).await, None => std::future::pending::<()>().await, } }; diff --git a/rs/moq-bench/src/stats.rs b/rs/moq-bench/src/stats.rs index e5de0577e0c..b094cd313e3 100644 --- a/rs/moq-bench/src/stats.rs +++ b/rs/moq-bench/src/stats.rs @@ -100,7 +100,7 @@ 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::now() + let now_ms = SystemTime::from(moq_clock::wall()) .duration_since(UNIX_EPOCH) .unwrap_or_default() .as_millis(); @@ -125,7 +125,7 @@ impl Stats { /// recorded stats are partial is invalid, so the caller must fail the run /// rather than exit green. pub async fn report(&self, interval: Duration, mut output: Option) -> anyhow::Result<()> { - let mut ticker = tokio::time::interval(interval); + let mut ticker = moq_clock::interval(interval); // Skip the immediate first tick so the first report covers a full interval. ticker.tick().await; @@ -419,7 +419,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::now(); + let captured_at = SystemTime::from(moq_clock::wall()); let LatencyState { buckets, max_ms, @@ -481,6 +481,7 @@ fn highest_bucket(buckets: &[u64]) -> Option { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use std::sync::Arc; diff --git a/rs/moq-boy/Cargo.toml b/rs/moq-boy/Cargo.toml index 905680aee84..18a5ca44508 100644 --- a/rs/moq-boy/Cargo.toml +++ b/rs/moq-boy/Cargo.toml @@ -29,6 +29,7 @@ boytacean = { version = "0.13", features = ["gen-mock"] } bytes = { workspace = true } hang = { workspace = true } moq-audio = { workspace = true } +moq-clock = { workspace = true } moq-json = { workspace = true } moq-mux = { workspace = true } moq-net = { workspace = true } diff --git a/rs/moq-boy/clippy.toml b/rs/moq-boy/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/moq-boy/clippy.toml @@ -0,0 +1,23 @@ +# Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. +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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-boy/src/input.rs b/rs/moq-boy/src/input.rs index 5da2942145e..4099443eac5 100644 --- a/rs/moq-boy/src/input.rs +++ b/rs/moq-boy/src/input.rs @@ -168,6 +168,7 @@ async fn handle_viewer_commands( } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use std::time::Duration; diff --git a/rs/moq-boy/src/main.rs b/rs/moq-boy/src/main.rs index 3e509520b7c..bf19324aa5e 100644 --- a/rs/moq-boy/src/main.rs +++ b/rs/moq-boy/src/main.rs @@ -25,11 +25,12 @@ use anyhow::{Context, Result}; use bytes::Bytes; +use moq_clock::Instant; use std::collections::{BTreeMap, HashMap}; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Condvar, Mutex}; -use std::time::{Duration, Instant}; +use std::time::Duration; #[cfg(feature = "jemalloc")] #[global_allocator] @@ -425,6 +426,8 @@ fn run_emulator( // Wait for next frame. let now = Instant::now(); if now < next_frame { + // The emulator thread runs outside any runtime, so it blocks on the host clock. + #[allow(clippy::disallowed_methods)] std::thread::sleep(next_frame - now); } next_frame += frame_duration; diff --git a/rs/moq-boy/src/stats.rs b/rs/moq-boy/src/stats.rs index c217ebb38b2..edd8af3f9e9 100644 --- a/rs/moq-boy/src/stats.rs +++ b/rs/moq-boy/src/stats.rs @@ -3,7 +3,8 @@ //! Tracks how much wall-clock time is spent on emulation, video encoding, //! and audio encoding. Published to viewers via the status track. -use std::time::{Duration, Instant}; +use moq_clock::Instant; +use std::time::Duration; use serde::Serialize; diff --git a/rs/moq-boy/src/video.rs b/rs/moq-boy/src/video.rs index 68c5e5c2f0e..fec0995ac6a 100644 --- a/rs/moq-boy/src/video.rs +++ b/rs/moq-boy/src/video.rs @@ -6,9 +6,10 @@ //! encode and the avc3 publish; this module keeps moq-boy's threading, //! frame-dropping, force-keyframe and timing-stats behavior. +use moq_clock::Instant; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::time::{Duration, Instant}; +use std::time::Duration; use bytes::Bytes; diff --git a/rs/moq-c/clippy.toml b/rs/moq-c/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/moq-c/clippy.toml @@ -0,0 +1,23 @@ +# Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. +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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-c/src/lib.rs b/rs/moq-c/src/lib.rs index c249cc994e5..6cfc0855809 100644 --- a/rs/moq-c/src/lib.rs +++ b/rs/moq-c/src/lib.rs @@ -51,4 +51,5 @@ pub(crate) use session::*; pub(crate) use state::*; #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod test; diff --git a/rs/moq-cli/benches/play_buffer.rs b/rs/moq-cli/benches/play_buffer.rs index 758c6ea8276..7e25af385e5 100644 --- a/rs/moq-cli/benches/play_buffer.rs +++ b/rs/moq-cli/benches/play_buffer.rs @@ -1,5 +1,6 @@ //! Encoded retention cost and peak memory, swept over delay and bitrate. //! Run with `cargo bench -p moq-cli --bench play_buffer`. +#![allow(clippy::disallowed_methods, clippy::disallowed_types)] #[allow(dead_code)] #[path = "../src/play/buffer.rs"] diff --git a/rs/moq-cli/clippy.toml b/rs/moq-cli/clippy.toml new file mode 100644 index 00000000000..f3f8720ac3f --- /dev/null +++ b/rs/moq-cli/clippy.toml @@ -0,0 +1,23 @@ +# 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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +disallowed-types = [ + { 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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-cli/src/announced.rs b/rs/moq-cli/src/announced.rs index 6b757249881..ff0ae698bae 100644 --- a/rs/moq-cli/src/announced.rs +++ b/rs/moq-cli/src/announced.rs @@ -168,6 +168,7 @@ impl View { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; use crate::args::{Command, Invocation}; diff --git a/rs/moq-cli/src/archive.rs b/rs/moq-cli/src/archive.rs index 4c8aa754b54..2fdbe898121 100644 --- a/rs/moq-cli/src/archive.rs +++ b/rs/moq-cli/src/archive.rs @@ -275,7 +275,7 @@ pub async fn import( }; let refresh = async { loop { - tokio::time::sleep(interval).await; + moq_clock::sleep(interval).await; // A rendition the recording enrolled after the replay started. for (track, timeline) in listing.timelines().await? { if let std::collections::btree_map::Entry::Vacant(entry) = timelines.entry(track) { @@ -310,6 +310,7 @@ fn open(url: &Url) -> anyhow::Result>> { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; diff --git a/rs/moq-cli/src/complete.rs b/rs/moq-cli/src/complete.rs index fb14eb3c21a..147774ad3a6 100644 --- a/rs/moq-cli/src/complete.rs +++ b/rs/moq-cli/src/complete.rs @@ -20,7 +20,8 @@ use std::future::Future; use std::time::Duration; use anyhow::Context; -use tokio::time::{Instant, timeout_at}; +use moq_clock::Instant; +use moq_clock::timeout_at; #[cfg(feature = "capture")] use usage_rs::complete::{Candidate, CompleteCtx, CompletionFuture}; use usage_rs::complete::{CompletionOverlay, CompletionRequest, Shell, render}; diff --git a/rs/moq-cli/src/fetch.rs b/rs/moq-cli/src/fetch.rs index 4a33d79c561..a91824ce382 100644 --- a/rs/moq-cli/src/fetch.rs +++ b/rs/moq-cli/src/fetch.rs @@ -6,8 +6,9 @@ use std::time::Duration; use anyhow::Context; use base64::Engine; use hang::moq_net; +use moq_clock::Instant; +use moq_clock::timeout_at; use tokio::io::{AsyncWrite, AsyncWriteExt}; -use tokio::time::{Instant, timeout_at}; use crate::args::MoqSide; diff --git a/rs/moq-cli/src/main.rs b/rs/moq-cli/src/main.rs index 196863afe11..318bba50fdf 100644 --- a/rs/moq-cli/src/main.rs +++ b/rs/moq-cli/src/main.rs @@ -1028,6 +1028,7 @@ fn reject_listener_cors(cors: &crate::web::Cors, endpoint: &str) -> anyhow::Resu } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; use std::cell::Cell; diff --git a/rs/moq-cli/src/play/media.rs b/rs/moq-cli/src/play/media.rs index 3c8bb8fae94..f20cc5c0298 100644 --- a/rs/moq-cli/src/play/media.rs +++ b/rs/moq-cli/src/play/media.rs @@ -708,10 +708,11 @@ async fn play_audio( async fn drain(sink: impl Sink) { // The estimated target moves, so the depth the sink was opened with says // nothing about what it holds now: read it at retirement instead. - let _ = tokio::time::timeout(sink.buffered() + AUDIO_DRAIN_GRACE, sink.finish()).await; + let _ = moq_clock::timeout(sink.buffered() + AUDIO_DRAIN_GRACE, sink.finish()).await; } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use bytes::Bytes; use hang::catalog::{AudioCodec, AudioConfig}; diff --git a/rs/moq-cli/src/play/metrics.rs b/rs/moq-cli/src/play/metrics.rs index 97c64ae49f3..645aeb7acd1 100644 --- a/rs/moq-cli/src/play/metrics.rs +++ b/rs/moq-cli/src/play/metrics.rs @@ -98,7 +98,7 @@ pub(super) struct Metrics { /// What closed engines counted, added to the current one's totals. base: Totals, start: Instant, - interval: tokio::time::Interval, + interval: moq_clock::Interval, } impl Metrics { @@ -109,8 +109,8 @@ impl Metrics { ) -> anyhow::Result<(Self, mpsc::UnboundedSender)> { let file = File::create(path).with_context(|| format!("failed to create {}", path.display()))?; let (observe, observers) = mpsc::unbounded_channel(); - let mut interval = tokio::time::interval(INTERVAL); - interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + let mut interval = moq_clock::interval(INTERVAL); + interval.set_missed_tick_behavior(moq_clock::MissedTickBehavior::Delay); let metrics = Self { file: BufWriter::new(file), presentation, diff --git a/rs/moq-cli/src/play/timeline.rs b/rs/moq-cli/src/play/timeline.rs index c699ce9d82f..72f9b35b3fb 100644 --- a/rs/moq-cli/src/play/timeline.rs +++ b/rs/moq-cli/src/play/timeline.rs @@ -617,6 +617,7 @@ pub(super) struct Fit { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; diff --git a/rs/moq-cli/src/play/window.rs b/rs/moq-cli/src/play/window.rs index 085de50a440..35b4691f4c2 100644 --- a/rs/moq-cli/src/play/window.rs +++ b/rs/moq-cli/src/play/window.rs @@ -317,10 +317,8 @@ impl ApplicationHandler for App { display.window.request_redraw(); } } - // winit waits on the host clock, so the deadline converts at this boundary. - Some(deadline) => event_loop.set_control_flow(ControlFlow::WaitUntil( - std::time::Instant::now() + deadline.saturating_duration_since(now), - )), + // winit waits on std's clock. + Some(deadline) => event_loop.set_control_flow(ControlFlow::WaitUntil(deadline.into_std())), None => event_loop.set_control_flow(ControlFlow::Wait), } } diff --git a/rs/moq-cli/src/publish.rs b/rs/moq-cli/src/publish.rs index 66651054d18..d1f810bda0d 100644 --- a/rs/moq-cli/src/publish.rs +++ b/rs/moq-cli/src/publish.rs @@ -605,7 +605,7 @@ async fn decode( // diagnosed by the rate at which these climb, and stdin may never end, so // they have to surface as they accumulate rather than at exit. let mut log = ts::stats::Log::default(); - let mut sampled = tokio::time::Instant::now(); + let mut sampled = moq_clock::now(); let sections = report.as_ref().map(crate::report::Stats::sections); let report_mpegts = |snapshot: &ts::stats::Snapshot| { if let Some(sections) = §ions { @@ -630,7 +630,7 @@ async fn decode( } if sampled.elapsed() >= ts::stats::Log::INTERVAL { - sampled = tokio::time::Instant::now(); + sampled = moq_clock::now(); if let Some(stats) = decoder.stats() { report_mpegts(&stats); log.sample(stats); @@ -787,6 +787,7 @@ impl CaptureArgs { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] pub(crate) mod tests { use std::time::Duration; diff --git a/rs/moq-cli/src/report.rs b/rs/moq-cli/src/report.rs index ae13fb52002..d1a95ef3797 100644 --- a/rs/moq-cli/src/report.rs +++ b/rs/moq-cli/src/report.rs @@ -200,7 +200,7 @@ impl Stats { /// Write a snapshot every interval, for as long as the import runs beside it. pub async fn run(&mut self) -> Infallible { - let mut interval = tokio::time::interval(INTERVAL); + let mut interval = moq_clock::interval(INTERVAL); loop { interval.tick().await; self.write(); @@ -300,7 +300,7 @@ impl Echo { None } }; - let mut interval = tokio::time::interval(INTERVAL); + let mut interval = moq_clock::interval(INTERVAL); loop { tokio::select! { update = next(&mut catalog) => match update { @@ -539,7 +539,7 @@ impl Readers { }; let id = reader.id(); self.drains.spawn(async move { - tokio::time::sleep(DRAIN).await; + moq_clock::sleep(DRAIN).await; (path, id) }); } @@ -594,6 +594,7 @@ async fn read_echo( } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; use tokio::io::{AsyncBufReadExt, BufReader}; diff --git a/rs/moq-cli/src/rtsp.rs b/rs/moq-cli/src/rtsp.rs index 5277d862bbd..d0d9326991c 100644 --- a/rs/moq-cli/src/rtsp.rs +++ b/rs/moq-cli/src/rtsp.rs @@ -52,7 +52,7 @@ pub async fn connect_import(target: ImportTarget, url: Url) -> anyhow::Result<() } tracing::info!(%url, ?backoff, "RTSP reconnecting"); - tokio::time::sleep(backoff).await; + moq_clock::sleep(backoff).await; backoff = (backoff * 2).min(BACKOFF_MAX); } } diff --git a/rs/moq-cli/src/subscribe.rs b/rs/moq-cli/src/subscribe.rs index fb93a4c72b9..ee20cc95a8c 100644 --- a/rs/moq-cli/src/subscribe.rs +++ b/rs/moq-cli/src/subscribe.rs @@ -426,7 +426,7 @@ impl Subscribe { // Reports a track that stops reaching the output while the rest keeps flowing, // the way `publish` reports one that stops arriving. let mut log = moq_mux::container::ts::stats::Log::default(); - let mut sampled = tokio::time::Instant::now(); + let mut sampled = moq_clock::now(); // The export's drop, gap and out-of-tolerance counts, as last logged. let mut reported = (0, 0, 0, 0); let sections = self.sections; @@ -448,7 +448,7 @@ impl Subscribe { stdout.flush().await?; if sampled.elapsed() >= moq_mux::container::ts::stats::Log::INTERVAL { - sampled = tokio::time::Instant::now(); + sampled = moq_clock::now(); let stats = ts.export().stats(); report(&stats); let release = &stats.release; @@ -483,14 +483,14 @@ impl Subscribe { sections.set(|report| report.release = Some(stats.clone())); } }; - let mut sampled = tokio::time::Instant::now(); + let mut sampled = moq_clock::now(); let mut reported = (0, 0, 0, 0); while let Some(object) = release.next().await? { stdout.write_all(&object.payload).await?; stdout.flush().await?; if sampled.elapsed() >= moq_mux::container::ts::stats::Log::INTERVAL { - sampled = tokio::time::Instant::now(); + sampled = moq_clock::now(); let stats = release.stats(); report(&stats); let counts = (stats.dropped, stats.trimmed, stats.gaps, stats.out_of_tolerance); diff --git a/rs/moq-cli/tests/integration/main.rs b/rs/moq-cli/tests/integration/main.rs index b51a69e2858..6a0d059b216 100644 --- a/rs/moq-cli/tests/integration/main.rs +++ b/rs/moq-cli/tests/integration/main.rs @@ -2,6 +2,7 @@ //! //! Each `tests/*.rs` file is its own crate that links this package and its //! dependencies again, so add new integration tests here as a module. +#![allow(clippy::disallowed_methods, clippy::disallowed_types)] mod auth_serve; mod export; diff --git a/rs/moq-clock/src/instant.rs b/rs/moq-clock/src/instant.rs index 2cebeb7c5fc..c52c09eaa87 100644 --- a/rs/moq-clock/src/instant.rs +++ b/rs/moq-clock/src/instant.rs @@ -10,7 +10,8 @@ use std::{ /// import change. Instants are only comparable within one clock: the simulator /// starts at [`Instant::ZERO`], and the runtime backends count from an origin they /// pick once, reading far past zero there so earlier moments stay representable. -/// An instant has no conversion back to the host clock. +/// On native, [`Instant::into_std`] and [`Instant::from_std`] convert at a third-party +/// API that takes std's instants. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Instant(u64); @@ -77,6 +78,29 @@ impl Instant { pub(crate) const fn from_nanos(nanos: u64) -> Self { Self(nanos) } + + /// This instant on std's clock, for a third-party API that takes one. + /// + /// Maps through the runtime backend's origin, as its timers do. That is exact on + /// a running clock. On paused tokio or the simulator it keeps the time between + /// instants, but not their distance from [`std::time::Instant::now`]. + /// + /// # Panics + /// + /// When std's clock cannot represent it, as with a simulated instant near zero + /// on a platform whose std clock starts at boot. + #[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))] + pub fn into_std(self) -> std::time::Instant { + crate::runtime::into_std(self).expect("instant outside std's clock range") + } + + /// The instant `at` names on std's clock, the inverse of [`Instant::into_std`]. + /// + /// Saturates at the clock's range, like a deadline past it. + #[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))] + pub fn from_std(at: std::time::Instant) -> Self { + crate::runtime::from_std(at) + } } impl Add for Instant { diff --git a/rs/moq-clock/src/lib.rs b/rs/moq-clock/src/lib.rs index 6882c7df13d..2f5f0eb9192 100644 --- a/rs/moq-clock/src/lib.rs +++ b/rs/moq-clock/src/lib.rs @@ -43,7 +43,10 @@ pub use deadline::{Deadline, Deadlines, Entered}; pub use installed::Installed; pub use instant::Instant; pub use manual::Manual; -pub use timer::{Elapsed, Interval, MissedTickBehavior, Sleep, Timeout, drive, interval, sleep, sleep_until, timeout}; +pub use timer::{ + Elapsed, Interval, MissedTickBehavior, Sleep, Timeout, drive, interval, interval_at, sleep, sleep_until, timeout, + timeout_at, +}; pub use wall::{OutOfRange, Wall}; /// Run an `async fn` test to completion on [`sim::run`]. diff --git a/rs/moq-clock/src/runtime.rs b/rs/moq-clock/src/runtime.rs index 46f90574fce..166b7c98914 100644 --- a/rs/moq-clock/src/runtime.rs +++ b/rs/moq-clock/src/runtime.rs @@ -89,6 +89,38 @@ fn real_now() -> Instant { now() } +/// The std instant the runtime clock counts from, as [`read`] picks it. +#[cfg(all(feature = "runtime", any(not(target_arch = "wasm32"), target_os = "wasi")))] +fn std_base() -> std::time::Instant { + read().0.into_std() +} + +#[cfg(not(any(feature = "runtime", all(target_arch = "wasm32", not(target_os = "wasi")))))] +fn std_base() -> std::time::Instant { + std_origin().0 +} + +/// `at` on std's clock, through the origin the runtime clock counts from. +#[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))] +pub(crate) fn into_std(at: Instant) -> Option { + let base = std_base(); + match at.since_origin().checked_sub(LEAD) { + Some(after) => base.checked_add(after), + None => base.checked_sub(LEAD - at.since_origin()), + } +} + +/// The inverse of [`into_std`], saturating at the clock's range. +#[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))] +pub(crate) fn from_std(at: std::time::Instant) -> Instant { + let base = std_base(); + let lead = Instant::from_origin(LEAD); + match at.checked_duration_since(base) { + Some(after) => lead.checked_add(after).unwrap_or(Instant::MAX), + None => lead.checked_sub(base - at).unwrap_or(Instant::ZERO), + } +} + /// A host timer for `at`, on the origin it was created with. #[cfg(feature = "runtime")] pub(crate) struct Timer { @@ -315,6 +347,49 @@ mod tests { assert!(instant <= crate::now(), "{instant:?} > {:?}", crate::now()); } + /// On a running clock, a converted instant is the same moment on std's clock. + #[test] + #[allow(clippy::disallowed_methods)] + fn std_conversion_is_exact_on_a_running_clock() { + let before = std::time::Instant::now(); + let now = crate::now(); + let after = std::time::Instant::now(); + let host = now.into_std(); + assert!(before <= host && host <= after, "{before:?} <= {host:?} <= {after:?}"); + assert_eq!(crate::Instant::from_std(host), now); + let earlier = now - Duration::from_secs(3_600); + assert_eq!(crate::Instant::from_std(earlier.into_std()), earlier); + } + + /// On paused tokio, converted instants keep the time between them. + #[test] + fn std_conversion_keeps_paused_durations() { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_time() + .start_paused(true) + .build() + .unwrap(); + runtime.block_on(async { + let start = crate::now(); + let host = start.into_std(); + tokio::time::advance(Duration::from_secs(60)).await; + let later = crate::now(); + assert_eq!(later.into_std() - host, Duration::from_secs(60)); + assert_eq!( + crate::Instant::from_std(host + Duration::from_secs(5)), + start + Duration::from_secs(5) + ); + }); + } + + /// A std instant past the clock's range saturates instead of wrapping. + #[test] + fn std_conversion_saturates() { + let now = crate::now(); + let far = now.into_std() + Duration::from_secs(1 << 40); + assert!(crate::Instant::from_std(far) > now + Duration::from_secs(1 << 33)); + } + /// A fresh clock names moments before the process started, as std's does, so /// looking back from startup never underflows. #[test] diff --git a/rs/moq-clock/src/sim.rs b/rs/moq-clock/src/sim.rs index cc7620b76fb..ebcb6bf33a3 100644 --- a/rs/moq-clock/src/sim.rs +++ b/rs/moq-clock/src/sim.rs @@ -735,6 +735,15 @@ mod tests { assert_eq!(fast, Ok(7)); } + #[crate::test] + async fn timeout_at_ends_at_the_deadline() { + let slow = crate::timeout_at(at(2), crate::sleep(Duration::from_secs(60))).await; + assert_eq!(slow.unwrap_err(), Elapsed); + assert_eq!(crate::now(), at(2)); + let late = crate::timeout_at(at(1), async { 7 }).await; + assert_eq!(late, Ok(7), "a ready future wins even past the deadline"); + } + #[crate::test] async fn advance_wakes_due_timers() { let timer = spawn(crate::sleep(Duration::from_secs(3))); @@ -831,6 +840,14 @@ mod tests { assert_eq!(crate::now(), at(4)); } + #[crate::test] + async fn interval_at_starts_at_its_first_tick() { + let mut ticks = crate::interval_at(at(2), Duration::from_secs(1)); + assert_eq!(ticks.tick().await, at(2)); + assert_eq!(crate::now(), at(2), "nothing ticks before the start"); + assert_eq!(ticks.tick().await, at(3)); + } + #[crate::test] async fn interval_delay_restarts_from_the_late_tick() { let mut ticks = crate::interval(Duration::from_secs(1)); diff --git a/rs/moq-clock/src/timer.rs b/rs/moq-clock/src/timer.rs index 774d9563cd0..ba499e3efb3 100644 --- a/rs/moq-clock/src/timer.rs +++ b/rs/moq-clock/src/timer.rs @@ -158,7 +158,17 @@ pub fn timeout(duration: Duration, future: F) -> Timeout(deadline: Instant, future: F) -> Timeout { + Timeout { + future: Box::pin(future.into_future()), + sleep: sleep_until(deadline), + } +} + +/// The future [`timeout`] and [`timeout_at`] return. pub struct Timeout { future: Pin>, sleep: Sleep, @@ -187,7 +197,7 @@ pub enum MissedTickBehavior { Skip, } -/// Ticks on the ambient clock every period, starting at once. +/// Ticks on the ambient clock every period. pub struct Interval { sleep: Sleep, period: Duration, @@ -200,9 +210,18 @@ pub struct Interval { /// /// When `period` is zero. pub fn interval(period: Duration) -> Interval { + interval_at(crate::now(), period) +} + +/// Tick every `period` on the ambient clock, the first tick at `start`. +/// +/// # Panics +/// +/// When `period` is zero. +pub fn interval_at(start: Instant, period: Duration) -> Interval { assert!(!period.is_zero(), "interval period must be non-zero"); Interval { - sleep: sleep_until(crate::now()), + sleep: sleep_until(start), period, missed: MissedTickBehavior::default(), } diff --git a/rs/moq-e2ee/clippy.toml b/rs/moq-e2ee/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/moq-e2ee/clippy.toml @@ -0,0 +1,23 @@ +# Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. +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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-e2ee/tests/transport.rs b/rs/moq-e2ee/tests/transport.rs index f9828e91444..68665cffdc4 100644 --- a/rs/moq-e2ee/tests/transport.rs +++ b/rs/moq-e2ee/tests/transport.rs @@ -1,4 +1,5 @@ //! Grouped tracks and datagrams on moq-lite and MoQ Transport. +#![allow(clippy::disallowed_methods, clippy::disallowed_types)] mod support; diff --git a/rs/moq-flate/clippy.toml b/rs/moq-flate/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/moq-flate/clippy.toml @@ -0,0 +1,23 @@ +# Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. +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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-gst/Cargo.toml b/rs/moq-gst/Cargo.toml index f1a3cee0081..50156b4ea64 100644 --- a/rs/moq-gst/Cargo.toml +++ b/rs/moq-gst/Cargo.toml @@ -22,6 +22,7 @@ anyhow = { workspace = true, features = ["backtrace"] } bytes = { workspace = true } gst = { package = "gstreamer", version = "0.25" } hang = { workspace = true } +moq-clock = { workspace = true } moq-mux = { workspace = true } moq-net = { workspace = true } moq-tokio = { workspace = true, default-features = true } diff --git a/rs/moq-gst/clippy.toml b/rs/moq-gst/clippy.toml new file mode 100644 index 00000000000..f3f8720ac3f --- /dev/null +++ b/rs/moq-gst/clippy.toml @@ -0,0 +1,23 @@ +# 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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +disallowed-types = [ + { 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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-gst/src/sink/imp.rs b/rs/moq-gst/src/sink/imp.rs index ea6254b51c8..2ecda4e23c3 100644 --- a/rs/moq-gst/src/sink/imp.rs +++ b/rs/moq-gst/src/sink/imp.rs @@ -727,7 +727,7 @@ impl MoqSink { }); let sample = super::wall::Sample { running: reference_running_time, - wall: std::time::SystemTime::now(), + wall: moq_clock::wall().into(), }; let map = buffer.map_readable().map_err(|_| { gst::error!(CAT, "failed to map buffer on pad {}", pad.name()); @@ -1252,6 +1252,7 @@ fn observe_caps( } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use std::sync::Arc; diff --git a/rs/moq-gst/src/sink/pad.rs b/rs/moq-gst/src/sink/pad.rs index 27a18e70530..1506a6e667c 100644 --- a/rs/moq-gst/src/sink/pad.rs +++ b/rs/moq-gst/src/sink/pad.rs @@ -1119,6 +1119,7 @@ pub(crate) fn h264_keyframe_au() -> Bytes { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; diff --git a/rs/moq-gst/src/source/imp.rs b/rs/moq-gst/src/source/imp.rs index 7dae3e7c2a1..dd192b0446e 100644 --- a/rs/moq-gst/src/source/imp.rs +++ b/rs/moq-gst/src/source/imp.rs @@ -1565,6 +1565,7 @@ mod tests { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod session_tests { use std::collections::BTreeMap; use std::sync::Mutex; diff --git a/rs/moq-hls/Cargo.toml b/rs/moq-hls/Cargo.toml index 6b6d9570f47..a38a3a6030c 100644 --- a/rs/moq-hls/Cargo.toml +++ b/rs/moq-hls/Cargo.toml @@ -24,6 +24,7 @@ hang = { workspace = true } humantime = { workspace = true } kio = { workspace = true } m3u8-rs = "6" +moq-clock = { workspace = true } moq-json = { workspace = true } moq-mux = { workspace = true } moq-net = { workspace = true } diff --git a/rs/moq-hls/clippy.toml b/rs/moq-hls/clippy.toml new file mode 100644 index 00000000000..f3f8720ac3f --- /dev/null +++ b/rs/moq-hls/clippy.toml @@ -0,0 +1,23 @@ +# 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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +disallowed-types = [ + { 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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-hls/src/export/mod.rs b/rs/moq-hls/src/export/mod.rs index 8f846c51f08..67dae16cc96 100644 --- a/rs/moq-hls/src/export/mod.rs +++ b/rs/moq-hls/src/export/mod.rs @@ -28,6 +28,7 @@ //! storage. #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod archive_tests; mod history; pub mod master; @@ -331,7 +332,7 @@ impl Broadcaster { Ok(Some(mpd::render_manifest( &mpd::Manifest { availability_start, - publish: SystemTime::now(), + publish: SystemTime::from(moq_clock::wall()), window: self.renditions.window(), finished, video, @@ -409,7 +410,7 @@ async fn watch_catalog( let wait = delay.mul_f64(0.5 + rand::rng().random::() / 2.0); delay = (delay * 2).min(CATALOG_RETRY_MAX); tokio::select! { - _ = tokio::time::sleep(wait) => {} + _ = moq_clock::sleep(wait) => {} _ = kio::wait(|waiter| broadcast.poll_closed(waiter)) => { renditions.close(); return; @@ -597,6 +598,7 @@ async fn watch( } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { /// A millisecond track: the frames written here carry timestamps. fn timed() -> moq_net::track::Info { diff --git a/rs/moq-hls/src/export/renditions.rs b/rs/moq-hls/src/export/renditions.rs index bd5246d7307..31693476378 100644 --- a/rs/moq-hls/src/export/renditions.rs +++ b/rs/moq-hls/src/export/renditions.rs @@ -289,7 +289,11 @@ impl Fanout { }); } if feed.anchor.is_none() { - feed.anchor = Some(SystemTime::now().checked_sub(end).unwrap_or(SystemTime::UNIX_EPOCH)); + feed.anchor = Some( + SystemTime::from(moq_clock::wall()) + .checked_sub(end) + .unwrap_or(SystemTime::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/import.rs b/rs/moq-hls/src/import.rs index e9480985dc9..9b287ac73d8 100644 --- a/rs/moq-hls/src/import.rs +++ b/rs/moq-hls/src/import.rs @@ -644,7 +644,7 @@ impl Import { /// `404` playlist ends the import immediately, since no amount of waiting turns it into a `200`. pub async fn run(&mut self) -> Result<()> { let mut delay = STEP_RETRY_MIN; - let mut deadline = tokio::time::Instant::now() + STEP_RETRY_BUDGET; + let mut deadline = moq_clock::now() + STEP_RETRY_BUDGET; loop { // A step where *nothing* ingested while a rendition was failing is a failed pass wearing @@ -668,7 +668,7 @@ impl Import { Ok(outcome) => { // The source is alive, so the earlier failures no longer describe it. delay = STEP_RETRY_MIN; - deadline = tokio::time::Instant::now() + STEP_RETRY_BUDGET; + deadline = moq_clock::now() + STEP_RETRY_BUDGET; outcome } // A status the origin actually sent is its answer: a 404 playlist is not going to @@ -677,7 +677,7 @@ impl Import { return Err(err); } Err(err) => { - let now = tokio::time::Instant::now(); + let now = moq_clock::now(); if now >= deadline { return Err(err); } @@ -689,7 +689,7 @@ impl Import { .mul_f64(0.5 + rand::rng().random::() / 2.0) .min(deadline - now); delay = (delay * 2).min(STEP_RETRY_MAX); - tokio::time::sleep(wait).await; + moq_clock::sleep(wait).await; continue; } }; @@ -702,7 +702,7 @@ impl Import { "HLS import step complete" ); - tokio::time::sleep(delay).await; + moq_clock::sleep(delay).await; } } @@ -1031,6 +1031,7 @@ fn moq_sequence(discontinuity_sequence: u64, media_sequence: u64) -> Result } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; use std::path::{Path, PathBuf}; diff --git a/rs/moq-hls/src/server/mod.rs b/rs/moq-hls/src/server/mod.rs index 297033031f8..edba91ba14e 100644 --- a/rs/moq-hls/src/server/mod.rs +++ b/rs/moq-hls/src/server/mod.rs @@ -122,13 +122,13 @@ impl Server { Poll::Ready(Some(_)) => Poll::Ready(true), Poll::Pending => follow.poll_synced(waiter).map(|()| false), }); - if !tokio::time::timeout(RESOLVE_TIMEOUT, routed).await.unwrap_or(false) { + if !moq_clock::timeout(RESOLVE_TIMEOUT, routed).await.unwrap_or(false) { return None; } let origin = self.inner.origin.consume(); // A covering dynamic route may never answer, so the request is bounded too. - let broadcast = tokio::time::timeout(RESOLVE_TIMEOUT, origin.request_broadcast(name, None)) + let broadcast = moq_clock::timeout(RESOLVE_TIMEOUT, origin.request_broadcast(name, None)) .await .map_err(|_| tracing::warn!(%name, "timed out resolving broadcast")) .ok()? @@ -269,7 +269,7 @@ mod tests { let origin = produce_origin(); let server = Server::new(origin.consume(), Config::default()); - let start = tokio::time::Instant::now(); + let start = moq_clock::now(); assert!(server.broadcaster("live").await.is_none()); assert_eq!(start.elapsed(), Duration::ZERO); } diff --git a/rs/moq-hls/src/server/routes.rs b/rs/moq-hls/src/server/routes.rs index dda6d035e60..0fb30596c17 100644 --- a/rs/moq-hls/src/server/routes.rs +++ b/rs/moq-hls/src/server/routes.rs @@ -236,7 +236,7 @@ async fn master(server: &Server, broadcast: &str, query: Option<&str>) -> Respon }; // A master listing no variant is unplayable: wait for one that can start, else answer // unavailable. - let _ = tokio::time::timeout(READY_TIMEOUT, broadcaster.advertised()).await; + let _ = moq_clock::timeout(READY_TIMEOUT, broadcaster.advertised()).await; let (video, audio) = broadcaster.variants(query); if video.is_empty() && audio.is_empty() { return not_found(); @@ -248,13 +248,13 @@ async fn manifest(server: &Server, broadcast: &str, query: Option<&str>) -> Resp let Some(broadcaster) = server.broadcaster(broadcast).await else { return not_found(); }; - let _ = tokio::time::timeout(READY_TIMEOUT, broadcaster.ready()).await; + let _ = moq_clock::timeout(READY_TIMEOUT, broadcaster.ready()).await; if broadcaster.is_empty() { return not_found(); } // A manifest whose timelines are all empty confuses players; give the broadcast a moment // to index its first complete segment before answering. - let _ = tokio::time::timeout(READY_TIMEOUT, broadcaster.playable()).await; + let _ = moq_clock::timeout(READY_TIMEOUT, broadcaster.playable()).await; // Each representation names its init by hash, which an inline codec only learns from media. broadcaster.build_inits().await; match broadcaster.manifest(query) { @@ -272,7 +272,7 @@ async fn media(server: &Server, broadcast: &str, kind: Kind, rendition: &str, qu let Some(rendition) = rendition_for(server, broadcast, kind, rendition).await else { return not_found(); }; - match tokio::time::timeout(READY_TIMEOUT, rendition.playlist(range, child_query.as_deref())).await { + match moq_clock::timeout(READY_TIMEOUT, rendition.playlist(range, child_query.as_deref())).await { Ok(Ok(Some(playlist))) => m3u8(playlist), Ok(Ok(None)) | Err(_) => not_found(), Ok(Err(crate::Error::RangeNotDurable | crate::Error::RangeUnavailable(_))) => range_not_satisfiable(), @@ -364,7 +364,7 @@ async fn segment( /// Resolve a rendition, waiting for the catalog to populate. async fn rendition_for(server: &Server, broadcast: &str, kind: Kind, rendition: &str) -> Option> { let broadcaster = server.broadcaster(broadcast).await?; - let _ = tokio::time::timeout(READY_TIMEOUT, broadcaster.ready()).await; + let _ = moq_clock::timeout(READY_TIMEOUT, broadcaster.ready()).await; broadcaster.rendition(kind, rendition) } @@ -427,6 +427,7 @@ fn server_error(err: crate::Error) -> Response { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; diff --git a/rs/moq-ice/Cargo.toml b/rs/moq-ice/Cargo.toml index e34bbdc354c..4fd94b25fcd 100644 --- a/rs/moq-ice/Cargo.toml +++ b/rs/moq-ice/Cargo.toml @@ -13,10 +13,11 @@ keywords = ["webrtc", "ice", "stun", "str0m", "moq"] categories = ["network-programming", "multimedia"] [dependencies] +moq-clock = { workspace = true } str0m = { workspace = true } stun-types = { workspace = true } thiserror = { workspace = true } -tokio = { workspace = true, features = ["macros", "net", "rt", "sync", "time"] } +tokio = { workspace = true, features = ["macros", "net", "rt", "sync"] } tracing = { workspace = true } [dev-dependencies] diff --git a/rs/moq-ice/clippy.toml b/rs/moq-ice/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/moq-ice/clippy.toml @@ -0,0 +1,23 @@ +# Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. +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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-ice/src/agent.rs b/rs/moq-ice/src/agent.rs index 20f310f2e53..e94730a0626 100644 --- a/rs/moq-ice/src/agent.rs +++ b/rs/moq-ice/src/agent.rs @@ -2,8 +2,9 @@ use std::collections::VecDeque; use std::net::{IpAddr, SocketAddr}; use std::ops::{Deref, DerefMut}; use std::sync::Arc; -use std::time::{Duration, Instant}; +use std::time::Duration; +use moq_clock::Instant; use str0m::net::{Protocol, Receive}; use str0m::{Candidate, IceConnectionState, Input, Output, Rtc}; use stun_types::attribute::XorMappedAddress; @@ -253,12 +254,12 @@ impl Agent { self.receive(&data, src); continue; } - _ = tokio::time::sleep(deadline - now) => {} + _ = moq_clock::sleep_until(deadline) => {} } } let now = Instant::now(); - let result = self.change().handle_input(Input::Timeout(now)); + let result = self.change().handle_input(Input::Timeout(now.into_std())); if let Err(err) = result { self.fail(Error::rtc(err)); } @@ -282,8 +283,9 @@ impl Agent { Err(err) => return self.fail(Error::rtc(err)), }; match output { + // str0m runs on std's clock. Output::Timeout(timeout) => { - self.timeout = timeout; + self.timeout = Instant::from_std(timeout); return; } Output::Transmit(transmit) => self.send(&transmit.contents, transmit.destination), @@ -335,7 +337,9 @@ impl Agent { tracing::debug!(%src, len = data.len(), "dropped unrecognized datagram"); return; }; - let result = self.change().handle_input(Input::Receive(Instant::now(), receive)); + let result = self + .change() + .handle_input(Input::Receive(Instant::now().into_std(), receive)); if let Err(err) = result { self.fail(Error::rtc(err)); } @@ -480,7 +484,7 @@ mod tests { locals: vec![local], inbound, }; - let mut agent = Agent::new(Rtc::builder().build(Instant::now()), socket).unwrap(); + let mut agent = Agent::new(Rtc::builder().build(Instant::now().into_std()), socket).unwrap(); // Until tokio has seen the socket writable, a send waits in the outbox. agent.socket.writable().await.unwrap(); @@ -508,7 +512,7 @@ mod tests { udp: socket, locals: vec![local], }; - Agent::new(Rtc::builder().build(Instant::now()), socket).unwrap() + Agent::new(Rtc::builder().build(Instant::now().into_std()), socket).unwrap() } #[tokio::test] diff --git a/rs/moq-json/benches/window.rs b/rs/moq-json/benches/window.rs index e406cbc694a..3f4a42437ec 100644 --- a/rs/moq-json/benches/window.rs +++ b/rs/moq-json/benches/window.rs @@ -4,6 +4,7 @@ //! frames are built outside the measured section. //! //! Run `cargo bench -p moq-json --bench window` and compare the table across revisions. +#![allow(clippy::disallowed_methods, clippy::disallowed_types)] use std::alloc::{GlobalAlloc, Layout, System}; use std::hint::black_box; diff --git a/rs/moq-json/clippy.toml b/rs/moq-json/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/moq-json/clippy.toml @@ -0,0 +1,23 @@ +# Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. +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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-loc/clippy.toml b/rs/moq-loc/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/moq-loc/clippy.toml @@ -0,0 +1,23 @@ +# Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. +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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-msf/clippy.toml b/rs/moq-msf/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/moq-msf/clippy.toml @@ -0,0 +1,23 @@ +# Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. +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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-native/clippy.toml b/rs/moq-native/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/moq-native/clippy.toml @@ -0,0 +1,23 @@ +# Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. +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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-nvenc/clippy.toml b/rs/moq-nvenc/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/moq-nvenc/clippy.toml @@ -0,0 +1,23 @@ +# Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. +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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-pattern/clippy.toml b/rs/moq-pattern/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/moq-pattern/clippy.toml @@ -0,0 +1,23 @@ +# Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. +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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-quic/clippy.toml b/rs/moq-quic/clippy.toml new file mode 100644 index 00000000000..f3f8720ac3f --- /dev/null +++ b/rs/moq-quic/clippy.toml @@ -0,0 +1,23 @@ +# 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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +disallowed-types = [ + { 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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-quic/src/bloom_token_log.rs b/rs/moq-quic/src/bloom_token_log.rs index 2b1648224c2..9150faa4c51 100644 --- a/rs/moq-quic/src/bloom_token_log.rs +++ b/rs/moq-quic/src/bloom_token_log.rs @@ -253,6 +253,7 @@ const DEFAULT_MAX_BYTES: usize = 10 << 20; const DEFAULT_EXPECTED_HITS: u64 = 1_000_000; #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod test { use super::*; use rand::prelude::*; diff --git a/rs/moq-quic/src/config/mod.rs b/rs/moq-quic/src/config/mod.rs index 69f06de8a07..0409b2ffeb0 100644 --- a/rs/moq-quic/src/config/mod.rs +++ b/rs/moq-quic/src/config/mod.rs @@ -405,7 +405,7 @@ impl ServerConfig { /// /// This exists to allow system time to be mocked in tests, or wherever else desired. /// - /// Defaults to [`StdSystemTime`], which simply calls [`SystemTime::now()`](SystemTime::now). + /// Defaults to [`StdSystemTime`], which reads the ambient clock's wall time. pub fn time_source(&mut self, time_source: Arc) -> &mut Self { self.time_source = time_source; self @@ -723,11 +723,11 @@ pub trait TimeSource: Send + Sync { /// Default implementation of [`TimeSource`] /// -/// Implements `now` by calling [`SystemTime::now()`](SystemTime::now). +/// Implements `now` by reading the ambient clock's wall time, [`moq_clock::wall()`]. pub struct StdSystemTime; impl TimeSource for StdSystemTime { fn now(&self) -> SystemTime { - SystemTime::now() + moq_clock::wall().into() } } diff --git a/rs/moq-quic/src/config/transport.rs b/rs/moq-quic/src/config/transport.rs index 4e99cf14bf9..c9574ea4443 100644 --- a/rs/moq-quic/src/config/transport.rs +++ b/rs/moq-quic/src/config/transport.rs @@ -655,7 +655,7 @@ impl QlogConfig { let mut streamer = QlogStreamer::new( self.title, self.description, - std::time::Instant::now(), + moq_clock::now().into_std(), trace, qlog::events::EventImportance::Core, // `Instant` should have sub-microsecond precision on most platforms diff --git a/rs/moq-quic/src/connection/streams/state.rs b/rs/moq-quic/src/connection/streams/state.rs index e823c3a77c7..f2696d89cc4 100644 --- a/rs/moq-quic/src/connection/streams/state.rs +++ b/rs/moq-quic/src/connection/streams/state.rs @@ -1192,6 +1192,7 @@ pub(super) fn get_or_insert_recv(opt: &mut Option, initial_max_data: } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; use crate::{ diff --git a/rs/moq-quic/src/lib.rs b/rs/moq-quic/src/lib.rs index a52b3f2dd32..2fd368abe13 100644 --- a/rs/moq-quic/src/lib.rs +++ b/rs/moq-quic/src/lib.rs @@ -40,6 +40,7 @@ mod entropy; pub mod fuzz; mod range_set; #[cfg(all(test, any(feature = "rustls-aws-lc-rs", feature = "rustls-ring")))] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests; pub mod transport_parameters; mod varint; diff --git a/rs/moq-relay/benches/auth.rs b/rs/moq-relay/benches/auth.rs index 0dd360d2458..1037e606bd8 100644 --- a/rs/moq-relay/benches/auth.rs +++ b/rs/moq-relay/benches/auth.rs @@ -1,6 +1,7 @@ //! Revalidate one token while sweeping unrelated sessions and held credentials, and //! cycle one verification slot while sweeping the waiting tokens and the slot count. //! The real relay/controller runs over loopback TCP; timings include one AUTH round trip. +#![allow(clippy::disallowed_methods, clippy::disallowed_types)] use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; use moq_auth::{Grant, lease}; diff --git a/rs/moq-relay/clippy.toml b/rs/moq-relay/clippy.toml new file mode 100644 index 00000000000..f3f8720ac3f --- /dev/null +++ b/rs/moq-relay/clippy.toml @@ -0,0 +1,23 @@ +# 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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +disallowed-types = [ + { 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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-relay/src/acme.rs b/rs/moq-relay/src/acme.rs index 72ff1b4f83b..46a4be65aab 100644 --- a/rs/moq-relay/src/acme.rs +++ b/rs/moq-relay/src/acme.rs @@ -217,8 +217,8 @@ impl Acme { let health = moq_tokio::accept::Health::new("acme"); // Readiness waits on issuance, so keep extending systemd's start timeout // rather than letting the unit's default kill the relay inside the budget. - let mut extend = tokio::time::interval(EXTEND_INTERVAL); - let deadline = tokio::time::sleep(self.timeout); + let mut extend = moq_clock::interval(EXTEND_INTERVAL); + let deadline = moq_clock::sleep(self.timeout); tokio::pin!(deadline); let mut last = None; let mut issued = false; @@ -261,13 +261,13 @@ impl Acme { let handshake = challenge.accept(stream); // The validator only needs the handshake, then closes. handshakes.spawn(async move { - let _ = tokio::time::timeout(CHALLENGE_TIMEOUT, handshake).await; + let _ = moq_clock::timeout(CHALLENGE_TIMEOUT, handshake).await; }); } } Err(err) => { if let Some(pause) = health.failed(&err) { - tokio::time::sleep(pause).await; + moq_clock::sleep(pause).await; } } }, @@ -332,7 +332,7 @@ impl Failures { let Some(contents) = Cache::read(&self.path)? else { return Ok(Vec::new()); }; - let cutoff = SystemTime::now() - FAILURE_WINDOW; + let cutoff = SystemTime::from(moq_clock::wall()) - FAILURE_WINDOW; let mut recent = Vec::new(); for line in String::from_utf8_lossy(&contents).lines() { let secs: u64 = line @@ -350,7 +350,7 @@ impl Failures { /// Record a failure now, returning the recent ones including it. fn record(&self) -> anyhow::Result> { let mut recent = self.recent()?; - recent.push(SystemTime::now()); + recent.push(SystemTime::from(moq_clock::wall())); let lines: String = recent .iter() .map(|at| format!("{}\n", at.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs())) @@ -370,7 +370,7 @@ impl Failures { fn refuse(&self, failed: &[SystemTime], domains: &str, addr: SocketAddr, last: Option<&str>) -> anyhow::Error { let retry = failed .first() - .map_or(SystemTime::now(), |oldest| *oldest + FAILURE_WINDOW); + .map_or(SystemTime::from(moq_clock::wall()), |oldest| *oldest + FAILURE_WINDOW); 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}", @@ -467,4 +467,5 @@ impl rustls_acme::AccountCache for Cache { } #[cfg(all(test, unix))] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests; diff --git a/rs/moq-relay/src/auth.rs b/rs/moq-relay/src/auth.rs index 21ba21d5d6a..09fda630dfe 100644 --- a/rs/moq-relay/src/auth.rs +++ b/rs/moq-relay/src/auth.rs @@ -1131,6 +1131,7 @@ pub(crate) fn peer(identity: &moq_tokio::tls::PeerIdentity) -> Option, token: &str) -> String { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; use futures::FutureExt; diff --git a/rs/moq-relay/src/cache.rs b/rs/moq-relay/src/cache.rs index 2b387d20fa3..3ab38e254bf 100644 --- a/rs/moq-relay/src/cache.rs +++ b/rs/moq-relay/src/cache.rs @@ -175,8 +175,8 @@ fn total_memory() -> u64 { /// relay's construction shapes. Returns on the first tick after that. async fn governor(pool: cache::PoolWeak, capacity: Option, headroom: u64) { let mut sys = sysinfo::System::new(); - let mut interval = tokio::time::interval(GOVERNOR_INTERVAL); - interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + let mut interval = moq_clock::interval(GOVERNOR_INTERVAL); + interval.set_missed_tick_behavior(moq_clock::MissedTickBehavior::Delay); loop { interval.tick().await; diff --git a/rs/moq-relay/src/cluster.rs b/rs/moq-relay/src/cluster.rs index 9d4fa7aad2c..21486367b99 100644 --- a/rs/moq-relay/src/cluster.rs +++ b/rs/moq-relay/src/cluster.rs @@ -1828,10 +1828,10 @@ impl Cluster { dialed: DialMap, http: ClientWithMiddleware, ) { - let mut tick = tokio::time::interval(CONNECT_API_POLL_INTERVAL); + let mut tick = moq_clock::interval(CONNECT_API_POLL_INTERVAL); // A slow fetch must not bank missed ticks into a catch-up burst; just resume // the cadence from the next whole interval. - tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + tick.set_missed_tick_behavior(moq_clock::MissedTickBehavior::Skip); loop { tick.tick().await; @@ -1964,7 +1964,7 @@ impl Cluster { let mut backoff = base_backoff; loop { - let started = tokio::time::Instant::now(); + let started = moq_clock::now(); let result = self.run_remote_once(&addrs, target).await; let elapsed = started.elapsed(); @@ -1980,7 +1980,7 @@ impl Cluster { } } - tokio::time::sleep(backoff).await; + moq_clock::sleep(backoff).await; } } @@ -2303,6 +2303,7 @@ fn remote_status( } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; use crate::Config as RelayConfig; diff --git a/rs/moq-relay/src/internal.rs b/rs/moq-relay/src/internal.rs index c8c621245df..873ef2aee5f 100644 --- a/rs/moq-relay/src/internal.rs +++ b/rs/moq-relay/src/internal.rs @@ -819,6 +819,7 @@ fn render_uring(out: &mut String, workers: &[UringWorker]) { fn render_uring(_out: &mut String, _workers: &[UringWorker]) {} #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; diff --git a/rs/moq-relay/src/listener.rs b/rs/moq-relay/src/listener.rs index 87ffd12d24a..6cf1fbfd3b7 100644 --- a/rs/moq-relay/src/listener.rs +++ b/rs/moq-relay/src/listener.rs @@ -183,7 +183,7 @@ impl AddrListener for Listener { } Err(err) => { if let Some(delay) = self.health.failed(&err) { - tokio::time::sleep(delay).await; + moq_clock::sleep(delay).await; } } } diff --git a/rs/moq-relay/src/listener/idle.rs b/rs/moq-relay/src/listener/idle.rs index 295454011d5..7f673d80f78 100644 --- a/rs/moq-relay/src/listener/idle.rs +++ b/rs/moq-relay/src/listener/idle.rs @@ -7,6 +7,7 @@ use axum::{ use axum_server::accept::Accept; use futures::{future::BoxFuture, task::AtomicWaker}; use http_body::Body as _; +use moq_clock::{Instant, Sleep}; use std::{ io, pin::Pin, @@ -14,10 +15,7 @@ use std::{ task::{Context, Poll}, time::Duration, }; -use tokio::{ - io::{AsyncRead, AsyncWrite, ReadBuf}, - time::{Instant, Sleep}, -}; +use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use tower_service::Service; /// A connection's accept guard, handed off once to a WebSocket upgrade. @@ -58,7 +56,7 @@ where let since = Instant::now(); Box::pin(async move { let (inner, service) = match timeout.and_then(|timeout| since.checked_add(timeout)) { - Some(deadline) => tokio::time::timeout_at(deadline, accepted) + Some(deadline) => moq_clock::timeout_at(deadline, accepted) .await .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "HTTP connection idle deadline"))??, None => accepted.await?, @@ -72,7 +70,7 @@ where }), wake: AtomicWaker::new(), }); - let timer = Box::pin(tokio::time::sleep(Duration::ZERO)); + let timer = Box::pin(moq_clock::sleep(Duration::ZERO)); Ok(( Io { inner, @@ -231,6 +229,7 @@ impl AsyncWrite for Io { unused_imports, reason = "The benchmark includes this private module without a test harness" )] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; use tokio::io::{AsyncReadExt, AsyncWriteExt}; diff --git a/rs/moq-relay/src/relay.rs b/rs/moq-relay/src/relay.rs index 5dc7a463733..b951e0305fc 100644 --- a/rs/moq-relay/src/relay.rs +++ b/rs/moq-relay/src/relay.rs @@ -825,6 +825,7 @@ async fn serve_listening( } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { #[tokio::test] async fn stun_listener_runs_with_the_relay_and_stops_with_it() { diff --git a/rs/moq-relay/src/session.rs b/rs/moq-relay/src/session.rs index 167569b6600..b32a2fcc6e8 100644 --- a/rs/moq-relay/src/session.rs +++ b/rs/moq-relay/src/session.rs @@ -98,7 +98,7 @@ impl Registry { id.clone(), Entry { request, - started: SystemTime::now(), + started: SystemTime::from(moq_clock::wall()), handle: handle.clone(), }, ); @@ -476,6 +476,7 @@ pub struct Nudged { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; use std::time::Duration; diff --git a/rs/moq-relay/src/shutdown.rs b/rs/moq-relay/src/shutdown.rs index 43c684b5596..7a89feaa5f2 100644 --- a/rs/moq-relay/src/shutdown.rs +++ b/rs/moq-relay/src/shutdown.rs @@ -14,7 +14,8 @@ use std::{sync::Arc, time::Duration}; -use tokio::{sync::watch, time::Instant}; +use moq_clock::Instant; +use tokio::sync::watch; /// Fires the relay-wide shutdown broadcast. Held by `Relay::run` for the OS /// signal path; an embedder clones one to stop the relay from its own task. @@ -130,7 +131,7 @@ impl Observer { Err(_) => None, }; match deadline { - Some(deadline) => tokio::time::sleep_until(deadline).await, + Some(deadline) => moq_clock::sleep_until(deadline).await, None => std::future::pending().await, } } @@ -256,7 +257,7 @@ impl Observer { tokio::select! { biased; _ = session.closed() => return, - () = tokio::time::sleep_until(deadline) => {} + () = moq_clock::sleep_until(deadline) => {} } tracing::debug!("peer did not leave before the drain deadline; closing"); session.abort(moq_net::Error::GoawayTimeout); @@ -302,6 +303,7 @@ impl Drop for Draining { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; diff --git a/rs/moq-relay/src/stun.rs b/rs/moq-relay/src/stun.rs index 1dc0f0e3601..b5bd971935a 100644 --- a/rs/moq-relay/src/stun.rs +++ b/rs/moq-relay/src/stun.rs @@ -7,11 +7,11 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Duration; use anyhow::Context; +use moq_clock::Instant; use serde::{Deserialize, Serialize}; use stun_types::attribute::XorMappedAddress; use stun_types::message::{BINDING, Message, MessageClass, MessageHeader, MessageWriteMutSlice}; use stun_types::prelude::*; -use tokio::time::Instant; /// Configuration for the optional public STUN Binding listener. #[derive(usage_rs::Args, Clone, Debug, Default, Deserialize, Serialize)] @@ -274,6 +274,7 @@ impl Server { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; use stun_types::message::{MessageType, MessageWriteVec}; diff --git a/rs/moq-relay/src/uring.rs b/rs/moq-relay/src/uring.rs index 37938262fa9..0654b065155 100644 --- a/rs/moq-relay/src/uring.rs +++ b/rs/moq-relay/src/uring.rs @@ -874,6 +874,7 @@ async fn serve_request( } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; diff --git a/rs/moq-relay/src/web.rs b/rs/moq-relay/src/web.rs index 1c057b99be1..36bde2e77ca 100644 --- a/rs/moq-relay/src/web.rs +++ b/rs/moq-relay/src/web.rs @@ -345,7 +345,7 @@ impl Web { let state = Arc::get_mut(&mut self.state).expect("with_timeout called after routes were built"); // hyper adds the header timeout to the clock unchecked, so an unreachable // one would panic on every connection. - state.timeout = timeout.filter(|timeout| std::time::Instant::now().checked_add(*timeout).is_some()); + state.timeout = timeout.filter(|timeout| moq_clock::now().checked_add(*timeout).is_some()); self } @@ -1070,11 +1070,11 @@ async fn serve_fetch( tracing::info!(%broadcast, %track, "fetching track"); - let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(30); + let deadline = moq_clock::now() + tokio::time::Duration::from_secs(30); // The lease outlives this handler: the body streams after it returns, so the // response holds the lease and ends it when the last frame is served. - let result = tokio::time::timeout_at(deadline, async { + let result = moq_clock::timeout_at(deadline, async { // NOTE: The auth token is already scoped to the broadcast. // Block until a route covers the broadcast (within the fetch deadline) so // freshly-connected subscribers don't get a spurious 404 before the announce arrives. @@ -1125,7 +1125,7 @@ async fn serve_fetch( /// `end` event carries the outcome. struct ServeGroup { group: moq_net::group::Consumer, - deadline: tokio::time::Instant, + deadline: moq_clock::Instant, /// Taken when the body ends, so the reason is reported once. lease: Option, } @@ -1136,7 +1136,7 @@ impl ServeGroup { return Ok(None); }; tokio::select! { - res = tokio::time::timeout_at(self.deadline, self.group.read_frame()) => match res { + res = moq_clock::timeout_at(self.deadline, self.group.read_frame()) => match res { Ok(res) => Ok(res?.map(|frame| frame.payload)), Err(_) => Err(moq_net::Error::Timeout), }, @@ -1178,6 +1178,7 @@ impl IntoResponse for ServeGroup { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; use rcgen::{CertificateParams, KeyPair}; diff --git a/rs/moq-relay/src/websocket.rs b/rs/moq-relay/src/websocket.rs index b0932506101..8d131f4a23d 100644 --- a/rs/moq-relay/src/websocket.rs +++ b/rs/moq-relay/src/websocket.rs @@ -272,6 +272,7 @@ fn tungstenite_text_to_axum(text: tungstenite::Utf8Bytes) -> axum::extract::ws:: } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; use axum::{Router, extract::WebSocketUpgrade, routing::any}; diff --git a/rs/moq-relay/tests/drills.rs b/rs/moq-relay/tests/drills.rs index e0f3fdc2dc7..480bbe5588a 100644 --- a/rs/moq-relay/tests/drills.rs +++ b/rs/moq-relay/tests/drills.rs @@ -25,6 +25,7 @@ //! drill fails when its recovery behavior is removed, and the loom/fuzz cases //! covering the primitives underneath. #![cfg(all(feature = "quic", feature = "websocket"))] +#![allow(clippy::disallowed_methods, clippy::disallowed_types)] use std::time::Duration; diff --git a/rs/moq-relay/tests/integration/main.rs b/rs/moq-relay/tests/integration/main.rs index a825d426bb9..267afaf80fc 100644 --- a/rs/moq-relay/tests/integration/main.rs +++ b/rs/moq-relay/tests/integration/main.rs @@ -4,6 +4,7 @@ //! dependencies again, so add new integration tests here as a module. //! `drills.rs` stays apart so each drill sensitivity mutation rebuilds only //! the drills. +#![allow(clippy::disallowed_methods, clippy::disallowed_types)] mod auth_embedder; mod auth_lifetime; diff --git a/rs/moq-rtc/Cargo.toml b/rs/moq-rtc/Cargo.toml index 1781b59523c..64728015a93 100644 --- a/rs/moq-rtc/Cargo.toml +++ b/rs/moq-rtc/Cargo.toml @@ -27,6 +27,7 @@ axum = { workspace = true, optional = true } bytes = { workspace = true } hang = { workspace = true } # Drives each str0m connection over its UDP socket. +moq-clock = { workspace = true } moq-ice = { workspace = true } moq-mux = { workspace = true } moq-net = { workspace = true } diff --git a/rs/moq-rtc/clippy.toml b/rs/moq-rtc/clippy.toml new file mode 100644 index 00000000000..f3f8720ac3f --- /dev/null +++ b/rs/moq-rtc/clippy.toml @@ -0,0 +1,23 @@ +# 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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +disallowed-types = [ + { 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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-rtc/src/client/whep.rs b/rs/moq-rtc/src/client/whep.rs index 1b148235f92..8f945c1aac0 100644 --- a/rs/moq-rtc/src/client/whep.rs +++ b/rs/moq-rtc/src/client/whep.rs @@ -6,8 +6,6 @@ //! returned answer, then hands the resulting `str0m::Rtc` to the internal //! session driver in ingest mode (the same sink the WHIP server uses). -use std::time::Instant; - use str0m::{ Candidate, Rtc, change::SdpAnswer, @@ -28,7 +26,7 @@ pub(crate) async fn dial( let sink = Box::new(IngestSink::new(broadcast, config)?); let socket = session::bind_udp(&client.config().ice_candidates).await?; - let mut rtc = Rtc::new(Instant::now()); + let mut rtc = Rtc::new(moq_clock::now().into_std()); for addr in &socket.locals { let cand = Candidate::host(*addr, "udp").map_err(Error::rtc)?; rtc.add_local_candidate(cand); diff --git a/rs/moq-rtc/src/codec/mod.rs b/rs/moq-rtc/src/codec/mod.rs index 4cbf5cabc15..9de1908cada 100644 --- a/rs/moq-rtc/src/codec/mod.rs +++ b/rs/moq-rtc/src/codec/mod.rs @@ -16,6 +16,7 @@ pub mod vp8; pub mod vp9; #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod bitstream_test; use bytes::Bytes; diff --git a/rs/moq-rtc/src/egress.rs b/rs/moq-rtc/src/egress.rs index 72cedcc7a34..ee371aba823 100644 --- a/rs/moq-rtc/src/egress.rs +++ b/rs/moq-rtc/src/egress.rs @@ -12,7 +12,9 @@ //! transport-agnostic. use std::collections::VecDeque; -use std::time::{Duration, Instant}; +use std::time::Duration; + +use moq_clock::Instant; use bytes::Bytes; use hang::catalog::{AudioCodec, VideoCodecKind}; @@ -550,12 +552,13 @@ pub fn dispatch(rtc: &mut str0m::Rtc, request: WriteRequest, wallclock: Instant) payload, mid: _, } = request; - if let Err(err) = writer.write(pt, wallclock, time, payload.to_vec()) { + if let Err(err) = writer.write(pt, wallclock.into_std(), time, payload.to_vec()) { tracing::warn!(%err, "egress write rejected by str0m"); } } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { /// Build an origin producer, spawning its driver on the ambient runtime. fn produce_origin() -> moq_net::origin::Producer { diff --git a/rs/moq-rtc/src/lib.rs b/rs/moq-rtc/src/lib.rs index e7f05fc51db..0f3f1706537 100644 --- a/rs/moq-rtc/src/lib.rs +++ b/rs/moq-rtc/src/lib.rs @@ -77,6 +77,7 @@ pub use error::*; pub use server::{Response, Server, whep, whip}; #[cfg(all(test, feature = "server"))] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use std::time::Duration; diff --git a/rs/moq-rtc/src/server/mux.rs b/rs/moq-rtc/src/server/mux.rs index df5a852ec86..cf7147a0525 100644 --- a/rs/moq-rtc/src/server/mux.rs +++ b/rs/moq-rtc/src/server/mux.rs @@ -208,6 +208,7 @@ fn local_ufrag(data: &[u8]) -> Option { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::time::Duration; diff --git a/rs/moq-rtc/src/server/whep.rs b/rs/moq-rtc/src/server/whep.rs index c8915c19a3c..25f1c1044b8 100644 --- a/rs/moq-rtc/src/server/whep.rs +++ b/rs/moq-rtc/src/server/whep.rs @@ -132,7 +132,7 @@ pub async fn accept( // // Bound the wait for resolution + the first catalog: an unannounced broadcast, or an // announced-but-catalog-less one, would otherwise park this handler forever. - let source = tokio::time::timeout(CATALOG_TIMEOUT, async { + let source = moq_clock::timeout(CATALOG_TIMEOUT, async { let broadcast = subscriber.request_broadcast(broadcast.as_path(), None).await?; EgressSource::new(moq_mux::Source::new(subscriber.clone(), broadcast)).await }) @@ -151,7 +151,7 @@ pub async fn accept( let (creds, inbound, registration) = mux.register(); let mut rtc = session::rtc_config_with_codecs(&codecs) .set_local_ice_credentials(creds) - .build(std::time::Instant::now()); + .build(moq_clock::now().into_std()); for addr in mux.candidates() { let cand = Candidate::host(*addr, "udp").map_err(Error::rtc)?; rtc.add_local_candidate(cand); diff --git a/rs/moq-rtc/src/server/whip.rs b/rs/moq-rtc/src/server/whip.rs index 425b0952f20..bbd0540b68f 100644 --- a/rs/moq-rtc/src/server/whip.rs +++ b/rs/moq-rtc/src/server/whip.rs @@ -136,7 +136,7 @@ pub async fn accept( let (creds, inbound, registration) = mux.register(); let mut rtc = RtcConfig::new() .set_local_ice_credentials(creds) - .build(std::time::Instant::now()); + .build(moq_clock::now().into_std()); for addr in mux.candidates() { let cand = Candidate::host(*addr, "udp").map_err(Error::rtc)?; rtc.add_local_candidate(cand); @@ -202,6 +202,7 @@ fn status_for(err: &Error) -> StatusCode { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use str0m::{ format::Codec, diff --git a/rs/moq-rtc/src/session.rs b/rs/moq-rtc/src/session.rs index e1b90ad4d3e..eaa8c2015b7 100644 --- a/rs/moq-rtc/src/session.rs +++ b/rs/moq-rtc/src/session.rs @@ -11,7 +11,9 @@ use std::collections::{HashMap, HashSet}; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; -use std::time::{Instant, SystemTime, UNIX_EPOCH}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use moq_clock::Instant; use str0m::{Candidate, Event, Rtc}; use tokio::net::UdpSocket; @@ -186,7 +188,9 @@ impl Session { // block; egress sessions never get here so the clock stays untouched. if let MediaRole::Ingest(sink) = &mut self.role { let media_us = media_time_to_micros(&data.time); - let timestamp_us = self.ingest_clock.normalize(data.mid, data.network_time, media_us); + let timestamp_us = + self.ingest_clock + .normalize(data.mid, Instant::from_std(data.network_time), media_us); sink.on_frame( data.mid, codec::Frame { @@ -506,7 +510,7 @@ pub fn rtc_config_with_codecs(codecs: &[str0m::format::Codec]) -> str0m::RtcConf /// [`rtc_config_with_codecs`] directly so it can inject the mux's known /// credentials before building. pub fn rtc_with_codecs(codecs: &[str0m::format::Codec]) -> Rtc { - rtc_config_with_codecs(codecs).build(std::time::Instant::now()) + rtc_config_with_codecs(codecs).build(moq_clock::now().into_std()) } /// Bind an ephemeral UDP socket for a single client session, read by its own diff --git a/rs/moq-rtsp/Cargo.toml b/rs/moq-rtsp/Cargo.toml index 41b4f7b63f6..5d6f54337d4 100644 --- a/rs/moq-rtsp/Cargo.toml +++ b/rs/moq-rtsp/Cargo.toml @@ -14,7 +14,7 @@ categories = ["multimedia", "network-programming", "web-programming"] [features] # A scripted RTSP server for downstream integration tests, such as `moq-cli`'s. -test-support = ["dep:base64", "tokio/io-util", "tokio/macros", "tokio/net", "tokio/rt", "tokio/sync"] +test-support = ["dep:base64", "dep:tokio", "tokio/io-util", "tokio/macros", "tokio/net", "tokio/rt", "tokio/sync"] # Pure library: pulls one RTSP session into a caller's broadcast. The CLI lives in # `moq-cli` (`moq import rtsp`), which owns reconnect and epochs. @@ -22,6 +22,7 @@ test-support = ["dep:base64", "tokio/io-util", "tokio/macros", "tokio/net", "tok base64 = { workspace = true, optional = true } futures = { workspace = true } hang = { workspace = true } +moq-clock = { workspace = true } moq-mux = { workspace = true } moq-net = { workspace = true } # Only for `RedactedUrl`, so the session URL logs without its query. @@ -30,8 +31,7 @@ percent-encoding = { workspace = true } # Pure-Rust RTSP client and RTP depacketizer (H.264, H.265, AAC). retina = "0.4.21" thiserror = { workspace = true } -# Timeouts; retina already runs on tokio. -tokio = { workspace = true, features = ["time"] } +tokio = { workspace = true, optional = true } tracing = { workspace = true } url = { workspace = true } diff --git a/rs/moq-rtsp/clippy.toml b/rs/moq-rtsp/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/moq-rtsp/clippy.toml @@ -0,0 +1,23 @@ +# Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. +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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-rtsp/src/client.rs b/rs/moq-rtsp/src/client.rs index e0fcd9f83fd..76e505d7940 100644 --- a/rs/moq-rtsp/src/client.rs +++ b/rs/moq-rtsp/src/client.rs @@ -225,16 +225,16 @@ impl Client { let result: Result = async { let mut session = self.within(session.play(play)).await??.demuxed()?; tracing::info!(%url, streams = tracks.len(), "RTSP session playing"); - let playing = tokio::time::Instant::now(); + let playing = moq_clock::now(); // Measured from the last frame, so RTCP reports alone cannot keep a dead camera alive. let mut deadline = playing + self.timeout; - while let Some(item) = tokio::time::timeout_at(deadline, session.next()) + while let Some(item) = moq_clock::timeout(deadline - moq_clock::now(), session.next()) .await .map_err(|_| Error::Stalled(self.timeout))? { let item = item?; if matches!(item, CodecItem::VideoFrame(_) | CodecItem::AudioFrame(_)) { - deadline = tokio::time::Instant::now() + self.timeout; + deadline = moq_clock::now() + self.timeout; } if ingest.push(item, session.streams())?.is_some() { tracing::warn!(%url, "RTSP timeline jumped, ending the session"); @@ -264,7 +264,7 @@ impl Client { impl Client { /// Fail `step` once it takes longer than the timeout. async fn within(&self, step: impl Future) -> Result { - tokio::time::timeout(self.timeout, step) + moq_clock::timeout(self.timeout, step) .await .map_err(|_| Error::Stalled(self.timeout)) } @@ -371,11 +371,11 @@ struct Stream { track: Track, /// The previous frame's timestamp, in the stream's clock units since the session start, and /// when it arrived. - last: Option<(i64, std::time::Instant)>, + last: Option<(i64, moq_clock::Instant)>, /// Whether a keyframe has been published (video) or the session started (audio). started: bool, /// When a lost packet broke the video's reference chain, so it waits for a keyframe. - held: Option, + held: Option, /// Whether retina's parameter sets still need inserting: until the splitter emits a keyframe /// carrying them, after which it re-inserts them ahead of every keyframe itself. fresh: bool, @@ -419,7 +419,7 @@ impl Ingest { frame.timestamp(), frame.data(), frame.has_new_parameters(), - frame.end_ctx().received(), + moq_clock::Instant::from_std(frame.end_ctx().received()), frame.loss(), ), CodecItem::AudioFrame(frame) => ( @@ -427,7 +427,7 @@ impl Ingest { frame.timestamp(), frame.data(), false, - frame.ctx().received(), + moq_clock::Instant::from_std(frame.ctx().received()), // AAC packets decode alone, and the decoder conceals a lost one. 0, ), @@ -470,7 +470,7 @@ impl Ingest { // access unit is damaged too, even when it is a keyframe, so drop it. if stream.started && stream.held.is_none() { tracing::warn!(stream_id, loss, "RTP packets lost, waiting for the next keyframe"); - stream.held = Some(tokio::time::Instant::now()); + stream.held = Some(moq_clock::now()); } video.reset(); return Ok(None); @@ -514,7 +514,7 @@ impl Ingest { /// Whether a video stream has waited longer than `timeout` for a keyframe: its first since /// `playing`, or its next since a loss held it. - fn awaiting_keyframe(&self, playing: tokio::time::Instant, timeout: std::time::Duration) -> bool { + fn awaiting_keyframe(&self, playing: moq_clock::Instant, timeout: std::time::Duration) -> bool { self.streams.iter().flatten().any(|stream| { let since = match stream.held { Some(held) => held, @@ -543,6 +543,7 @@ impl Ingest { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use std::time::Duration; diff --git a/rs/moq-shaper/Cargo.toml b/rs/moq-shaper/Cargo.toml index 232fb5c1282..3bbc9af171d 100644 --- a/rs/moq-shaper/Cargo.toml +++ b/rs/moq-shaper/Cargo.toml @@ -25,6 +25,7 @@ anyhow = { workspace = true } clap = { workspace = true } humantime = { workspace = true } humantime-serde = { workspace = true } +moq-clock = { workspace = true } rand = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/rs/moq-shaper/clippy.toml b/rs/moq-shaper/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/moq-shaper/clippy.toml @@ -0,0 +1,23 @@ +# Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. +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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-shaper/src/lib.rs b/rs/moq-shaper/src/lib.rs index 1c1c28ce0fa..8a7eb2a0812 100644 --- a/rs/moq-shaper/src/lib.rs +++ b/rs/moq-shaper/src/lib.rs @@ -44,11 +44,12 @@ pub use preset::Preset; use anyhow::Context; #[cfg(test)] use mem::UdpSocket; +use moq_clock::Instant; use rand::{RngExt, SeedableRng, rngs::Xoshiro256PlusPlus}; use serde::{Deserialize, Serialize}; #[cfg(not(test))] use tokio::net::UdpSocket; -use tokio::{sync::mpsc, task::JoinSet, time::Instant}; +use tokio::{sync::mpsc, task::JoinSet}; /// How one direction of the path treats each datagram. /// @@ -897,7 +898,7 @@ async fn deliver( None => ready.push(parcel), } } - _ = tokio::time::sleep_until(wake.unwrap_or_else(Instant::now)), if wake.is_some() => { + _ = moq_clock::sleep_until(wake.unwrap_or_else(Instant::now)), if wake.is_some() => { // The window closes a batch that never filled. if let Some(closes) = held.closes.filter(|&closes| closes <= Instant::now()) { held.release(closes, &mut ready, &tally[direction]); @@ -1237,6 +1238,7 @@ fn gaussian(rng: &mut Xoshiro256PlusPlus) -> f64 { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; diff --git a/rs/moq-shaper/src/main.rs b/rs/moq-shaper/src/main.rs index c16eb30578c..1c652de50f8 100644 --- a/rs/moq-shaper/src/main.rs +++ b/rs/moq-shaper/src/main.rs @@ -128,7 +128,7 @@ async fn main() -> anyhow::Result<()> { // The first tick is a full period in, so a line reports traffic, not the start. let mut interval = args .report_interval - .map(|period| tokio::time::interval_at(tokio::time::Instant::now() + period, period)); + .map(|period| moq_clock::interval_at(moq_clock::now() + period, period)); let shutdown = shutdown(); tokio::pin!(shutdown); loop { @@ -201,7 +201,7 @@ struct Report<'a> { } /// The next report tick, or never without an interval. -async fn tick(interval: &mut Option) { +async fn tick(interval: &mut Option) { match interval { Some(interval) => { interval.tick().await; diff --git a/rs/moq-sock/clippy.toml b/rs/moq-sock/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/moq-sock/clippy.toml @@ -0,0 +1,23 @@ +# Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. +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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-sock/src/shard.rs b/rs/moq-sock/src/shard.rs index 861cc299e34..1996199819f 100644 --- a/rs/moq-sock/src/shard.rs +++ b/rs/moq-sock/src/shard.rs @@ -593,6 +593,7 @@ fn program(count: u16) -> [libc::sock_filter; 18] { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; diff --git a/rs/moq-sock/tests/udp/main.rs b/rs/moq-sock/tests/udp/main.rs index 00fe7c43216..30900ccbc32 100644 --- a/rs/moq-sock/tests/udp/main.rs +++ b/rs/moq-sock/tests/udp/main.rs @@ -1,3 +1,4 @@ +#![allow(clippy::disallowed_methods, clippy::disallowed_types)] #[cfg(apple)] use std::io::{self, IoSlice}; #[cfg(not(any( diff --git a/rs/moq-srt/clippy.toml b/rs/moq-srt/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/moq-srt/clippy.toml @@ -0,0 +1,23 @@ +# Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. +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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-srt/src/dial.rs b/rs/moq-srt/src/dial.rs index 7162daa7c5d..710377d518e 100644 --- a/rs/moq-srt/src/dial.rs +++ b/rs/moq-srt/src/dial.rs @@ -184,6 +184,7 @@ impl Mode { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { /// Build an origin producer, spawning its driver on the ambient runtime. fn produce_origin() -> moq_net::origin::Producer { diff --git a/rs/moq-srt/src/server.rs b/rs/moq-srt/src/server.rs index c51096223f1..40609ed6d72 100644 --- a/rs/moq-srt/src/server.rs +++ b/rs/moq-srt/src/server.rs @@ -20,7 +20,7 @@ //! everything and routes by prefix, use [`crate::run`]. use std::net::SocketAddr; -use std::time::{Duration, Instant as StdInstant}; +use std::time::Duration; use futures::{SinkExt, StreamExt}; use moq_mux::container::Frame; @@ -582,30 +582,21 @@ pub(crate) async fn serve_subscribe( }; // Sample the muxer's generation alongside the frame it describes, so a new // program clock re-anchors the pacing rather than mapping the new timeline - // through the old anchor. + // through the old anchor. srt-tokio paces on std's clock, where a late payload + // keeps its past instant, so TSBPD still sees its spacing from its neighbors. for (at, payload) in egress.push(&frame, subscriber.discontinuity(), moq_net::time::now()) { - socket.send((host_instant(at), payload)).await?; + socket.send((at.into_std(), payload)).await?; } } if let Some((at, payload)) = egress.flush() { - socket.send((host_instant(at), payload)).await?; + socket.send((at.into_std(), payload)).await?; } socket.close().await?; Ok(()) } -/// The std instant `at` names, since srt-tokio paces on std's clock. A late payload -/// keeps its past instant, so TSBPD still sees its spacing from its neighbors. -fn host_instant(at: Instant) -> StdInstant { - let (now, host) = (moq_net::time::now(), StdInstant::now()); - match at.checked_duration_since(now) { - Some(ahead) => host + ahead, - None => host.checked_sub(now - at).unwrap_or(host), - } -} - /// Clamp a paced send instant up to the connection's first one, seeding that floor /// on the first call. /// @@ -661,20 +652,14 @@ fn parse_stream_id(stream_id: Option<&StreamId>) -> Option<(String, ConnectionMo } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { + use std::time::Instant as StdInstant; + use super::*; use bytes::Bytes; use std::time::Duration; - /// A late payload keeps its spacing on std's clock instead of collapsing onto now. - #[test] - fn a_late_payload_keeps_its_past_host_instant() { - let now = StdInstant::now(); - let late = host_instant(moq_net::time::now() - Duration::from_millis(100)); - assert!(late < now, "{late:?} should precede {now:?}"); - assert!(host_instant(moq_net::time::now() + Duration::from_millis(100)) > now); - } - /// Regression for #2978: a frame that completes a chunk must not re-stamp bytes /// already buffered from an earlier pacing instant. #[test] diff --git a/rs/moq-srt/src/ts.rs b/rs/moq-srt/src/ts.rs index 662033e2925..8ba641d3c43 100644 --- a/rs/moq-srt/src/ts.rs +++ b/rs/moq-srt/src/ts.rs @@ -41,7 +41,7 @@ pub struct Publisher { // The importer's per-stream counters, logged as `moq import ts` logs them, under a // span naming the path, since one server carries many ingests. log: ts::stats::Log, - sampled: tokio::time::Instant, + sampled: moq_net::time::Instant, span: tracing::Span, } @@ -99,7 +99,7 @@ impl Publisher { Ok(Self { importer, log: ts::stats::Log::default(), - sampled: tokio::time::Instant::now(), + sampled: moq_net::time::now(), span: tracing::info_span!("srt", %path), }) } @@ -117,7 +117,7 @@ impl Publisher { } .map_err(moq_mux::Error::from)?; if self.sampled.elapsed() >= ts::stats::Log::INTERVAL { - self.sampled = tokio::time::Instant::now(); + self.sampled = moq_net::time::now(); let _span = self.span.enter(); self.log.sample(self.stats()); } @@ -242,6 +242,7 @@ impl Subscriber { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use moq_mux::catalog::hang::Container; use moq_mux::catalog::{CatalogFormat, Stream}; diff --git a/rs/moq-tokio/clippy.toml b/rs/moq-tokio/clippy.toml new file mode 100644 index 00000000000..f3f8720ac3f --- /dev/null +++ b/rs/moq-tokio/clippy.toml @@ -0,0 +1,23 @@ +# 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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +disallowed-types = [ + { 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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-tokio/examples/chat.rs b/rs/moq-tokio/examples/chat.rs index 609c0e707cd..7e025da587e 100644 --- a/rs/moq-tokio/examples/chat.rs +++ b/rs/moq-tokio/examples/chat.rs @@ -73,7 +73,7 @@ async fn run_broadcast(origin: moq_net::origin::Producer) -> anyhow::Result<()> tracing::info!("wrote hello + world"); // Sleep before sending our next message. - tokio::time::sleep(tokio::time::Duration::from_secs(10)).await; + moq_clock::sleep(tokio::time::Duration::from_secs(10)).await; // There's also a helper method to create a group with a single frame. track.write_frame( @@ -83,7 +83,7 @@ async fn run_broadcast(origin: moq_net::origin::Producer) -> anyhow::Result<()> tracing::info!("wrote foobarbaz"); // Sleep before exiting and closing the broadcast. - tokio::time::sleep(tokio::time::Duration::from_secs(10)).await; + moq_clock::sleep(tokio::time::Duration::from_secs(10)).await; // End the broadcast. Dropping the producer does the same; closing is explicit. broadcast.close(); diff --git a/rs/moq-tokio/examples/clock.rs b/rs/moq-tokio/examples/clock.rs index df86aef0436..4a6a78703eb 100644 --- a/rs/moq-tokio/examples/clock.rs +++ b/rs/moq-tokio/examples/clock.rs @@ -163,7 +163,7 @@ impl Publisher { let next = next.with_second(0).unwrap().with_nanosecond(0).unwrap(); let delay = (next - now).to_std().unwrap(); - tokio::time::sleep(delay).await; + moq_clock::sleep(delay).await; now = next; // just assume we didn't undersleep } @@ -183,7 +183,7 @@ impl Publisher { let next = next.with_nanosecond(0).unwrap(); let delay = (next - now).to_std().unwrap(); - tokio::time::sleep(delay).await; + moq_clock::sleep(delay).await; // Get the current time again to check if we overslept let actual = Utc::now(); diff --git a/rs/moq-tokio/src/client.rs b/rs/moq-tokio/src/client.rs index a0ca66921b6..1063777a363 100644 --- a/rs/moq-tokio/src/client.rs +++ b/rs/moq-tokio/src/client.rs @@ -323,7 +323,7 @@ impl Client { let session = match self.timeout.is_zero() { true => attempt.await?, - false => tokio::time::timeout(self.timeout, attempt) + false => moq_clock::timeout(self.timeout, attempt) .await .map_err(|_| Error::ConnectTimeout(self.timeout))??, }; @@ -370,7 +370,7 @@ impl Client { // arm was still pending. let dialed = match self.timeout.is_zero() { true => attempt.await?, - false => match tokio::time::timeout(self.timeout, attempt).await { + false => match moq_clock::timeout(self.timeout, attempt).await { Ok(res) => res?, Err(_) => return Err(Error::ConnectTimeout(self.timeout)), }, @@ -795,6 +795,7 @@ async fn connect_session( } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; diff --git a/rs/moq-tokio/src/connection.rs b/rs/moq-tokio/src/connection.rs index ddf962cfb30..416c90dd8ef 100644 --- a/rs/moq-tokio/src/connection.rs +++ b/rs/moq-tokio/src/connection.rs @@ -492,7 +492,7 @@ struct State { session: Option, /// The loop's [`Draining`] predecessor and its handover deadline, so /// [`Connection::close`] drains it too without overstaying that window. - predecessor: Option<(moq_net::Session, tokio::time::Instant)>, + predecessor: Option<(moq_net::Session, moq_clock::Instant)>, } /// The producer side of everything a [`Connection`] handle can observe. @@ -832,7 +832,7 @@ impl Connection { let mut close = std::pin::pin!(session.close()); tokio::select! { res = &mut close => res, - _ = tokio::time::sleep_until(deadline) => { + _ = moq_clock::sleep_until(deadline) => { abort.abort(moq_net::Error::GoawayTimeout); close.await } @@ -870,7 +870,7 @@ impl Connection { shared.connected(&dialed.session, dialed.transport); let session = dialed.session; - let connected = tokio::time::Instant::now(); + let connected = moq_clock::now(); // Wait for the session to end, forwarding its bandwidth estimates into the // persistent producers meanwhile so consumers track the live stats across the // connection, and draining any predecessor left over from a migration. @@ -1005,7 +1005,7 @@ impl Connection { if restarting { // After the sleep, so the window counts only the time after the // peer stops answering. - retry.start = tokio::time::Instant::now(); + retry.start = moq_clock::now(); } continue; } @@ -1122,7 +1122,7 @@ impl Connection { let dialed = match attempt_timeout(index, candidates.len()) { None => dialed.await, - Some(limit) => match tokio::time::timeout(limit, dialed).await { + Some(limit) => match moq_clock::timeout(limit, dialed).await { Ok(dialed) => dialed, Err(_) => Err(Error::Reconnect(format!("timed out connecting to {}", Endpoint(url)))), }, @@ -1317,7 +1317,7 @@ struct Retry { /// The wait before the next attempt, before jitter. delay: Duration, /// When this run of failures began; the give-up timeout counts from here. - start: tokio::time::Instant, + start: moq_clock::Instant, /// The latest failure, so giving up reports a real cause. last_error: Option, } @@ -1326,7 +1326,7 @@ impl Retry { fn new(initial: Duration) -> Self { Self { delay: initial, - start: tokio::time::Instant::now(), + start: moq_clock::now(), last_error: None, } } @@ -1352,7 +1352,7 @@ fn timeout_error(timeout: Duration, last_error: Option<&Error>) -> Error { } /// Jitter the next delay and cap it at the retry window. `None` means the window is exhausted. -fn retry_wait(delay: Duration, retry_start: tokio::time::Instant, timeout: Duration) -> Option { +fn retry_wait(delay: Duration, retry_start: moq_clock::Instant, timeout: Duration) -> Option { let wait = delay.mul_f64(0.5 + rand::rng().random::() / 2.0); if timeout.is_zero() { return Some(wait); @@ -1432,14 +1432,14 @@ enum Ended { struct Draining { session: moq_net::Session, closed: std::pin::Pin + Send>>, - deadline: std::pin::Pin>, + deadline: std::pin::Pin>, /// Mirrors the session into [`State::predecessor`] for as long as this lives. state: kio::Producer, } impl Draining { fn new(session: moq_net::Session, handover: Duration, state: &kio::Producer) -> Self { - let deadline = Box::pin(tokio::time::sleep(handover)); + let deadline = Box::pin(moq_clock::sleep(handover)); if let Ok(mut state) = state.write() { state.predecessor = Some((session.clone(), deadline.deadline())); } @@ -1509,7 +1509,7 @@ fn poll_draining(draining: &mut Option, waiter: &kio::Waiter) -> bool /// to reach would leave the old session holding its connection well past the /// handover window. async fn sleep_draining(delay: Duration, draining: &mut Option, shared: &Shared) { - let mut sleep = std::pin::pin!(tokio::time::sleep(delay)); + let mut sleep = std::pin::pin!(moq_clock::sleep(delay)); kio::wait(|waiter| { // Nothing is serving once it retires: the predecessor closed or overstayed // its handover, and the replacement is still a dial away. Leaving the state @@ -1641,6 +1641,7 @@ fn terminal(state: &State) -> Error { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; diff --git a/rs/moq-tokio/src/connection/auth.rs b/rs/moq-tokio/src/connection/auth.rs index ea686213d3a..76b8b1b97cd 100644 --- a/rs/moq-tokio/src/connection/auth.rs +++ b/rs/moq-tokio/src/connection/auth.rs @@ -313,7 +313,7 @@ async fn present( let attempt = async { if opening.is_none() { if let Some(delay) = delay { - tokio::time::sleep(delay).await; + moq_clock::sleep(delay).await; } let handle = session.auth(); let bytes = replay.bytes.clone(); @@ -401,6 +401,7 @@ async fn present( } #[cfg(all(test, feature = "tcp"))] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; diff --git a/rs/moq-tokio/src/failover.rs b/rs/moq-tokio/src/failover.rs index 51d8b1c8e6b..da290786ad9 100644 --- a/rs/moq-tokio/src/failover.rs +++ b/rs/moq-tokio/src/failover.rs @@ -108,7 +108,7 @@ where // When the next attempt may start: the first as soon as an address resolves, // each later one a stagger after the one before it. - let mut ready = tokio::time::Instant::now(); + let mut ready = moq_clock::now(); let mut next_index = 0; let mut start = |addr: SocketAddr, attempts: &mut FuturesUnordered<_>| { @@ -151,7 +151,7 @@ where failures.push((index, Attempt { addr, error: err })); // A failure starts the next candidate immediately (RFC 8305 // section 5) rather than waiting out the stagger delay. - ready = tokio::time::Instant::now(); + ready = moq_clock::now(); } } } @@ -162,7 +162,7 @@ where match addr { Some(addr) => { start(addr, &mut attempts); - ready = tokio::time::Instant::now() + delay; + ready = moq_clock::now() + delay; } None => exhausted = true, } @@ -175,8 +175,8 @@ where /// /// Resolution can outlast the stagger, in which case the attempt starts as soon /// as an address lands. -async fn pull(candidates: &mut Candidates, ready: tokio::time::Instant) -> Option { - tokio::time::sleep_until(ready).await; +async fn pull(candidates: &mut Candidates, ready: moq_clock::Instant) -> Option { + moq_clock::sleep_until(ready).await; candidates.next().await } @@ -190,6 +190,7 @@ fn collapse(mut failures: Vec>) -> E { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; use crate::connect::DEFAULT_RACE; diff --git a/rs/moq-tokio/src/iroh.rs b/rs/moq-tokio/src/iroh.rs index 7bbb6a88c09..e049c09fc3d 100644 --- a/rs/moq-tokio/src/iroh.rs +++ b/rs/moq-tokio/src/iroh.rs @@ -33,6 +33,8 @@ fn congestion_factory(family: CongestionControl) -> Arc, _: std::time::Instant, _: u16) -> Box { Box::new(*self) @@ -492,6 +495,7 @@ fn url_set_scheme(url: Url, scheme: &str) -> Result { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; diff --git a/rs/moq-tokio/src/jemalloc.rs b/rs/moq-tokio/src/jemalloc.rs index 41fed46dded..604590e744f 100644 --- a/rs/moq-tokio/src/jemalloc.rs +++ b/rs/moq-tokio/src/jemalloc.rs @@ -98,6 +98,7 @@ pub async fn run() -> crate::Result<()> { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { const USR1_CHILD: &str = "MOQ_NATIVE_USR1_CHILD"; diff --git a/rs/moq-tokio/src/listen.rs b/rs/moq-tokio/src/listen.rs index 5fe86304b76..3c14ca6fa3e 100644 --- a/rs/moq-tokio/src/listen.rs +++ b/rs/moq-tokio/src/listen.rs @@ -558,7 +558,7 @@ impl Config { .map(Into::into) .or(self.timeout) .unwrap_or(DEFAULT_TIMEOUT); - (!timeout.is_zero() && std::time::Instant::now().checked_add(timeout).is_some()).then_some(timeout) + (!timeout.is_zero() && moq_clock::now().checked_add(timeout).is_some()).then_some(timeout) } #[cfg(feature = "quic")] diff --git a/rs/moq-tokio/src/mdns.rs b/rs/moq-tokio/src/mdns.rs index 0633aa8b562..fffe6b57751 100644 --- a/rs/moq-tokio/src/mdns.rs +++ b/rs/moq-tokio/src/mdns.rs @@ -712,12 +712,12 @@ fn addr_url(addr: SocketAddr) -> Option { /// refusing to start over one of those would be wrong; an error only decides the /// outcome if *nothing* announces. async fn announced(monitor: &mdns_sd::Receiver) -> Result<()> { - let deadline = tokio::time::Instant::now() + ANNOUNCE_TIMEOUT; + let deadline = moq_clock::now() + ANNOUNCE_TIMEOUT; // Kept so a total failure reports why rather than just "timed out". let mut failure = None; loop { - let event = match tokio::time::timeout_at(deadline, monitor.recv_async()).await { + let event = match moq_clock::timeout_at(deadline, monitor.recv_async()).await { Ok(Ok(event)) => event, // The daemon died, or nothing announced in time. Either way the mesh is // not live, which is exactly what the caller is gating on. @@ -771,6 +771,7 @@ fn instance_id(fullname: &str) -> Option<&str> { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; diff --git a/rs/moq-tokio/src/quic/backend.rs b/rs/moq-tokio/src/quic/backend.rs index e7f5b64cb9b..17a5c03145c 100644 --- a/rs/moq-tokio/src/quic/backend.rs +++ b/rs/moq-tokio/src/quic/backend.rs @@ -1047,6 +1047,7 @@ impl driver::ConnectionIdGenerator for ServerIdGenerator { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; use url::Url; diff --git a/rs/moq-tokio/src/quic/driver/mod.rs b/rs/moq-tokio/src/quic/driver/mod.rs index a0fb8d6781c..a8081009129 100644 --- a/rs/moq-tokio/src/quic/driver/mod.rs +++ b/rs/moq-tokio/src/quic/driver/mod.rs @@ -89,6 +89,7 @@ pub use crate::quic::driver::send_group::{SendGroup, SendOptions}; pub use crate::quic::driver::send_stream::{SendStream, StoppedError, WriteError}; #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests; #[derive(Debug)] diff --git a/rs/moq-tokio/src/quic/web/session.rs b/rs/moq-tokio/src/quic/web/session.rs index 5215933272a..682a2cf44d4 100644 --- a/rs/moq-tokio/src/quic/web/session.rs +++ b/rs/moq-tokio/src/quic/web/session.rs @@ -492,7 +492,7 @@ impl Session { } // Wait for the peer to close the CONNECT stream after receiving the capsule. - if tokio::time::timeout(timeout, self.conn.closed()).await.is_err() { + if moq_clock::timeout(timeout, self.conn.closed()).await.is_err() { tracing::debug!("timeout waiting for peer to close; force-closing connection"); self.conn.close(http3_code, b""); } @@ -1036,6 +1036,7 @@ impl web_transport_trait::Session for Session { } #[cfg(all(test, any(feature = "aws-lc-rs", feature = "ring")))] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use std::{ io::{self, IoSliceMut}, diff --git a/rs/moq-tokio/src/resolve.rs b/rs/moq-tokio/src/resolve.rs index 2ce9408e11c..26844fd0f8d 100644 --- a/rs/moq-tokio/src/resolve.rs +++ b/rs/moq-tokio/src/resolve.rs @@ -329,7 +329,7 @@ impl Candidates { // stagger between attempts dwarfs this. if self.count == 0 && !self.delayed && self.full.pending() { self.delayed = true; - let _ = tokio::time::timeout(self.delay, self.answer_full()).await; + let _ = moq_clock::timeout(self.delay, self.answer_full()).await; continue; } @@ -560,6 +560,7 @@ impl Candidates { /// afresh needs a name whose answer changes between dials. Entries carry the /// port too, so two servers on one loopback address can stand in for two hosts. #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] pub(crate) mod hosts { use std::collections::HashMap; use std::net::SocketAddr; @@ -588,7 +589,7 @@ impl Query { Self { call: Some(tokio::spawn(async move { - tokio::time::sleep(delay).await; + moq_clock::sleep(delay).await; Ok(addrs) })), ..Default::default() @@ -597,6 +598,7 @@ impl Query { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; diff --git a/rs/moq-tokio/src/server.rs b/rs/moq-tokio/src/server.rs index b174ef82b16..92a9b01a817 100644 --- a/rs/moq-tokio/src/server.rs +++ b/rs/moq-tokio/src/server.rs @@ -909,9 +909,7 @@ impl Listener { if !server.versions.alpns().contains(&peer.protocol()) { return Err(WebRtcError::Protocol(peer.protocol().to_string()).into()); } - let deadline = server - .timeout - .and_then(|timeout| tokio::time::Instant::now().checked_add(timeout)); + let deadline = server.timeout.and_then(|timeout| moq_clock::now().checked_add(timeout)); let handshake = async { let opened = peer.channel().await?; @@ -1034,8 +1032,8 @@ struct Setup { impl Setup { /// When a connection accepted now must finish its handshake, or `None` to wait /// forever, including past the clock's range. - fn deadline(&self) -> Option { - tokio::time::Instant::now().checked_add(self.timeout?) + fn deadline(&self) -> Option { + moq_clock::now().checked_add(self.timeout?) } } @@ -1054,7 +1052,7 @@ async fn accept_request( server: &moq_net::Server, session: S, binding: moq_net::transport::Binding, - deadline: Option, + deadline: Option, ) -> crate::Result<(PendingRequest>, Option)> where S: crate::transport::Grouped, @@ -1073,7 +1071,7 @@ where pub(crate) async fn accept_websocket( session: qmux::Session, options: crate::websocket::Options, - deadline: Option, + deadline: Option, ) -> crate::Result { let (request, deadline) = accept_request(&options.server, session, moq_net::transport::Binding::Uri, deadline).await?; @@ -1095,7 +1093,7 @@ pub(crate) async fn accept_websocket( /// When an accepted connection's handshake must be done, and how to tell the peer /// it wasn't. struct Deadline { - at: tokio::time::Instant, + at: moq_clock::Instant, /// Closes the session with the timeout code. close: Box, } @@ -1109,7 +1107,7 @@ impl Deadline { all(feature = "uds", unix), feature = "webrtc" ))] - fn new(at: tokio::time::Instant, session: S) -> Self + fn new(at: moq_clock::Instant, session: S) -> Self where S: web_transport_trait::poll::Session + Clone + Send + Sync + 'static, { @@ -1131,7 +1129,7 @@ impl Deadline { let Some(deadline) = deadline else { return handshake.await; }; - match tokio::time::timeout_at(deadline.at, handshake).await { + match moq_clock::timeout_at(deadline.at, handshake).await { Ok(res) => res, Err(_) => { (deadline.close)(); @@ -1154,7 +1152,7 @@ impl Deadline { feature = "webrtc" ))] async fn within( - deadline: Option, + deadline: Option, handshake: impl Future>, ) -> crate::Result where @@ -1163,7 +1161,7 @@ where let Some(deadline) = deadline else { return Ok(handshake.await?); }; - match tokio::time::timeout_at(deadline, handshake).await { + match moq_clock::timeout_at(deadline, handshake).await { Ok(res) => Ok(res?), Err(_) => Err(moq_net::Error::Timeout.into()), } @@ -1549,7 +1547,7 @@ fn spawn_unix_loop( struct Incoming { transport: Transport, link: Link, - deadline: Option, + deadline: Option, active: moq_net::server::Active, } @@ -1951,6 +1949,7 @@ impl Request { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; diff --git a/rs/moq-tokio/src/tcp.rs b/rs/moq-tokio/src/tcp.rs index 467777d52e2..444ac051841 100644 --- a/rs/moq-tokio/src/tcp.rs +++ b/rs/moq-tokio/src/tcp.rs @@ -336,7 +336,7 @@ impl Listener { } Err(err) => { if let Some(delay) = self.health.failed(&err) { - tokio::time::sleep(delay).await; + moq_clock::sleep(delay).await; } } } @@ -345,6 +345,7 @@ impl Listener { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; use std::time::Duration; diff --git a/rs/moq-tokio/src/transport.rs b/rs/moq-tokio/src/transport.rs index 5f60ad295b9..575173ec928 100644 --- a/rs/moq-tokio/src/transport.rs +++ b/rs/moq-tokio/src/transport.rs @@ -941,6 +941,7 @@ impl GroupedSend for qmux::SendStream { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use std::sync::{ Arc, Mutex, diff --git a/rs/moq-tokio/src/unix.rs b/rs/moq-tokio/src/unix.rs index 125651c0ceb..4cbd528e0e1 100644 --- a/rs/moq-tokio/src/unix.rs +++ b/rs/moq-tokio/src/unix.rs @@ -383,7 +383,7 @@ impl Listener { } Err(err) => { if let Some(delay) = self.health.failed(&err) { - tokio::time::sleep(delay).await; + moq_clock::sleep(delay).await; } } } diff --git a/rs/moq-tokio/src/webrtc.rs b/rs/moq-tokio/src/webrtc.rs index 5664d861797..01c86875102 100644 --- a/rs/moq-tokio/src/webrtc.rs +++ b/rs/moq-tokio/src/webrtc.rs @@ -21,7 +21,7 @@ use std::net::{IpAddr, SocketAddr}; use std::str::FromStr; use std::sync::{Arc, Mutex}; -use std::time::{Duration, Instant}; +use std::time::Duration; use bytes::Bytes; use str0m::Rtc; @@ -811,7 +811,7 @@ async fn next_write(writes: Option<&mut mpsc::Receiver>) -> Option /// A str0m connection with this socket's host candidates. fn rtc(locals: &[SocketAddr]) -> Result { - let mut rtc = Rtc::builder().build(Instant::now()); + let mut rtc = Rtc::builder().build(moq_clock::now().into_std()); for &addr in locals { let candidate = str0m::Candidate::host(addr, "udp").map_err(|err| Error::Candidate(err.to_string()))?; rtc.add_local_candidate(candidate); @@ -959,4 +959,5 @@ async fn mdns(host: &str) -> Result { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests; diff --git a/rs/moq-tokio/src/webrtc/tests.rs b/rs/moq-tokio/src/webrtc/tests.rs index b3afab026bb..865bd21af1d 100644 --- a/rs/moq-tokio/src/webrtc/tests.rs +++ b/rs/moq-tokio/src/webrtc/tests.rs @@ -1,5 +1,5 @@ use std::net::{IpAddr, Ipv4Addr}; -use std::time::Duration; +use std::time::{Duration, Instant}; use super::*; diff --git a/rs/moq-tokio/src/websocket.rs b/rs/moq-tokio/src/websocket.rs index 7dee4958e57..b8af49bef77 100644 --- a/rs/moq-tokio/src/websocket.rs +++ b/rs/moq-tokio/src/websocket.rs @@ -151,7 +151,7 @@ where { let deadline = options .timeout - .and_then(|timeout| tokio::time::Instant::now().checked_add(timeout)); + .and_then(|timeout| moq_clock::now().checked_add(timeout)); // A vanished peer sends no FIN. Ping and timeout bound the same stale-session // lifetime that QUIC's idle timeout bounds on the native path. let mut upgraded = qmux::ws::Upgraded::new(socket) @@ -412,7 +412,7 @@ pub(crate) async fn connect( // TODO if let chain match resolved.delay { delay if !delay.is_zero() && !WEBSOCKET_WON.lock().unwrap().contains(&key) => { - tokio::time::sleep(delay).await; + moq_clock::sleep(delay).await; tracing::debug!(peer = %crate::connect::Endpoint(&url), delay_ms = %delay.as_millis(), "QUIC not yet connected, attempting WebSocket fallback"); } _ => {} @@ -745,7 +745,7 @@ impl Listener { } Err(err) => { if let Some(delay) = self.health.failed(&err) { - tokio::time::sleep(delay).await; + moq_clock::sleep(delay).await; } } } diff --git a/rs/moq-tokio/tests/integration/main.rs b/rs/moq-tokio/tests/integration/main.rs index 6e263fb089d..60a4ad58372 100644 --- a/rs/moq-tokio/tests/integration/main.rs +++ b/rs/moq-tokio/tests/integration/main.rs @@ -2,6 +2,7 @@ //! //! Each `tests/*.rs` file is its own crate that links this package and its //! dependencies again, so add new integration tests here as a module. +#![allow(clippy::disallowed_methods, clippy::disallowed_types)] mod backend; mod broadcast; diff --git a/rs/moq-transcode/clippy.toml b/rs/moq-transcode/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/moq-transcode/clippy.toml @@ -0,0 +1,23 @@ +# Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. +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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-transcode/src/active.rs b/rs/moq-transcode/src/active.rs index 4d260e0cd13..e380cf2d79c 100644 --- a/rs/moq-transcode/src/active.rs +++ b/rs/moq-transcode/src/active.rs @@ -358,6 +358,7 @@ fn next_update(state: &State, seen: &BTreeMap) -> Option { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use std::time::Duration; diff --git a/rs/moq-transcode/src/catalog.rs b/rs/moq-transcode/src/catalog.rs index d74b55fe592..19d4057ab49 100644 --- a/rs/moq-transcode/src/catalog.rs +++ b/rs/moq-transcode/src/catalog.rs @@ -410,6 +410,7 @@ pub(crate) fn populate( } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use hang::catalog::H264; diff --git a/rs/moq-transcode/src/lib.rs b/rs/moq-transcode/src/lib.rs index ece4aa834b3..6456a4a0b80 100644 --- a/rs/moq-transcode/src/lib.rs +++ b/rs/moq-transcode/src/lib.rs @@ -210,6 +210,7 @@ impl Transcoder { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { use super::*; diff --git a/rs/moq-v4l/clippy.toml b/rs/moq-v4l/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/moq-v4l/clippy.toml @@ -0,0 +1,23 @@ +# Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. +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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-video/Cargo.toml b/rs/moq-video/Cargo.toml index 1223c402e98..50a8bf04cab 100644 --- a/rs/moq-video/Cargo.toml +++ b/rs/moq-video/Cargo.toml @@ -124,6 +124,7 @@ kio = { workspace = true, optional = true } # libvpx bindings for the `vpx` feature. The library itself comes from the build # host; see the feature above. libvpx-native-sys = { version = "5.0.17", optional = true } +moq-clock = { workspace = true } moq-mux = { workspace = true } moq-net = { workspace = true } # Vendored, statically linked software H.264 fallback (no system dependency). diff --git a/rs/moq-video/clippy.toml b/rs/moq-video/clippy.toml new file mode 100644 index 00000000000..d5a7b48f913 --- /dev/null +++ b/rs/moq-video/clippy.toml @@ -0,0 +1,23 @@ +# Production uses the ambient clock; legacy test-only clock cleanup is tracked separately. +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()" }, + { path = "std::time::SystemTime::now", reason = "read the ambient clock: moq_clock::wall()" }, + { path = "std::time::SystemTime::elapsed", reason = "wall time never measures elapsed time" }, + { path = "std::thread::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::Instant::now", reason = "read the ambient clock: moq_clock::now()" }, + { path = "tokio::time::sleep", reason = "sleep on the ambient clock: moq_clock::sleep()" }, + { path = "tokio::time::sleep_until", reason = "sleep on the ambient clock: moq_clock::sleep_until()" }, + { path = "tokio::time::timeout", reason = "use the ambient clock: moq_clock::timeout()" }, + { path = "tokio::time::interval", reason = "use the ambient clock: moq_clock::interval()" }, + { path = "tokio::time::timeout_at", reason = "use deadlines from the ambient clock" }, + { path = "tokio::time::interval_at", reason = "tick on the ambient clock" }, +] + +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" }, + { path = "tokio::time::Interval", reason = "use moq_clock::Interval" }, +] diff --git a/rs/moq-video/examples/encode-presets.rs b/rs/moq-video/examples/encode-presets.rs index 17d626af9b7..5be2de5a5d1 100644 --- a/rs/moq-video/examples/encode-presets.rs +++ b/rs/moq-video/examples/encode-presets.rs @@ -19,6 +19,7 @@ //! times the input's size on disk. //! //! Hardware on another machine needs its own run; nothing here extrapolates. +#![allow(clippy::disallowed_methods, clippy::disallowed_types)] use std::time::{Duration, Instant}; diff --git a/rs/moq-video/src/capture/avfoundation.rs b/rs/moq-video/src/capture/avfoundation.rs index d908e5bad6d..436fe31f54c 100644 --- a/rs/moq-video/src/capture/avfoundation.rs +++ b/rs/moq-video/src/capture/avfoundation.rs @@ -128,7 +128,7 @@ pub(super) async fn open(config: &Config, device: Option<&str>) -> Result frame, Ok(Err(error)) => return Err(error), Ok(Ok(None)) | Err(_) => { @@ -181,7 +181,7 @@ async fn ensure_camera_access(media: &AVMediaType) -> Result<(), Error> { }); unsafe { AVCaptureDevice::requestAccessForMediaType_completionHandler(media, &handler) }; - return match tokio::time::timeout(ACCESS_TIMEOUT, rx).await { + return match moq_clock::timeout(ACCESS_TIMEOUT, rx).await { Ok(Ok(true)) => Ok(()), Ok(Ok(false)) => Err(Error::PermissionDenied( "camera access; enable it in System Settings > Privacy & Security > Camera".to_string(), diff --git a/rs/moq-video/src/capture/channel.rs b/rs/moq-video/src/capture/channel.rs index a80a9d0ca7f..94029d03c00 100644 --- a/rs/moq-video/src/capture/channel.rs +++ b/rs/moq-video/src/capture/channel.rs @@ -8,8 +8,8 @@ //! the [`Stream`](super::Stream) drops, the device is released, and no //! blocking thread is left pinned. +use moq_clock::Instant; use std::sync::{Arc, Mutex}; -use std::time::Instant; use tokio::sync::Notify; diff --git a/rs/moq-video/src/capture/mod.rs b/rs/moq-video/src/capture/mod.rs index 38c066d558c..8fcba21796e 100644 --- a/rs/moq-video/src/capture/mod.rs +++ b/rs/moq-video/src/capture/mod.rs @@ -397,7 +397,7 @@ impl Synthetic { } /// Deliver a frame acquired at `captured`. - pub(crate) fn push_at(&self, surface: crate::frame::Surface, captured: std::time::Instant) { + pub(crate) fn push_at(&self, surface: crate::frame::Surface, captured: moq_clock::Instant) { self.chan.push_at(surface, captured); } diff --git a/rs/moq-video/src/capture/pipewire.rs b/rs/moq-video/src/capture/pipewire.rs index 6e88c035965..46b8644253f 100644 --- a/rs/moq-video/src/capture/pipewire.rs +++ b/rs/moq-video/src/capture/pipewire.rs @@ -180,7 +180,7 @@ async fn start(config: &Config, capture: Capture, session: Option) _session: session, }; - let geo = match tokio::time::timeout(FORMAT_TIMEOUT, geo_rx).await { + let geo = match moq_clock::timeout(FORMAT_TIMEOUT, geo_rx).await { Ok(Ok(result)) => result?, Ok(Err(_)) => { return Err(Error::Codec(anyhow::anyhow!( @@ -195,7 +195,7 @@ async fn start(config: &Config, capture: Capture, session: Option) } }; - let first = match tokio::time::timeout(FIRST_FRAME_TIMEOUT, chan.recv()).await { + let first = match moq_clock::timeout(FIRST_FRAME_TIMEOUT, chan.recv()).await { Ok(Ok(Some(frame))) => frame, Ok(Err(error)) => return Err(error), Ok(Ok(None)) | Err(_) => { diff --git a/rs/moq-video/src/capture/screencapture.rs b/rs/moq-video/src/capture/screencapture.rs index e42d87f6371..675a00b72c9 100644 --- a/rs/moq-video/src/capture/screencapture.rs +++ b/rs/moq-video/src/capture/screencapture.rs @@ -191,7 +191,7 @@ async fn open(config: &Config, filter: &SCContentFilter, size: (u32, u32)) -> Re }; let label = config.source.label(); - let first = match tokio::time::timeout(FIRST_FRAME_TIMEOUT, chan.recv()).await { + let first = match moq_clock::timeout(FIRST_FRAME_TIMEOUT, chan.recv()).await { Ok(Ok(Some(frame))) => frame, Ok(Err(error)) => return Err(error), Ok(Ok(None)) | Err(_) => { @@ -376,7 +376,7 @@ async fn shareable_content() -> Result, Error> { }); unsafe { SCShareableContent::getShareableContentWithCompletionHandler(&handler) }; - match tokio::time::timeout(ASYNC_TIMEOUT, rx).await { + match moq_clock::timeout(ASYNC_TIMEOUT, rx).await { Ok(Ok(Ok(content))) => Ok(content.0), Ok(Ok(Err(msg))) => Err(Error::Codec(anyhow::anyhow!("shareable content: {msg}"))), Ok(Err(_)) => Err(Error::Codec(anyhow::anyhow!("shareable content handler dropped"))), @@ -398,7 +398,7 @@ async fn start_capture(stream: &SCStream) -> Result<(), Error> { }); unsafe { stream.startCaptureWithCompletionHandler(Some(&handler)) }; - match tokio::time::timeout(ASYNC_TIMEOUT, rx).await { + match moq_clock::timeout(ASYNC_TIMEOUT, rx).await { Ok(Ok(None)) => Ok(()), Ok(Ok(Some(msg))) => Err(Error::Codec(anyhow::anyhow!("start capture: {msg}"))), Ok(Err(_)) => Err(Error::Codec(anyhow::anyhow!("start-capture handler dropped"))), diff --git a/rs/moq-video/src/capture/settle.rs b/rs/moq-video/src/capture/settle.rs index 9cbcb049b9a..8336fc40de6 100644 --- a/rs/moq-video/src/capture/settle.rs +++ b/rs/moq-video/src/capture/settle.rs @@ -8,7 +8,8 @@ //! again. So hold instead: once the geometry moves, stop capturing but keep //! polling, and only end once it has stayed put. -use std::time::{Duration, Instant}; +use moq_clock::Instant; +use std::time::Duration; /// How long a new geometry has to hold still before the stream ends. /// diff --git a/rs/moq-video/src/capture/wgc.rs b/rs/moq-video/src/capture/wgc.rs index fd688ef965e..3a23d8a7844 100644 --- a/rs/moq-video/src/capture/wgc.rs +++ b/rs/moq-video/src/capture/wgc.rs @@ -2,7 +2,9 @@ //! Native API calls live separately so the stop/wakeup contract runs in host CI. use std::sync::{Condvar, Mutex}; -use std::time::{Duration, Instant}; +use std::time::Duration; + +use moq_clock::Instant; use moq_net::Timestamp; diff --git a/rs/moq-video/src/capture/wgc/native.rs b/rs/moq-video/src/capture/wgc/native.rs index 19843fa674d..157493b7919 100644 --- a/rs/moq-video/src/capture/wgc/native.rs +++ b/rs/moq-video/src/capture/wgc/native.rs @@ -3,7 +3,9 @@ use std::ffi::c_void; use std::sync::Arc; use std::thread::JoinHandle; -use std::time::{Duration, Instant}; +use std::time::Duration; + +use moq_clock::Instant; use windows::Foundation::{Metadata::ApiInformation, TypedEventHandler}; use windows::Graphics::Capture::{ diff --git a/rs/moq-video/src/capture/x11.rs b/rs/moq-video/src/capture/x11.rs index 8af750e2d5f..75cf0437614 100644 --- a/rs/moq-video/src/capture/x11.rs +++ b/rs/moq-video/src/capture/x11.rs @@ -7,10 +7,11 @@ //! memory. It is also the fallback when the `pipewire` feature is disabled //! on an X11 desktop. +use moq_clock::Instant; use std::os::fd::AsRawFd; use std::ptr::NonNull; use std::sync::Arc; -use std::time::{Duration, Instant}; +use std::time::Duration; use x11rb::connection::{Connection, RequestConnection}; use x11rb::protocol::Event; @@ -326,6 +327,8 @@ impl Capture { fn read(&mut self) -> Result { let now = Instant::now(); if self.next > now { + // The capture thread runs outside any runtime, so it blocks on the host clock. + #[allow(clippy::disallowed_methods)] std::thread::sleep(self.next - now); } self.next = Instant::now() + self.interval; diff --git a/rs/moq-video/src/decode/backend/v4l2.rs b/rs/moq-video/src/decode/backend/v4l2.rs index 9a76f27491e..38e2379dc68 100644 --- a/rs/moq-video/src/decode/backend/v4l2.rs +++ b/rs/moq-video/src/decode/backend/v4l2.rs @@ -32,8 +32,9 @@ //! sequence follows the kernel's stateful decoder documentation and an //! implementation that also ran on a Pi Zero 2 W and a Pi 3. +use moq_clock::Instant; use std::collections::VecDeque; -use std::time::{Duration, Instant}; +use std::time::Duration; use bytes::Bytes; use moq_net::Timestamp; diff --git a/rs/moq-video/src/decode/consumer.rs b/rs/moq-video/src/decode/consumer.rs index e982a8ac425..344e5adf671 100644 --- a/rs/moq-video/src/decode/consumer.rs +++ b/rs/moq-video/src/decode/consumer.rs @@ -5,8 +5,8 @@ use std::pin::Pin; use std::task::{Context, Poll, ready}; use hang::catalog::VideoConfig; +use moq_clock::Instant; use moq_mux::container::Read; -use tokio::time::Instant; use super::decoder::Config; use super::select::{Lane, Next, Selector}; @@ -188,7 +188,7 @@ impl Consumer { fn poll_read( &mut self, cx: &mut Context<'_>, - sleep: &mut Option>>, + sleep: &mut Option>>, ) -> Poll, Error>> { loop { let deadline = match self.selector.next(Instant::now()) { @@ -235,7 +235,7 @@ impl Consumer { let Some(deadline) = deadline else { return Poll::Pending; }; - let sleep = sleep.get_or_insert_with(|| Box::pin(tokio::time::sleep_until(deadline))); + let sleep = sleep.get_or_insert_with(|| Box::pin(moq_clock::sleep_until(deadline))); sleep.as_mut().reset(deadline); ready!(sleep.as_mut().poll(cx)); } @@ -372,6 +372,7 @@ impl Reader { #[cfg(test)] mod tests { #![cfg_attr(not(feature = "openh264"), allow(dead_code, unused_imports))] + #![allow(clippy::disallowed_methods, clippy::disallowed_types)] use bytes::Bytes; use moq_net::Timestamp; diff --git a/rs/moq-video/src/decode/select.rs b/rs/moq-video/src/decode/select.rs index 652c393f84b..85735aaf8ba 100644 --- a/rs/moq-video/src/decode/select.rs +++ b/rs/moq-video/src/decode/select.rs @@ -10,7 +10,7 @@ use std::collections::VecDeque; use std::time::Duration; -use tokio::time::Instant; +use moq_clock::Instant; use crate::Frame; diff --git a/rs/moq-video/src/encode/backend/v4l2.rs b/rs/moq-video/src/encode/backend/v4l2.rs index 61b868a8295..19888642539 100644 --- a/rs/moq-video/src/encode/backend/v4l2.rs +++ b/rs/moq-video/src/encode/backend/v4l2.rs @@ -34,8 +34,9 @@ //! from an implementation that also ran on a Pi Zero 2 W and a Pi 3; those two //! have not been re-run with this port. +use moq_clock::Instant; use std::collections::VecDeque; -use std::time::{Duration, Instant}; +use std::time::Duration; use bytes::{Bytes, BytesMut}; use moq_net::Timestamp; diff --git a/rs/moq-video/src/encode/producer.rs b/rs/moq-video/src/encode/producer.rs index 2d8ea2eb45f..f4007501bbd 100644 --- a/rs/moq-video/src/encode/producer.rs +++ b/rs/moq-video/src/encode/producer.rs @@ -831,6 +831,7 @@ fn map_capture_timestamp(epoch_micros: u64, timestamp: Timestamp) -> Result