From d7770fe2e961abb86402e801ab73aedb67d6e276 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 20 Oct 2026 17:55:52 -0700 Subject: [PATCH 1/9] quest(m1): claim time/crates Co-Authored-By: Claude Opus 5.5 From 25cf1b665d86333bb6463cf65f12c882b72fd374 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Tue, 20 Oct 2026 18:25:52 -0700 Subject: [PATCH 2/9] refactor(rs): move the remaining crates onto moq-clock Production clock reads and timers in hang, moq-audio, moq-video, moq-gst, moq-rtsp, moq-srt, moq-hls, moq-shaper, moq-boy, moq-cli, moq-tokio, moq-relay, moq-quic, and moq-bench now go through moq-clock, and each finished crate gets the per-crate clippy ratchet. moq-clock gains timeout_at and interval_at, mirroring tokio's. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 9 ++++++++ rs/hang/Cargo.toml | 1 + rs/hang/clippy.toml | 23 +++++++++++++++++++ rs/hang/examples/video.rs | 6 ++--- rs/libmoq/clippy.toml | 23 +++++++++++++++++++ rs/moq-audio/Cargo.toml | 1 + rs/moq-audio/clippy.toml | 23 +++++++++++++++++++ rs/moq-audio/src/aec.rs | 1 + rs/moq-audio/src/capture.rs | 2 +- rs/moq-audio/src/capture/buffer.rs | 2 ++ rs/moq-audio/src/capture/channel.rs | 4 +++- rs/moq-audio/src/capture/permission.rs | 2 +- rs/moq-audio/src/capture/screencapture.rs | 6 ++--- rs/moq-audio/src/decode/consumer.rs | 3 ++- rs/moq-audio/src/encode/capture.rs | 5 +++-- rs/moq-audio/src/encode/producer.rs | 1 + rs/moq-audio/src/playback/driver.rs | 6 ++++- rs/moq-audio/src/playback/mixer.rs | 1 + rs/moq-audio/tests/integration/main.rs | 1 + rs/moq-bench/Cargo.toml | 1 + rs/moq-bench/clippy.toml | 23 +++++++++++++++++++ rs/moq-bench/src/connection.rs | 9 ++++---- rs/moq-bench/src/host.rs | 6 +++-- rs/moq-bench/src/main.rs | 4 ++-- rs/moq-bench/src/stats.rs | 7 +++--- rs/moq-boy/Cargo.toml | 1 + rs/moq-boy/clippy.toml | 23 +++++++++++++++++++ rs/moq-boy/src/input.rs | 1 + rs/moq-boy/src/main.rs | 5 ++++- rs/moq-boy/src/stats.rs | 3 ++- rs/moq-boy/src/video.rs | 3 ++- rs/moq-c/clippy.toml | 23 +++++++++++++++++++ rs/moq-c/src/lib.rs | 1 + rs/moq-cli/benches/play_buffer.rs | 1 + rs/moq-cli/clippy.toml | 23 +++++++++++++++++++ rs/moq-cli/src/announced.rs | 1 + rs/moq-cli/src/archive.rs | 3 ++- rs/moq-cli/src/complete.rs | 3 ++- rs/moq-cli/src/fetch.rs | 3 ++- rs/moq-cli/src/main.rs | 5 +++-- rs/moq-cli/src/play/media.rs | 3 ++- rs/moq-cli/src/play/metrics.rs | 6 ++--- rs/moq-cli/src/play/timeline.rs | 1 + rs/moq-cli/src/play/window.rs | 1 + rs/moq-cli/src/publish.rs | 5 +++-- rs/moq-cli/src/rtsp.rs | 2 +- rs/moq-cli/src/subscribe.rs | 8 +++---- rs/moq-cli/tests/integration/main.rs | 1 + rs/moq-clock/src/lib.rs | 5 ++++- rs/moq-clock/src/timer.rs | 25 ++++++++++++++++++--- rs/moq-e2ee/clippy.toml | 23 +++++++++++++++++++ rs/moq-e2ee/tests/transport.rs | 1 + rs/moq-flate/clippy.toml | 23 +++++++++++++++++++ rs/moq-gst/Cargo.toml | 1 + rs/moq-gst/clippy.toml | 23 +++++++++++++++++++ rs/moq-gst/src/sink/imp.rs | 2 +- rs/moq-gst/src/sink/pad.rs | 1 + rs/moq-gst/src/source/imp.rs | 1 + rs/moq-hls/Cargo.toml | 1 + rs/moq-hls/clippy.toml | 23 +++++++++++++++++++ rs/moq-hls/src/export/mod.rs | 6 +++-- rs/moq-hls/src/export/renditions.rs | 6 ++++- rs/moq-hls/src/import.rs | 11 ++++----- rs/moq-hls/src/server/mod.rs | 4 ++-- rs/moq-hls/src/server/routes.rs | 11 ++++----- rs/moq-json/benches/window.rs | 1 + rs/moq-json/clippy.toml | 23 +++++++++++++++++++ rs/moq-loc/clippy.toml | 23 +++++++++++++++++++ rs/moq-msf/clippy.toml | 23 +++++++++++++++++++ rs/moq-native/clippy.toml | 23 +++++++++++++++++++ rs/moq-nvenc/clippy.toml | 23 +++++++++++++++++++ rs/moq-pattern/clippy.toml | 23 +++++++++++++++++++ rs/moq-quic/clippy.toml | 23 +++++++++++++++++++ rs/moq-quic/src/bloom_token_log.rs | 1 + rs/moq-quic/src/config/mod.rs | 4 ++-- rs/moq-quic/src/config/transport.rs | 1 + rs/moq-quic/src/connection/streams/state.rs | 1 + rs/moq-quic/src/lib.rs | 1 + rs/moq-relay/benches/auth.rs | 1 + rs/moq-relay/clippy.toml | 23 +++++++++++++++++++ rs/moq-relay/src/acme.rs | 15 +++++++------ rs/moq-relay/src/auth.rs | 1 + rs/moq-relay/src/auth/refresh.rs | 1 + rs/moq-relay/src/cache.rs | 4 ++-- rs/moq-relay/src/cluster.rs | 9 ++++---- rs/moq-relay/src/internal.rs | 1 + rs/moq-relay/src/listener.rs | 2 +- rs/moq-relay/src/listener/idle.rs | 11 +++++---- rs/moq-relay/src/relay.rs | 5 +++-- rs/moq-relay/src/session.rs | 3 ++- rs/moq-relay/src/shutdown.rs | 6 +++-- rs/moq-relay/src/stun.rs | 3 ++- rs/moq-relay/src/uring.rs | 1 + rs/moq-relay/src/web.rs | 11 ++++----- rs/moq-relay/src/websocket.rs | 1 + rs/moq-relay/tests/drills.rs | 1 + rs/moq-relay/tests/integration/main.rs | 1 + rs/moq-rtsp/Cargo.toml | 6 ++--- rs/moq-rtsp/clippy.toml | 23 +++++++++++++++++++ rs/moq-rtsp/src/client.rs | 17 ++++++++------ rs/moq-shaper/Cargo.toml | 1 + rs/moq-shaper/clippy.toml | 23 +++++++++++++++++++ rs/moq-shaper/src/lib.rs | 6 +++-- rs/moq-shaper/src/main.rs | 4 ++-- rs/moq-sock/clippy.toml | 23 +++++++++++++++++++ rs/moq-sock/src/shard.rs | 1 + rs/moq-sock/tests/udp/main.rs | 1 + rs/moq-srt/clippy.toml | 23 +++++++++++++++++++ rs/moq-srt/src/dial.rs | 1 + rs/moq-srt/src/server.rs | 10 ++++++--- rs/moq-srt/src/ts.rs | 7 +++--- rs/moq-tokio/clippy.toml | 23 +++++++++++++++++++ rs/moq-tokio/examples/chat.rs | 4 ++-- rs/moq-tokio/examples/clock.rs | 4 ++-- rs/moq-tokio/src/client.rs | 5 +++-- rs/moq-tokio/src/connection.rs | 23 ++++++++++--------- rs/moq-tokio/src/connection/auth.rs | 3 ++- rs/moq-tokio/src/failover.rs | 11 ++++----- rs/moq-tokio/src/iroh.rs | 4 ++++ rs/moq-tokio/src/jemalloc.rs | 1 + rs/moq-tokio/src/listen.rs | 2 +- rs/moq-tokio/src/mdns.rs | 5 +++-- rs/moq-tokio/src/quic/backend.rs | 1 + rs/moq-tokio/src/quic/driver/mod.rs | 1 + rs/moq-tokio/src/quic/web/session.rs | 3 ++- rs/moq-tokio/src/resolve.rs | 6 +++-- rs/moq-tokio/src/server.rs | 25 ++++++++++----------- rs/moq-tokio/src/tcp.rs | 3 ++- rs/moq-tokio/src/transport.rs | 1 + rs/moq-tokio/src/unix.rs | 2 +- rs/moq-tokio/src/webrtc.rs | 7 ++++-- rs/moq-tokio/src/webrtc/tests.rs | 2 +- rs/moq-tokio/src/websocket.rs | 6 ++--- rs/moq-tokio/tests/integration/main.rs | 1 + rs/moq-transcode/clippy.toml | 23 +++++++++++++++++++ rs/moq-transcode/src/active.rs | 1 + rs/moq-transcode/src/catalog.rs | 1 + rs/moq-transcode/src/lib.rs | 1 + rs/moq-v4l/clippy.toml | 23 +++++++++++++++++++ rs/moq-video/Cargo.toml | 1 + rs/moq-video/clippy.toml | 23 +++++++++++++++++++ rs/moq-video/examples/encode-presets.rs | 1 + rs/moq-video/src/capture/avfoundation.rs | 4 ++-- rs/moq-video/src/capture/channel.rs | 2 +- rs/moq-video/src/capture/mod.rs | 2 +- rs/moq-video/src/capture/pipewire.rs | 4 ++-- rs/moq-video/src/capture/screencapture.rs | 6 ++--- rs/moq-video/src/capture/settle.rs | 3 ++- rs/moq-video/src/capture/wgc.rs | 4 +++- rs/moq-video/src/capture/wgc/native.rs | 4 +++- rs/moq-video/src/capture/x11.rs | 5 ++++- rs/moq-video/src/decode/backend/v4l2.rs | 3 ++- rs/moq-video/src/decode/consumer.rs | 7 +++--- rs/moq-video/src/decode/select.rs | 2 +- rs/moq-video/src/encode/backend/v4l2.rs | 3 ++- rs/moq-video/src/encode/producer.rs | 14 +++++------- rs/moq-video/src/frame.rs | 4 ++-- rs/moq-video/src/frame/cuda.rs | 1 + rs/moq-video/src/render/renderer.rs | 1 + rs/moq-video/src/v4l2.rs | 2 ++ rs/moq-wasm/clippy.toml | 23 +++++++++++++++++++ rs/uniffi-bindgen/clippy.toml | 23 +++++++++++++++++++ 162 files changed, 1018 insertions(+), 195 deletions(-) create mode 100644 rs/hang/clippy.toml create mode 100644 rs/libmoq/clippy.toml create mode 100644 rs/moq-audio/clippy.toml create mode 100644 rs/moq-bench/clippy.toml create mode 100644 rs/moq-boy/clippy.toml create mode 100644 rs/moq-c/clippy.toml create mode 100644 rs/moq-cli/clippy.toml create mode 100644 rs/moq-e2ee/clippy.toml create mode 100644 rs/moq-flate/clippy.toml create mode 100644 rs/moq-gst/clippy.toml create mode 100644 rs/moq-hls/clippy.toml create mode 100644 rs/moq-json/clippy.toml create mode 100644 rs/moq-loc/clippy.toml create mode 100644 rs/moq-msf/clippy.toml create mode 100644 rs/moq-native/clippy.toml create mode 100644 rs/moq-nvenc/clippy.toml create mode 100644 rs/moq-pattern/clippy.toml create mode 100644 rs/moq-quic/clippy.toml create mode 100644 rs/moq-relay/clippy.toml create mode 100644 rs/moq-rtsp/clippy.toml create mode 100644 rs/moq-shaper/clippy.toml create mode 100644 rs/moq-sock/clippy.toml create mode 100644 rs/moq-srt/clippy.toml create mode 100644 rs/moq-tokio/clippy.toml create mode 100644 rs/moq-transcode/clippy.toml create mode 100644 rs/moq-v4l/clippy.toml create mode 100644 rs/moq-video/clippy.toml create mode 100644 rs/moq-wasm/clippy.toml create mode 100644 rs/uniffi-bindgen/clippy.toml diff --git a/Cargo.lock b/Cargo.lock index 7c703cac3a9..1f2717db3fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3137,6 +3137,7 @@ dependencies = [ "derive_more 2.1.1", "hex", "kio 0.6.2", + "moq-clock", "moq-json", "moq-mux", "moq-net", @@ -4564,6 +4565,7 @@ dependencies = [ "fixed-resample", "hang", "kio 0.6.2", + "moq-clock", "moq-mux", "moq-net", "objc2 0.6.5", @@ -4645,6 +4647,7 @@ version = "0.0.1" dependencies = [ "anyhow", "humantime", + "moq-clock", "moq-net", "moq-tokio", "moq-uring", @@ -4667,6 +4670,7 @@ dependencies = [ "bytes", "hang", "moq-audio", + "moq-clock", "moq-json", "moq-mux", "moq-net", @@ -4854,6 +4858,7 @@ dependencies = [ "gstreamer", "hang", "moq-audio", + "moq-clock", "moq-json", "moq-mux", "moq-net", @@ -4877,6 +4882,7 @@ dependencies = [ "kio 0.6.2", "m3u8-rs", "moq-archive", + "moq-clock", "moq-json", "moq-mux", "moq-net", @@ -5214,6 +5220,7 @@ dependencies = [ "base64 0.23.1", "futures", "hang", + "moq-clock", "moq-mux", "moq-net", "moq-tokio", @@ -5234,6 +5241,7 @@ dependencies = [ "clap", "humantime", "humantime-serde", + "moq-clock", "rand 0.10.3", "serde", "serde_json", @@ -5470,6 +5478,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/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 b19552a05ea..5c32abb88a8 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 471ab8474a7..56231822595 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 03a1dc9d47a..f6009d38c43 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; @@ -935,6 +936,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); } @@ -1006,6 +1009,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 7239d2ddcb2..a05f3638f68 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"] } 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/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 e48a45ca0f5..6f32d874dd6 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 3ae442fc20f..05f137a0ad7 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 453b298ad98..9a730c3a9f1 100644 --- a/rs/moq-c/src/lib.rs +++ b/rs/moq-c/src/lib.rs @@ -49,4 +49,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 16a4611efd8..809824751dc 100644 --- a/rs/moq-cli/src/archive.rs +++ b/rs/moq-cli/src/archive.rs @@ -138,7 +138,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) { @@ -270,6 +270,7 @@ impl Tracks { } #[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 10005ec4e31..1eccdf6287f 100644 --- a/rs/moq-cli/src/main.rs +++ b/rs/moq-cli/src/main.rs @@ -287,13 +287,13 @@ struct Shutdown { /// Keep all stages and listener tasks alive while admitted sessions drain. async fn drain(shutdown: Shutdown, signals: &mut Signals) { - let deadline = tokio::time::Instant::now() + shutdown.observer.drain_timeout; + let deadline = moq_clock::now() + shutdown.observer.drain_timeout; shutdown.trigger.start(); tracing::info!(window = ?shutdown.observer.drain_timeout, "shutdown requested; draining sessions (signal again to exit immediately)"); tokio::select! { () = signals.recv() => {}, () = shutdown.observer.activity().close() => {}, - () = tokio::time::sleep_until(deadline) => {}, + () = moq_clock::sleep_until(deadline) => {}, } } @@ -984,6 +984,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 7aa884a844d..b692331c4f0 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..8d401eeac93 100644 --- a/rs/moq-cli/src/play/window.rs +++ b/rs/moq-cli/src/play/window.rs @@ -318,6 +318,7 @@ impl ApplicationHandler for App { } } // winit waits on the host clock, so the deadline converts at this boundary. + #[allow(clippy::disallowed_methods, clippy::disallowed_types)] Some(deadline) => event_loop.set_control_flow(ControlFlow::WaitUntil( std::time::Instant::now() + deadline.saturating_duration_since(now), )), diff --git a/rs/moq-cli/src/publish.rs b/rs/moq-cli/src/publish.rs index 23701932f0a..dd5a98b3068 100644 --- a/rs/moq-cli/src/publish.rs +++ b/rs/moq-cli/src/publish.rs @@ -570,7 +570,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(); // Run the read/decode loop so an error surfaces here rather than // dropping the decoder (and its tracks) with a bare Error::Dropped. @@ -589,7 +589,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() { log.sample(stats); } @@ -731,6 +731,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/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 df9a1881778..58396525e64 100644 --- a/rs/moq-cli/src/subscribe.rs +++ b/rs/moq-cli/src/subscribe.rs @@ -398,7 +398,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 release = |stats: &moq_mux::container::ts::stats::Export| { @@ -421,7 +421,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(); let counts = (stats.dropped, stats.trimmed, stats.gaps, stats.out_of_tolerance); if counts != reported { @@ -455,14 +455,14 @@ impl Subscribe { "TS passthrough release clock" ); }; - let mut sampled = tokio::time::Instant::now(); + let mut sampled = moq_clock::now(); let mut reported = (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 counts = (release.dropped(), release.out_of_tolerance()); if counts != reported { reported = counts; diff --git a/rs/moq-cli/tests/integration/main.rs b/rs/moq-cli/tests/integration/main.rs index 67dc72a93e3..f5812c7f86f 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/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/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 4cf02e10bda..0334536336a 100644 --- a/rs/moq-gst/Cargo.toml +++ b/rs/moq-gst/Cargo.toml @@ -20,6 +20,7 @@ anyhow = { workspace = true, features = ["backtrace"] } bytes = { workspace = true } gst = { package = "gstreamer", version = "0.24" } hang = { workspace = true } +moq-clock = { workspace = true } moq-json = { workspace = true } moq-mux = { workspace = true } moq-net = { workspace = 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 dc8d7581722..bb11e6832fd 100644 --- a/rs/moq-gst/src/sink/imp.rs +++ b/rs/moq-gst/src/sink/imp.rs @@ -709,7 +709,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()); diff --git a/rs/moq-gst/src/sink/pad.rs b/rs/moq-gst/src/sink/pad.rs index f6723f8f7f9..626cf705784 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 d97ea5c9637..2f912bfe3b1 100644 --- a/rs/moq-gst/src/source/imp.rs +++ b/rs/moq-gst/src/source/imp.rs @@ -1557,6 +1557,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 63f019c019b..bff17b67d5f 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; @@ -317,7 +318,7 @@ impl Broadcaster { Some(mpd::render_manifest( &mpd::Manifest { availability_start, - publish: SystemTime::now(), + publish: SystemTime::from(moq_clock::wall()), window: self.renditions.window(), finished, video, @@ -395,7 +396,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; @@ -579,6 +580,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 06cf273443f..ffd5253800d 100644 --- a/rs/moq-hls/src/export/renditions.rs +++ b/rs/moq-hls/src/export/renditions.rs @@ -281,7 +281,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 e7a889bf2a4..91b32d89079 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 2c820f30953..876c4648fde 100644 --- a/rs/moq-hls/src/server/mod.rs +++ b/rs/moq-hls/src/server/mod.rs @@ -113,14 +113,14 @@ impl Server { // Confirm a route covers the broadcast (and it is in scope) before resolving it. The // source resolves a rendition's sibling `broadcast` reference through the same origin. - tokio::time::timeout(RESOLVE_TIMEOUT, self.inner.origin.routed(name)) + moq_clock::timeout(RESOLVE_TIMEOUT, self.inner.origin.routed(name)) .await .ok() .flatten()?; 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()? diff --git a/rs/moq-hls/src/server/routes.rs b/rs/moq-hls/src/server/routes.rs index d3ca165078b..1d3b3d6dd0b 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) { @@ -271,7 +271,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(), @@ -363,7 +363,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) } @@ -426,6 +426,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-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 826d4d02eed..c33e1731dfb 100644 --- a/rs/moq-quic/src/config/mod.rs +++ b/rs/moq-quic/src/config/mod.rs @@ -676,11 +676,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 554080ef169..a7dc511fc21 100644 --- a/rs/moq-quic/src/config/transport.rs +++ b/rs/moq-quic/src/config/transport.rs @@ -651,6 +651,7 @@ impl QlogConfig { // The streamer's own epoch only times the events it stamps itself, which this // crate never asks it to; `QlogStream` stamps them on MoQ's clock instead. + #[allow(clippy::disallowed_methods, clippy::disallowed_types)] let mut streamer = QlogStreamer::new( self.title, self.description, diff --git a/rs/moq-quic/src/connection/streams/state.rs b/rs/moq-quic/src/connection/streams/state.rs index afdc4185bda..c028b2b2751 100644 --- a/rs/moq-quic/src/connection/streams/state.rs +++ b/rs/moq-quic/src/connection/streams/state.rs @@ -1174,6 +1174,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 173dd59ff17..74461196b72 100644 --- a/rs/moq-relay/src/auth.rs +++ b/rs/moq-relay/src/auth.rs @@ -1108,6 +1108,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 c28c8304f59..6f99592b5f3 100644 --- a/rs/moq-relay/src/cluster.rs +++ b/rs/moq-relay/src/cluster.rs @@ -1825,10 +1825,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; @@ -1961,7 +1961,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(); @@ -1977,7 +1977,7 @@ impl Cluster { } } - tokio::time::sleep(backoff).await; + moq_clock::sleep(backoff).await; } } @@ -2300,6 +2300,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 34e2674b852..6ccbb1aa8f7 100644 --- a/rs/moq-relay/src/relay.rs +++ b/rs/moq-relay/src/relay.rs @@ -771,10 +771,10 @@ async fn drain(trigger: shutdown::Trigger, mut shutdown: shutdown::Observer, sig return Ok(()); } _ = shutdown.drained() => {} - _ = tokio::time::sleep_until(deadline) => {} + _ = moq_clock::sleep_until(deadline) => {} } - let elapsed = tokio::time::Instant::now().saturating_duration_since(deadline - window); + let elapsed = moq_clock::now().saturating_duration_since(deadline - window); match shutdown.tally() { shutdown::Tally { live: 0, forced: 0, .. } => { tracing::info!(?elapsed, "drain ended with no established sessions; exiting") @@ -851,6 +851,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 8b0183662be..a1afc6c6fbb 100644 --- a/rs/moq-relay/src/shutdown.rs +++ b/rs/moq-relay/src/shutdown.rs @@ -12,7 +12,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. @@ -128,7 +129,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, } } @@ -250,6 +251,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 e391b6eafec..359dba0be52 100644 --- a/rs/moq-relay/src/uring.rs +++ b/rs/moq-relay/src/uring.rs @@ -837,6 +837,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 7a4b246fdc8..564177dd493 100644 --- a/rs/moq-relay/src/web.rs +++ b/rs/moq-relay/src/web.rs @@ -344,7 +344,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 } @@ -1064,11 +1064,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. @@ -1119,7 +1119,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, } @@ -1130,7 +1130,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), }, @@ -1172,6 +1172,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 69ac35ea3d2..eebba249405 100644 --- a/rs/moq-relay/tests/drills.rs +++ b/rs/moq-relay/tests/drills.rs @@ -24,6 +24,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 c8b52f43141..d31ddaeb20b 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-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..1806275e7e8 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,13 @@ struct Stream { track: Track, /// The previous frame's timestamp, in the stream's clock units since the session start, and /// when it arrived. + // retina stamps arrival on std's clock; only its own stamps are compared. + #[allow(clippy::disallowed_types)] last: Option<(i64, std::time::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, @@ -470,7 +472,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 +516,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 +545,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 b7933e45555..21842c5ce34 100644 --- a/rs/moq-shaper/src/lib.rs +++ b/rs/moq-shaper/src/lib.rs @@ -42,11 +42,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. /// @@ -895,7 +896,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]); @@ -1235,6 +1236,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 450f9028351..c0b65ac7377 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; @@ -598,8 +598,9 @@ pub(crate) async fn serve_subscribe( /// 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()); +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] +fn host_instant(at: Instant) -> std::time::Instant { + let (now, host) = (moq_net::time::now(), std::time::Instant::now()); match at.checked_duration_since(now) { Some(ahead) => host + ahead, None => host.checked_sub(now - at).unwrap_or(host), @@ -661,7 +662,10 @@ 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; 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 446c9f91712..53eea959ef6 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 623d443de72..56d491aff38 100644 --- a/rs/moq-tokio/src/connection.rs +++ b/rs/moq-tokio/src/connection.rs @@ -487,7 +487,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. @@ -827,7 +827,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 } @@ -863,7 +863,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. @@ -968,7 +968,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; } @@ -1086,7 +1086,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)))), }, @@ -1281,7 +1281,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, } @@ -1290,7 +1290,7 @@ impl Retry { fn new(initial: Duration) -> Self { Self { delay: initial, - start: tokio::time::Instant::now(), + start: moq_clock::now(), last_error: None, } } @@ -1316,7 +1316,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); @@ -1340,14 +1340,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())); } @@ -1417,7 +1417,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 @@ -1549,6 +1549,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 f6e5a194b24..ebeabaea0e9 100644 --- a/rs/moq-tokio/src/connection/auth.rs +++ b/rs/moq-tokio/src/connection/auth.rs @@ -310,7 +310,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(); @@ -389,6 +389,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 d30a1f5b010..ece74c5a03c 100644 --- a/rs/moq-tokio/src/listen.rs +++ b/rs/moq-tokio/src/listen.rs @@ -522,7 +522,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 18a31deba37..905f3a1c5b3 100644 --- a/rs/moq-tokio/src/mdns.rs +++ b/rs/moq-tokio/src/mdns.rs @@ -766,12 +766,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. @@ -825,6 +825,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 caab2d7a5db..6be9c4393c8 100644 --- a/rs/moq-tokio/src/quic/backend.rs +++ b/rs/moq-tokio/src/quic/backend.rs @@ -1036,6 +1036,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 5acc2455104..45f832c6b49 100644 --- a/rs/moq-tokio/src/quic/driver/mod.rs +++ b/rs/moq-tokio/src/quic/driver/mod.rs @@ -84,6 +84,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 b65d732209d..302e7611544 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 b84e07ee320..0d85083f629 100644 --- a/rs/moq-tokio/src/server.rs +++ b/rs/moq-tokio/src/server.rs @@ -905,9 +905,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?; @@ -1030,8 +1028,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?) } } @@ -1050,7 +1048,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, @@ -1069,7 +1067,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?; @@ -1091,7 +1089,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, } @@ -1105,7 +1103,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, { @@ -1127,7 +1125,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)(); @@ -1150,7 +1148,7 @@ impl Deadline { feature = "webrtc" ))] async fn within( - deadline: Option, + deadline: Option, handshake: impl Future>, ) -> crate::Result where @@ -1159,7 +1157,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()), } @@ -1545,7 +1543,7 @@ fn spawn_unix_loop( struct Incoming { transport: Transport, link: Link, - deadline: Option, + deadline: Option, active: moq_net::server::Active, } @@ -1936,6 +1934,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 9737ad42857..60e477b3e7c 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..331d998c466 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; @@ -810,8 +810,10 @@ async fn next_write(writes: Option<&mut mpsc::Receiver>) -> Option } /// A str0m connection with this socket's host candidates. +// str0m runs on std's clock, which moq-ice drives it with. +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] fn rtc(locals: &[SocketAddr]) -> Result { - let mut rtc = Rtc::builder().build(Instant::now()); + let mut rtc = Rtc::builder().build(std::time::Instant::now()); 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 +961,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 253b2c6f4b7..7c6a6e5deba 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 alpn; mod backend; 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..3d523992314 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)); } @@ -370,6 +370,7 @@ impl Reader { } #[cfg(test)] +#[allow(clippy::disallowed_methods, clippy::disallowed_types)] mod tests { #![cfg_attr(not(feature = "openh264"), allow(dead_code, unused_imports))] 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..9f8353576c1 100644 --- a/rs/moq-video/src/encode/producer.rs +++ b/rs/moq-video/src/encode/producer.rs @@ -829,6 +829,7 @@ fn map_capture_timestamp(epoch_micros: u64, timestamp: Timestamp) -> Result